three.webgpu.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800
  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, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, RenderTarget, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, PerspectiveCamera, CubeUVReflectionMapping, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, WebXRController, RAD2DEG, SRGBColorSpace, PCFShadowMap, Frustum, FrontSide, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, AddEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, ZeroFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, 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, NearestFilter, 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, CylinderGeometry, 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, 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, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, 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 monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. id: geometry.id,
  133. attributes: this.getAttributesData( geometry.attributes ),
  134. indexVersion: geometry.index ? geometry.index.version : null,
  135. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  136. },
  137. worldMatrix: object.matrixWorld.clone()
  138. };
  139. if ( object.center ) {
  140. data.center = object.center.clone();
  141. }
  142. if ( object.morphTargetInfluences ) {
  143. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  144. }
  145. if ( renderObject.bundle !== null ) {
  146. data.version = renderObject.bundle.version;
  147. }
  148. if ( data.material.transmission > 0 ) {
  149. const { width, height } = renderObject.context;
  150. data.bufferWidth = width;
  151. data.bufferHeight = height;
  152. }
  153. this.renderObjects.set( renderObject, data );
  154. }
  155. return data;
  156. }
  157. /**
  158. * Returns an attribute data structure holding the attributes versions for
  159. * monitoring.
  160. *
  161. * @param {Object} attributes - The geometry attributes.
  162. * @return {Object} An object for monitoring the versions of attributes.
  163. */
  164. getAttributesData( attributes ) {
  165. const attributesData = {};
  166. for ( const name in attributes ) {
  167. const attribute = attributes[ name ];
  168. attributesData[ name ] = {
  169. version: attribute.version
  170. };
  171. }
  172. return attributesData;
  173. }
  174. /**
  175. * Returns `true` if the node builder's material uses
  176. * node properties.
  177. *
  178. * @param {NodeBuilder} builder - The current node builder.
  179. * @return {boolean} Whether the node builder's material uses node properties or not.
  180. */
  181. containsNode( builder ) {
  182. const material = builder.material;
  183. for ( const property in material ) {
  184. if ( material[ property ] && material[ property ].isNode )
  185. return true;
  186. }
  187. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  188. return true;
  189. return false;
  190. }
  191. /**
  192. * Returns a material data structure holding the material property values for
  193. * monitoring.
  194. *
  195. * @param {Material} material - The material.
  196. * @return {Object} An object for monitoring material properties.
  197. */
  198. getMaterialData( material ) {
  199. const data = {};
  200. for ( const property of this.refreshUniforms ) {
  201. const value = material[ property ];
  202. if ( value === null || value === undefined ) continue;
  203. if ( typeof value === 'object' && value.clone !== undefined ) {
  204. if ( value.isTexture === true ) {
  205. data[ property ] = { id: value.id, version: value.version };
  206. } else {
  207. data[ property ] = value.clone();
  208. }
  209. } else {
  210. data[ property ] = value;
  211. }
  212. }
  213. return data;
  214. }
  215. /**
  216. * Returns `true` if the given render object has not changed its state.
  217. *
  218. * @param {RenderObject} renderObject - The render object.
  219. * @return {boolean} Whether the given render object has changed its state or not.
  220. */
  221. equals( renderObject ) {
  222. const { object, material, geometry } = renderObject;
  223. const renderObjectData = this.getRenderObjectData( renderObject );
  224. // world matrix
  225. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  226. renderObjectData.worldMatrix.copy( object.matrixWorld );
  227. return false;
  228. }
  229. // material
  230. const materialData = renderObjectData.material;
  231. for ( const property in materialData ) {
  232. const value = materialData[ property ];
  233. const mtlValue = material[ property ];
  234. if ( value.equals !== undefined ) {
  235. if ( value.equals( mtlValue ) === false ) {
  236. value.copy( mtlValue );
  237. return false;
  238. }
  239. } else if ( mtlValue.isTexture === true ) {
  240. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  241. value.id = mtlValue.id;
  242. value.version = mtlValue.version;
  243. return false;
  244. }
  245. } else if ( value !== mtlValue ) {
  246. materialData[ property ] = mtlValue;
  247. return false;
  248. }
  249. }
  250. if ( materialData.transmission > 0 ) {
  251. const { width, height } = renderObject.context;
  252. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  253. renderObjectData.bufferWidth = width;
  254. renderObjectData.bufferHeight = height;
  255. return false;
  256. }
  257. }
  258. // geometry
  259. const storedGeometryData = renderObjectData.geometry;
  260. const attributes = geometry.attributes;
  261. const storedAttributes = storedGeometryData.attributes;
  262. const storedAttributeNames = Object.keys( storedAttributes );
  263. const currentAttributeNames = Object.keys( attributes );
  264. if ( storedGeometryData.id !== geometry.id ) {
  265. storedGeometryData.id = geometry.id;
  266. return false;
  267. }
  268. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  269. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  270. return false;
  271. }
  272. // compare each attribute
  273. for ( const name of storedAttributeNames ) {
  274. const storedAttributeData = storedAttributes[ name ];
  275. const attribute = attributes[ name ];
  276. if ( attribute === undefined ) {
  277. // attribute was removed
  278. delete storedAttributes[ name ];
  279. return false;
  280. }
  281. if ( storedAttributeData.version !== attribute.version ) {
  282. storedAttributeData.version = attribute.version;
  283. return false;
  284. }
  285. }
  286. // check index
  287. const index = geometry.index;
  288. const storedIndexVersion = storedGeometryData.indexVersion;
  289. const currentIndexVersion = index ? index.version : null;
  290. if ( storedIndexVersion !== currentIndexVersion ) {
  291. storedGeometryData.indexVersion = currentIndexVersion;
  292. return false;
  293. }
  294. // check drawRange
  295. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  296. storedGeometryData.drawRange.start = geometry.drawRange.start;
  297. storedGeometryData.drawRange.count = geometry.drawRange.count;
  298. return false;
  299. }
  300. // morph targets
  301. if ( renderObjectData.morphTargetInfluences ) {
  302. let morphChanged = false;
  303. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  304. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  305. morphChanged = true;
  306. }
  307. }
  308. if ( morphChanged ) return true;
  309. }
  310. // center
  311. if ( renderObjectData.center ) {
  312. if ( renderObjectData.center.equals( object.center ) === false ) {
  313. renderObjectData.center.copy( object.center );
  314. return true;
  315. }
  316. }
  317. // bundle
  318. if ( renderObject.bundle !== null ) {
  319. renderObjectData.version = renderObject.bundle.version;
  320. }
  321. return true;
  322. }
  323. /**
  324. * Checks if the given render object requires a refresh.
  325. *
  326. * @param {RenderObject} renderObject - The render object.
  327. * @param {NodeFrame} nodeFrame - The current node frame.
  328. * @return {boolean} Whether the given render object requires a refresh or not.
  329. */
  330. needsRefresh( renderObject, nodeFrame ) {
  331. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  332. return true;
  333. const { renderId } = nodeFrame;
  334. if ( this.renderId !== renderId ) {
  335. this.renderId = renderId;
  336. return true;
  337. }
  338. const isStatic = renderObject.object.static === true;
  339. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  340. if ( isStatic || isBundle )
  341. return false;
  342. const notEqual = this.equals( renderObject ) !== true;
  343. return notEqual;
  344. }
  345. }
  346. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  347. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  348. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  349. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  350. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  351. function cyrb53( value, seed = 0 ) {
  352. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  353. if ( value instanceof Array ) {
  354. for ( let i = 0, val; i < value.length; i ++ ) {
  355. val = value[ i ];
  356. h1 = Math.imul( h1 ^ val, 2654435761 );
  357. h2 = Math.imul( h2 ^ val, 1597334677 );
  358. }
  359. } else {
  360. for ( let i = 0, ch; i < value.length; i ++ ) {
  361. ch = value.charCodeAt( i );
  362. h1 = Math.imul( h1 ^ ch, 2654435761 );
  363. h2 = Math.imul( h2 ^ ch, 1597334677 );
  364. }
  365. }
  366. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  367. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  368. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  369. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  370. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  371. }
  372. /**
  373. * Computes a hash for the given string.
  374. *
  375. * @method
  376. * @param {string} str - The string to be hashed.
  377. * @return {number} The hash.
  378. */
  379. const hashString = ( str ) => cyrb53( str );
  380. /**
  381. * Computes a hash for the given array.
  382. *
  383. * @method
  384. * @param {Array<number>} array - The array to be hashed.
  385. * @return {number} The hash.
  386. */
  387. const hashArray = ( array ) => cyrb53( array );
  388. /**
  389. * Computes a hash for the given list of parameters.
  390. *
  391. * @method
  392. * @param {...number} params - A list of parameters.
  393. * @return {number} The hash.
  394. */
  395. const hash$1 = ( ...params ) => cyrb53( params );
  396. /**
  397. * Computes a cache key for the given node.
  398. *
  399. * @method
  400. * @param {Object} object - The object to be hashed.
  401. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  402. * @return {number} The hash.
  403. */
  404. function getCacheKey$1( object, force = false ) {
  405. const values = [];
  406. if ( object.isNode === true ) {
  407. values.push( object.id );
  408. object = object.getSelf();
  409. }
  410. for ( const { property, childNode } of getNodeChildren( object ) ) {
  411. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  412. }
  413. return cyrb53( values );
  414. }
  415. /**
  416. * This generator function can be used to iterate over the node children
  417. * of the given object.
  418. *
  419. * @generator
  420. * @param {Object} node - The object to be hashed.
  421. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  422. * @yields {Object} A result node holding the property, index (if available) and the child node.
  423. */
  424. function* getNodeChildren( node, toJSON = false ) {
  425. for ( const property in node ) {
  426. // Ignore private properties.
  427. if ( property.startsWith( '_' ) === true ) continue;
  428. const object = node[ property ];
  429. if ( Array.isArray( object ) === true ) {
  430. for ( let i = 0; i < object.length; i ++ ) {
  431. const child = object[ i ];
  432. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  433. yield { property, index: i, childNode: child };
  434. }
  435. }
  436. } else if ( object && object.isNode === true ) {
  437. yield { property, childNode: object };
  438. } else if ( typeof object === 'object' ) {
  439. for ( const subProperty in object ) {
  440. const child = object[ subProperty ];
  441. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  442. yield { property, index: subProperty, childNode: child };
  443. }
  444. }
  445. }
  446. }
  447. }
  448. const typeFromLength = /*@__PURE__*/ new Map( [
  449. [ 1, 'float' ],
  450. [ 2, 'vec2' ],
  451. [ 3, 'vec3' ],
  452. [ 4, 'vec4' ],
  453. [ 9, 'mat3' ],
  454. [ 16, 'mat4' ]
  455. ] );
  456. const dataFromObject = /*@__PURE__*/ new WeakMap();
  457. /**
  458. * Returns the data type for the given the length.
  459. *
  460. * @method
  461. * @param {number} length - The length.
  462. * @return {string} The data type.
  463. */
  464. function getTypeFromLength( length ) {
  465. return typeFromLength.get( length );
  466. }
  467. /**
  468. * Returns the typed array for the given data type.
  469. *
  470. * @method
  471. * @param {string} type - The data type.
  472. * @return {TypedArray} The typed array.
  473. */
  474. function getTypedArrayFromType( type ) {
  475. // Handle component type for vectors and matrices
  476. if ( /[iu]?vec\d/.test( type ) ) {
  477. // Handle int vectors
  478. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  479. // Handle uint vectors
  480. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  481. // Default to float vectors
  482. return Float32Array;
  483. }
  484. // Handle matrices (always float)
  485. if ( /mat\d/.test( type ) ) return Float32Array;
  486. // Basic types
  487. if ( /float/.test( type ) ) return Float32Array;
  488. if ( /uint/.test( type ) ) return Uint32Array;
  489. if ( /int/.test( type ) ) return Int32Array;
  490. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  491. }
  492. /**
  493. * Returns the length for the given data type.
  494. *
  495. * @method
  496. * @param {string} type - The data type.
  497. * @return {number} The length.
  498. */
  499. function getLengthFromType( type ) {
  500. if ( /float|int|uint/.test( type ) ) return 1;
  501. if ( /vec2/.test( type ) ) return 2;
  502. if ( /vec3/.test( type ) ) return 3;
  503. if ( /vec4/.test( type ) ) return 4;
  504. if ( /mat2/.test( type ) ) return 4;
  505. if ( /mat3/.test( type ) ) return 9;
  506. if ( /mat4/.test( type ) ) return 16;
  507. console.error( 'THREE.TSL: Unsupported type:', type );
  508. }
  509. /**
  510. * Returns the data type for the given value.
  511. *
  512. * @method
  513. * @param {any} value - The value.
  514. * @return {?string} The data type.
  515. */
  516. function getValueType( value ) {
  517. if ( value === undefined || value === null ) return null;
  518. const typeOf = typeof value;
  519. if ( value.isNode === true ) {
  520. return 'node';
  521. } else if ( typeOf === 'number' ) {
  522. return 'float';
  523. } else if ( typeOf === 'boolean' ) {
  524. return 'bool';
  525. } else if ( typeOf === 'string' ) {
  526. return 'string';
  527. } else if ( typeOf === 'function' ) {
  528. return 'shader';
  529. } else if ( value.isVector2 === true ) {
  530. return 'vec2';
  531. } else if ( value.isVector3 === true ) {
  532. return 'vec3';
  533. } else if ( value.isVector4 === true ) {
  534. return 'vec4';
  535. } else if ( value.isMatrix2 === true ) {
  536. return 'mat2';
  537. } else if ( value.isMatrix3 === true ) {
  538. return 'mat3';
  539. } else if ( value.isMatrix4 === true ) {
  540. return 'mat4';
  541. } else if ( value.isColor === true ) {
  542. return 'color';
  543. } else if ( value instanceof ArrayBuffer ) {
  544. return 'ArrayBuffer';
  545. }
  546. return null;
  547. }
  548. /**
  549. * Returns the value/object for the given data type and parameters.
  550. *
  551. * @method
  552. * @param {string} type - The given type.
  553. * @param {...any} params - A parameter list.
  554. * @return {any} The value/object.
  555. */
  556. function getValueFromType( type, ...params ) {
  557. const last4 = type ? type.slice( -4 ) : undefined;
  558. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  559. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  560. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  561. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  562. }
  563. if ( type === 'color' ) {
  564. return new Color( ...params );
  565. } else if ( last4 === 'vec2' ) {
  566. return new Vector2( ...params );
  567. } else if ( last4 === 'vec3' ) {
  568. return new Vector3( ...params );
  569. } else if ( last4 === 'vec4' ) {
  570. return new Vector4( ...params );
  571. } else if ( last4 === 'mat2' ) {
  572. return new Matrix2( ...params );
  573. } else if ( last4 === 'mat3' ) {
  574. return new Matrix3( ...params );
  575. } else if ( last4 === 'mat4' ) {
  576. return new Matrix4( ...params );
  577. } else if ( type === 'bool' ) {
  578. return params[ 0 ] || false;
  579. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  580. return params[ 0 ] || 0;
  581. } else if ( type === 'string' ) {
  582. return params[ 0 ] || '';
  583. } else if ( type === 'ArrayBuffer' ) {
  584. return base64ToArrayBuffer( params[ 0 ] );
  585. }
  586. return null;
  587. }
  588. /**
  589. * Gets the object data that can be shared between different rendering steps.
  590. *
  591. * @param {Object} object - The object to get the data for.
  592. * @return {Object} The object data.
  593. */
  594. function getDataFromObject( object ) {
  595. let data = dataFromObject.get( object );
  596. if ( data === undefined ) {
  597. data = {};
  598. dataFromObject.set( object, data );
  599. }
  600. return data;
  601. }
  602. /**
  603. * Converts the given array buffer to a Base64 string.
  604. *
  605. * @method
  606. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  607. * @return {string} The Base64 string.
  608. */
  609. function arrayBufferToBase64( arrayBuffer ) {
  610. let chars = '';
  611. const array = new Uint8Array( arrayBuffer );
  612. for ( let i = 0; i < array.length; i ++ ) {
  613. chars += String.fromCharCode( array[ i ] );
  614. }
  615. return btoa( chars );
  616. }
  617. /**
  618. * Converts the given Base64 string to an array buffer.
  619. *
  620. * @method
  621. * @param {string} base64 - The Base64 string.
  622. * @return {ArrayBuffer} The array buffer.
  623. */
  624. function base64ToArrayBuffer( base64 ) {
  625. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  626. }
  627. var NodeUtils = /*#__PURE__*/Object.freeze({
  628. __proto__: null,
  629. arrayBufferToBase64: arrayBufferToBase64,
  630. base64ToArrayBuffer: base64ToArrayBuffer,
  631. getCacheKey: getCacheKey$1,
  632. getDataFromObject: getDataFromObject,
  633. getLengthFromType: getLengthFromType,
  634. getNodeChildren: getNodeChildren,
  635. getTypeFromLength: getTypeFromLength,
  636. getTypedArrayFromType: getTypedArrayFromType,
  637. getValueFromType: getValueFromType,
  638. getValueType: getValueType,
  639. hash: hash$1,
  640. hashArray: hashArray,
  641. hashString: hashString
  642. });
  643. /**
  644. * Possible shader stages.
  645. *
  646. * @property {string} VERTEX The vertex shader stage.
  647. * @property {string} FRAGMENT The fragment shader stage.
  648. */
  649. const NodeShaderStage = {
  650. VERTEX: 'vertex'};
  651. /**
  652. * Update types of a node.
  653. *
  654. * @property {string} NONE The update method is not executed.
  655. * @property {string} FRAME The update method is executed per frame.
  656. * @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.
  657. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  658. */
  659. const NodeUpdateType = {
  660. NONE: 'none',
  661. FRAME: 'frame',
  662. RENDER: 'render',
  663. OBJECT: 'object'
  664. };
  665. /**
  666. * Data types of a node.
  667. *
  668. * @property {string} BOOLEAN Boolean type.
  669. * @property {string} INTEGER Integer type.
  670. * @property {string} FLOAT Float type.
  671. * @property {string} VECTOR2 Two-dimensional vector type.
  672. * @property {string} VECTOR3 Three-dimensional vector type.
  673. * @property {string} VECTOR4 Four-dimensional vector type.
  674. * @property {string} MATRIX2 2x2 matrix type.
  675. * @property {string} MATRIX3 3x3 matrix type.
  676. * @property {string} MATRIX4 4x4 matrix type.
  677. */
  678. const NodeType = {
  679. BOOLEAN: 'bool',
  680. INTEGER: 'int',
  681. FLOAT: 'float',
  682. VECTOR2: 'vec2',
  683. VECTOR3: 'vec3',
  684. VECTOR4: 'vec4',
  685. MATRIX2: 'mat2',
  686. MATRIX3: 'mat3',
  687. MATRIX4: 'mat4'
  688. };
  689. /**
  690. * Access types of a node. These are relevant for compute and storage usage.
  691. *
  692. * @property {string} READ_ONLY Read-only access
  693. * @property {string} WRITE_ONLY Write-only access.
  694. * @property {string} READ_WRITE Read and write access.
  695. */
  696. const NodeAccess = {
  697. READ_ONLY: 'readOnly',
  698. WRITE_ONLY: 'writeOnly',
  699. READ_WRITE: 'readWrite',
  700. };
  701. const defaultShaderStages = [ 'fragment', 'vertex' ];
  702. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  703. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  704. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  705. let _nodeId = 0;
  706. /**
  707. * Base class for all nodes.
  708. *
  709. * @augments EventDispatcher
  710. */
  711. class Node extends EventDispatcher {
  712. static get type() {
  713. return 'Node';
  714. }
  715. /**
  716. * Constructs a new node.
  717. *
  718. * @param {?string} nodeType - The node type.
  719. */
  720. constructor( nodeType = null ) {
  721. super();
  722. /**
  723. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  724. *
  725. * @type {?string}
  726. * @default null
  727. */
  728. this.nodeType = nodeType;
  729. /**
  730. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  731. *
  732. * @type {string}
  733. * @default 'none'
  734. */
  735. this.updateType = NodeUpdateType.NONE;
  736. /**
  737. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  738. *
  739. * @type {string}
  740. * @default 'none'
  741. */
  742. this.updateBeforeType = NodeUpdateType.NONE;
  743. /**
  744. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  745. *
  746. * @type {string}
  747. * @default 'none'
  748. */
  749. this.updateAfterType = NodeUpdateType.NONE;
  750. /**
  751. * The UUID of the node.
  752. *
  753. * @type {string}
  754. * @readonly
  755. */
  756. this.uuid = MathUtils.generateUUID();
  757. /**
  758. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  759. *
  760. * @type {number}
  761. * @readonly
  762. * @default 0
  763. */
  764. this.version = 0;
  765. /**
  766. * Whether this node is global or not. This property is relevant for the internal
  767. * node caching system. All nodes which should be declared just once should
  768. * set this flag to `true` (a typical example is {@link AttributeNode}).
  769. *
  770. * @type {boolean}
  771. * @default false
  772. */
  773. this.global = false;
  774. /**
  775. * This flag can be used for type testing.
  776. *
  777. * @type {boolean}
  778. * @readonly
  779. * @default true
  780. */
  781. this.isNode = true;
  782. // private
  783. /**
  784. * The cache key of this node.
  785. *
  786. * @private
  787. * @type {?number}
  788. * @default null
  789. */
  790. this._cacheKey = null;
  791. /**
  792. * The cache key 's version.
  793. *
  794. * @private
  795. * @type {number}
  796. * @default 0
  797. */
  798. this._cacheKeyVersion = 0;
  799. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  800. }
  801. /**
  802. * Set this property to `true` when the node should be regenerated.
  803. *
  804. * @type {boolean}
  805. * @default false
  806. * @param {boolean} value
  807. */
  808. set needsUpdate( value ) {
  809. if ( value === true ) {
  810. this.version ++;
  811. }
  812. }
  813. /**
  814. * The type of the class. The value is usually the constructor name.
  815. *
  816. * @type {string}
  817. * @readonly
  818. */
  819. get type() {
  820. return this.constructor.type;
  821. }
  822. /**
  823. * Convenient method for defining {@link Node#update}.
  824. *
  825. * @param {Function} callback - The update method.
  826. * @param {string} updateType - The update type.
  827. * @return {Node} A reference to this node.
  828. */
  829. onUpdate( callback, updateType ) {
  830. this.updateType = updateType;
  831. this.update = callback.bind( this.getSelf() );
  832. return this;
  833. }
  834. /**
  835. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  836. * this method automatically sets the update type to `FRAME`.
  837. *
  838. * @param {Function} callback - The update method.
  839. * @return {Node} A reference to this node.
  840. */
  841. onFrameUpdate( callback ) {
  842. return this.onUpdate( callback, NodeUpdateType.FRAME );
  843. }
  844. /**
  845. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  846. * this method automatically sets the update type to `RENDER`.
  847. *
  848. * @param {Function} callback - The update method.
  849. * @return {Node} A reference to this node.
  850. */
  851. onRenderUpdate( callback ) {
  852. return this.onUpdate( callback, NodeUpdateType.RENDER );
  853. }
  854. /**
  855. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  856. * this method automatically sets the update type to `OBJECT`.
  857. *
  858. * @param {Function} callback - The update method.
  859. * @return {Node} A reference to this node.
  860. */
  861. onObjectUpdate( callback ) {
  862. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  863. }
  864. /**
  865. * Convenient method for defining {@link Node#updateReference}.
  866. *
  867. * @param {Function} callback - The update method.
  868. * @return {Node} A reference to this node.
  869. */
  870. onReference( callback ) {
  871. this.updateReference = callback.bind( this.getSelf() );
  872. return this;
  873. }
  874. /**
  875. * The `this` reference might point to a Proxy so this method can be used
  876. * to get the reference to the actual node instance.
  877. *
  878. * @return {Node} A reference to the node.
  879. */
  880. getSelf() {
  881. // Returns non-node object.
  882. return this.self || this;
  883. }
  884. /**
  885. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  886. * to such objects based on a given state (e.g. the current node frame or builder).
  887. *
  888. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  889. * @return {any} The updated reference.
  890. */
  891. updateReference( /*state*/ ) {
  892. return this;
  893. }
  894. /**
  895. * By default this method returns the value of the {@link Node#global} flag. This method
  896. * can be overwritten in derived classes if an analytical way is required to determine the
  897. * global status.
  898. *
  899. * @param {NodeBuilder} builder - The current node builder.
  900. * @return {boolean} Whether this node is global or not.
  901. */
  902. isGlobal( /*builder*/ ) {
  903. return this.global;
  904. }
  905. /**
  906. * Generator function that can be used to iterate over the child nodes.
  907. *
  908. * @generator
  909. * @yields {Node} A child node.
  910. */
  911. * getChildren() {
  912. for ( const { childNode } of getNodeChildren( this ) ) {
  913. yield childNode;
  914. }
  915. }
  916. /**
  917. * Calling this method dispatches the `dispose` event. This event can be used
  918. * to register event listeners for clean up tasks.
  919. */
  920. dispose() {
  921. this.dispatchEvent( { type: 'dispose' } );
  922. }
  923. /**
  924. * Callback for {@link Node#traverse}.
  925. *
  926. * @callback traverseCallback
  927. * @param {Node} node - The current node.
  928. */
  929. /**
  930. * Can be used to traverse through the node's hierarchy.
  931. *
  932. * @param {traverseCallback} callback - A callback that is executed per node.
  933. */
  934. traverse( callback ) {
  935. callback( this );
  936. for ( const childNode of this.getChildren() ) {
  937. childNode.traverse( callback );
  938. }
  939. }
  940. /**
  941. * Returns the cache key for this node.
  942. *
  943. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  944. * @return {number} The cache key of the node.
  945. */
  946. getCacheKey( force = false ) {
  947. force = force || this.version !== this._cacheKeyVersion;
  948. if ( force === true || this._cacheKey === null ) {
  949. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  950. this._cacheKeyVersion = this.version;
  951. }
  952. return this._cacheKey;
  953. }
  954. /**
  955. * Generate a custom cache key for this node.
  956. *
  957. * @return {number} The cache key of the node.
  958. */
  959. customCacheKey() {
  960. return 0;
  961. }
  962. /**
  963. * Returns the references to this node which is by default `this`.
  964. *
  965. * @return {Node} A reference to this node.
  966. */
  967. getScope() {
  968. return this;
  969. }
  970. /**
  971. * Returns the hash of the node which is used to identify the node. By default it's
  972. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  973. * depending on their implementation.
  974. *
  975. * @param {NodeBuilder} builder - The current node builder.
  976. * @return {string} The hash.
  977. */
  978. getHash( /*builder*/ ) {
  979. return this.uuid;
  980. }
  981. /**
  982. * Returns the update type of {@link Node#update}.
  983. *
  984. * @return {NodeUpdateType} The update type.
  985. */
  986. getUpdateType() {
  987. return this.updateType;
  988. }
  989. /**
  990. * Returns the update type of {@link Node#updateBefore}.
  991. *
  992. * @return {NodeUpdateType} The update type.
  993. */
  994. getUpdateBeforeType() {
  995. return this.updateBeforeType;
  996. }
  997. /**
  998. * Returns the update type of {@link Node#updateAfter}.
  999. *
  1000. * @return {NodeUpdateType} The update type.
  1001. */
  1002. getUpdateAfterType() {
  1003. return this.updateAfterType;
  1004. }
  1005. /**
  1006. * Certain types are composed of multiple elements. For example a `vec3`
  1007. * is composed of three `float` values. This method returns the type of
  1008. * these elements.
  1009. *
  1010. * @param {NodeBuilder} builder - The current node builder.
  1011. * @return {string} The type of the node.
  1012. */
  1013. getElementType( builder ) {
  1014. const type = this.getNodeType( builder );
  1015. const elementType = builder.getElementType( type );
  1016. return elementType;
  1017. }
  1018. /**
  1019. * Returns the node member type for the given name.
  1020. *
  1021. * @param {NodeBuilder} builder - The current node builder.
  1022. * @param {string} name - The name of the member.
  1023. * @return {string} The type of the node.
  1024. */
  1025. getMemberType( /*uilder, name*/ ) {
  1026. return 'void';
  1027. }
  1028. /**
  1029. * Returns the node's type.
  1030. *
  1031. * @param {NodeBuilder} builder - The current node builder.
  1032. * @return {string} The type of the node.
  1033. */
  1034. getNodeType( builder ) {
  1035. const nodeProperties = builder.getNodeProperties( this );
  1036. if ( nodeProperties.outputNode ) {
  1037. return nodeProperties.outputNode.getNodeType( builder );
  1038. }
  1039. return this.nodeType;
  1040. }
  1041. /**
  1042. * This method is used during the build process of a node and ensures
  1043. * equal nodes are not built multiple times but just once. For example if
  1044. * `attribute( 'uv' )` is used multiple times by the user, the build
  1045. * process makes sure to process just the first node.
  1046. *
  1047. * @param {NodeBuilder} builder - The current node builder.
  1048. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1049. */
  1050. getShared( builder ) {
  1051. const hash = this.getHash( builder );
  1052. const nodeFromHash = builder.getNodeFromHash( hash );
  1053. return nodeFromHash || this;
  1054. }
  1055. /**
  1056. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1057. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1058. * The output node must be returned in the `return` statement.
  1059. *
  1060. * @param {NodeBuilder} builder - The current node builder.
  1061. * @return {?Node} The output node.
  1062. */
  1063. setup( builder ) {
  1064. const nodeProperties = builder.getNodeProperties( this );
  1065. let index = 0;
  1066. for ( const childNode of this.getChildren() ) {
  1067. nodeProperties[ 'node' + index ++ ] = childNode;
  1068. }
  1069. // return a outputNode if exists or null
  1070. return nodeProperties.outputNode || null;
  1071. }
  1072. /**
  1073. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1074. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1075. *
  1076. * @param {NodeBuilder} builder - The current node builder.
  1077. */
  1078. analyze( builder ) {
  1079. const usageCount = builder.increaseUsage( this );
  1080. if ( usageCount === 1 ) {
  1081. // node flow children
  1082. const nodeProperties = builder.getNodeProperties( this );
  1083. for ( const childNode of Object.values( nodeProperties ) ) {
  1084. if ( childNode && childNode.isNode === true ) {
  1085. childNode.build( builder );
  1086. }
  1087. }
  1088. }
  1089. }
  1090. /**
  1091. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1092. * This state builds the output node and returns the resulting shader string.
  1093. *
  1094. * @param {NodeBuilder} builder - The current node builder.
  1095. * @param {?string} output - Can be used to define the output type.
  1096. * @return {?string} The generated shader string.
  1097. */
  1098. generate( builder, output ) {
  1099. const { outputNode } = builder.getNodeProperties( this );
  1100. if ( outputNode && outputNode.isNode === true ) {
  1101. return outputNode.build( builder, output );
  1102. }
  1103. }
  1104. /**
  1105. * The method can be implemented to update the node's internal state before it is used to render an object.
  1106. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1107. *
  1108. * @abstract
  1109. * @param {NodeFrame} frame - A reference to the current node frame.
  1110. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1111. */
  1112. updateBefore( /*frame*/ ) {
  1113. console.warn( 'Abstract function.' );
  1114. }
  1115. /**
  1116. * The method can be implemented to update the node's internal state after it was used to render an object.
  1117. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1118. *
  1119. * @abstract
  1120. * @param {NodeFrame} frame - A reference to the current node frame.
  1121. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1122. */
  1123. updateAfter( /*frame*/ ) {
  1124. console.warn( 'Abstract function.' );
  1125. }
  1126. /**
  1127. * The method can be implemented to update the node's internal state when it is used to render an object.
  1128. * The {@link Node#updateType} property defines how often the update is executed.
  1129. *
  1130. * @abstract
  1131. * @param {NodeFrame} frame - A reference to the current node frame.
  1132. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1133. */
  1134. update( /*frame*/ ) {
  1135. console.warn( 'Abstract function.' );
  1136. }
  1137. /**
  1138. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1139. * on the current build stage (setup, analyze or generate).
  1140. *
  1141. * @param {NodeBuilder} builder - The current node builder.
  1142. * @param {?string} output - Can be used to define the output type.
  1143. * @return {?string} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1144. */
  1145. build( builder, output = null ) {
  1146. const refNode = this.getShared( builder );
  1147. if ( this !== refNode ) {
  1148. return refNode.build( builder, output );
  1149. }
  1150. builder.addNode( this );
  1151. builder.addChain( this );
  1152. /* Build stages expected results:
  1153. - "setup" -> Node
  1154. - "analyze" -> null
  1155. - "generate" -> String
  1156. */
  1157. let result = null;
  1158. const buildStage = builder.getBuildStage();
  1159. if ( buildStage === 'setup' ) {
  1160. this.updateReference( builder );
  1161. const properties = builder.getNodeProperties( this );
  1162. if ( properties.initialized !== true ) {
  1163. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1164. properties.initialized = true;
  1165. const outputNode = this.setup( builder ); // return a node or null
  1166. const isNodeOutput = outputNode && outputNode.isNode === true;
  1167. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1168. // !! no outputNode !!
  1169. //outputNode = builder.stack;
  1170. }*/
  1171. for ( const childNode of Object.values( properties ) ) {
  1172. if ( childNode && childNode.isNode === true ) {
  1173. childNode.build( builder );
  1174. }
  1175. }
  1176. if ( isNodeOutput ) {
  1177. outputNode.build( builder );
  1178. }
  1179. properties.outputNode = outputNode;
  1180. }
  1181. } else if ( buildStage === 'analyze' ) {
  1182. this.analyze( builder );
  1183. } else if ( buildStage === 'generate' ) {
  1184. const isGenerateOnce = this.generate.length === 1;
  1185. if ( isGenerateOnce ) {
  1186. const type = this.getNodeType( builder );
  1187. const nodeData = builder.getDataFromNode( this );
  1188. result = nodeData.snippet;
  1189. if ( result === undefined ) {
  1190. result = this.generate( builder ) || '';
  1191. nodeData.snippet = result;
  1192. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1193. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1194. }
  1195. result = builder.format( result, type, output );
  1196. } else {
  1197. result = this.generate( builder, output ) || '';
  1198. }
  1199. }
  1200. builder.removeChain( this );
  1201. builder.addSequentialNode( this );
  1202. return result;
  1203. }
  1204. /**
  1205. * Returns the child nodes as a JSON object.
  1206. *
  1207. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1208. */
  1209. getSerializeChildren() {
  1210. return getNodeChildren( this );
  1211. }
  1212. /**
  1213. * Serializes the node to JSON.
  1214. *
  1215. * @param {Object} json - The output JSON object.
  1216. */
  1217. serialize( json ) {
  1218. const nodeChildren = this.getSerializeChildren();
  1219. const inputNodes = {};
  1220. for ( const { property, index, childNode } of nodeChildren ) {
  1221. if ( index !== undefined ) {
  1222. if ( inputNodes[ property ] === undefined ) {
  1223. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1224. }
  1225. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1226. } else {
  1227. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1228. }
  1229. }
  1230. if ( Object.keys( inputNodes ).length > 0 ) {
  1231. json.inputNodes = inputNodes;
  1232. }
  1233. }
  1234. /**
  1235. * Deserializes the node from the given JSON.
  1236. *
  1237. * @param {Object} json - The JSON object.
  1238. */
  1239. deserialize( json ) {
  1240. if ( json.inputNodes !== undefined ) {
  1241. const nodes = json.meta.nodes;
  1242. for ( const property in json.inputNodes ) {
  1243. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1244. const inputArray = [];
  1245. for ( const uuid of json.inputNodes[ property ] ) {
  1246. inputArray.push( nodes[ uuid ] );
  1247. }
  1248. this[ property ] = inputArray;
  1249. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1250. const inputObject = {};
  1251. for ( const subProperty in json.inputNodes[ property ] ) {
  1252. const uuid = json.inputNodes[ property ][ subProperty ];
  1253. inputObject[ subProperty ] = nodes[ uuid ];
  1254. }
  1255. this[ property ] = inputObject;
  1256. } else {
  1257. const uuid = json.inputNodes[ property ];
  1258. this[ property ] = nodes[ uuid ];
  1259. }
  1260. }
  1261. }
  1262. }
  1263. /**
  1264. * Serializes the node into the three.js JSON Object/Scene format.
  1265. *
  1266. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1267. * @return {Object} The serialized node.
  1268. */
  1269. toJSON( meta ) {
  1270. const { uuid, type } = this;
  1271. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1272. if ( isRoot ) {
  1273. meta = {
  1274. textures: {},
  1275. images: {},
  1276. nodes: {}
  1277. };
  1278. }
  1279. // serialize
  1280. let data = meta.nodes[ uuid ];
  1281. if ( data === undefined ) {
  1282. data = {
  1283. uuid,
  1284. type,
  1285. meta,
  1286. metadata: {
  1287. version: 4.6,
  1288. type: 'Node',
  1289. generator: 'Node.toJSON'
  1290. }
  1291. };
  1292. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1293. this.serialize( data );
  1294. delete data.meta;
  1295. }
  1296. // TODO: Copied from Object3D.toJSON
  1297. function extractFromCache( cache ) {
  1298. const values = [];
  1299. for ( const key in cache ) {
  1300. const data = cache[ key ];
  1301. delete data.metadata;
  1302. values.push( data );
  1303. }
  1304. return values;
  1305. }
  1306. if ( isRoot ) {
  1307. const textures = extractFromCache( meta.textures );
  1308. const images = extractFromCache( meta.images );
  1309. const nodes = extractFromCache( meta.nodes );
  1310. if ( textures.length > 0 ) data.textures = textures;
  1311. if ( images.length > 0 ) data.images = images;
  1312. if ( nodes.length > 0 ) data.nodes = nodes;
  1313. }
  1314. return data;
  1315. }
  1316. }
  1317. /**
  1318. * Base class for representing element access on an array-like
  1319. * node data structures.
  1320. *
  1321. * @augments Node
  1322. */
  1323. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1324. static get type() {
  1325. return 'ArrayElementNode';
  1326. }
  1327. /**
  1328. * Constructs an array element node.
  1329. *
  1330. * @param {Node} node - The array-like node.
  1331. * @param {Node} indexNode - The index node that defines the element access.
  1332. */
  1333. constructor( node, indexNode ) {
  1334. super();
  1335. /**
  1336. * The array-like node.
  1337. *
  1338. * @type {Node}
  1339. */
  1340. this.node = node;
  1341. /**
  1342. * The index node that defines the element access.
  1343. *
  1344. * @type {Node}
  1345. */
  1346. this.indexNode = indexNode;
  1347. /**
  1348. * This flag can be used for type testing.
  1349. *
  1350. * @type {boolean}
  1351. * @readonly
  1352. * @default true
  1353. */
  1354. this.isArrayElementNode = true;
  1355. }
  1356. /**
  1357. * This method is overwritten since the node type is inferred from the array-like node.
  1358. *
  1359. * @param {NodeBuilder} builder - The current node builder.
  1360. * @return {string} The node type.
  1361. */
  1362. getNodeType( builder ) {
  1363. return this.node.getElementType( builder );
  1364. }
  1365. generate( builder ) {
  1366. const nodeSnippet = this.node.build( builder );
  1367. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1368. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1369. }
  1370. }
  1371. /**
  1372. * This module is part of the TSL core and usually not used in app level code.
  1373. * It represents a convert operation during the shader generation process
  1374. * meaning it converts the data type of a node to a target data type.
  1375. *
  1376. * @augments Node
  1377. */
  1378. class ConvertNode extends Node {
  1379. static get type() {
  1380. return 'ConvertNode';
  1381. }
  1382. /**
  1383. * Constructs a new convert node.
  1384. *
  1385. * @param {Node} node - The node which type should be converted.
  1386. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1387. */
  1388. constructor( node, convertTo ) {
  1389. super();
  1390. /**
  1391. * The node which type should be converted.
  1392. *
  1393. * @type {Node}
  1394. */
  1395. this.node = node;
  1396. /**
  1397. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1398. *
  1399. * @type {string}
  1400. */
  1401. this.convertTo = convertTo;
  1402. }
  1403. /**
  1404. * This method is overwritten since the implementation tries to infer the best
  1405. * matching type from the {@link ConvertNode#convertTo} property.
  1406. *
  1407. * @param {NodeBuilder} builder - The current node builder.
  1408. * @return {string} The node type.
  1409. */
  1410. getNodeType( builder ) {
  1411. const requestType = this.node.getNodeType( builder );
  1412. let convertTo = null;
  1413. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1414. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1415. convertTo = overloadingType;
  1416. }
  1417. }
  1418. return convertTo;
  1419. }
  1420. serialize( data ) {
  1421. super.serialize( data );
  1422. data.convertTo = this.convertTo;
  1423. }
  1424. deserialize( data ) {
  1425. super.deserialize( data );
  1426. this.convertTo = data.convertTo;
  1427. }
  1428. generate( builder, output ) {
  1429. const node = this.node;
  1430. const type = this.getNodeType( builder );
  1431. const snippet = node.build( builder, type );
  1432. return builder.format( snippet, type, output );
  1433. }
  1434. }
  1435. /**
  1436. * This module uses cache management to create temporary variables
  1437. * if the node is used more than once to prevent duplicate calculations.
  1438. *
  1439. * The class acts as a base class for many other nodes types.
  1440. *
  1441. * @augments Node
  1442. */
  1443. class TempNode extends Node {
  1444. static get type() {
  1445. return 'TempNode';
  1446. }
  1447. /**
  1448. * Constructs a temp node.
  1449. *
  1450. * @param {?string} nodeType - The node type.
  1451. */
  1452. constructor( nodeType = null ) {
  1453. super( nodeType );
  1454. /**
  1455. * This flag can be used for type testing.
  1456. *
  1457. * @type {boolean}
  1458. * @readonly
  1459. * @default true
  1460. */
  1461. this.isTempNode = true;
  1462. }
  1463. /**
  1464. * Whether this node is used more than once in context of other nodes.
  1465. *
  1466. * @param {NodeBuilder} builder - The node builder.
  1467. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1468. */
  1469. hasDependencies( builder ) {
  1470. return builder.getDataFromNode( this ).usageCount > 1;
  1471. }
  1472. build( builder, output ) {
  1473. const buildStage = builder.getBuildStage();
  1474. if ( buildStage === 'generate' ) {
  1475. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1476. const nodeData = builder.getDataFromNode( this );
  1477. if ( nodeData.propertyName !== undefined ) {
  1478. return builder.format( nodeData.propertyName, type, output );
  1479. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1480. const snippet = super.build( builder, type );
  1481. const nodeVar = builder.getVarFromNode( this, null, type );
  1482. const propertyName = builder.getPropertyName( nodeVar );
  1483. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1484. nodeData.snippet = snippet;
  1485. nodeData.propertyName = propertyName;
  1486. return builder.format( nodeData.propertyName, type, output );
  1487. }
  1488. }
  1489. return super.build( builder, output );
  1490. }
  1491. }
  1492. /**
  1493. * This module is part of the TSL core and usually not used in app level code.
  1494. * It represents a join operation during the shader generation process.
  1495. * For example in can compose/join two single floats into a `vec2` type.
  1496. *
  1497. * @augments TempNode
  1498. */
  1499. class JoinNode extends TempNode {
  1500. static get type() {
  1501. return 'JoinNode';
  1502. }
  1503. /**
  1504. * Constructs a new join node.
  1505. *
  1506. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1507. * @param {?string} [nodeType=null] - The node type.
  1508. */
  1509. constructor( nodes = [], nodeType = null ) {
  1510. super( nodeType );
  1511. /**
  1512. * An array of nodes that should be joined.
  1513. *
  1514. * @type {Array<Node>}
  1515. */
  1516. this.nodes = nodes;
  1517. }
  1518. /**
  1519. * This method is overwritten since the node type must be inferred from the
  1520. * joined data length if not explicitly defined.
  1521. *
  1522. * @param {NodeBuilder} builder - The current node builder.
  1523. * @return {string} The node type.
  1524. */
  1525. getNodeType( builder ) {
  1526. if ( this.nodeType !== null ) {
  1527. return builder.getVectorType( this.nodeType );
  1528. }
  1529. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1530. }
  1531. generate( builder, output ) {
  1532. const type = this.getNodeType( builder );
  1533. const nodes = this.nodes;
  1534. const primitiveType = builder.getComponentType( type );
  1535. const snippetValues = [];
  1536. for ( const input of nodes ) {
  1537. let inputSnippet = input.build( builder );
  1538. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1539. if ( inputPrimitiveType !== primitiveType ) {
  1540. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1541. }
  1542. snippetValues.push( inputSnippet );
  1543. }
  1544. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1545. return builder.format( snippet, type, output );
  1546. }
  1547. }
  1548. const _stringVectorComponents = vectorComponents.join( '' );
  1549. /**
  1550. * This module is part of the TSL core and usually not used in app level code.
  1551. * `SplitNode` represents a property access operation which means it is
  1552. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1553. * For example:
  1554. * ```js
  1555. * const redValue = color.r;
  1556. * ```
  1557. *
  1558. * @augments Node
  1559. */
  1560. class SplitNode extends Node {
  1561. static get type() {
  1562. return 'SplitNode';
  1563. }
  1564. /**
  1565. * Constructs a new split node.
  1566. *
  1567. * @param {Node} node - The node that should be accessed.
  1568. * @param {string} [components='x'] - The components that should be accessed.
  1569. */
  1570. constructor( node, components = 'x' ) {
  1571. super();
  1572. /**
  1573. * The node that should be accessed.
  1574. *
  1575. * @type {Node}
  1576. */
  1577. this.node = node;
  1578. /**
  1579. * The components that should be accessed.
  1580. *
  1581. * @type {string}
  1582. */
  1583. this.components = components;
  1584. /**
  1585. * This flag can be used for type testing.
  1586. *
  1587. * @type {boolean}
  1588. * @readonly
  1589. * @default true
  1590. */
  1591. this.isSplitNode = true;
  1592. }
  1593. /**
  1594. * Returns the vector length which is computed based on the requested components.
  1595. *
  1596. * @return {number} The vector length.
  1597. */
  1598. getVectorLength() {
  1599. let vectorLength = this.components.length;
  1600. for ( const c of this.components ) {
  1601. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1602. }
  1603. return vectorLength;
  1604. }
  1605. /**
  1606. * Returns the component type of the node's type.
  1607. *
  1608. * @param {NodeBuilder} builder - The current node builder.
  1609. * @return {string} The component type.
  1610. */
  1611. getComponentType( builder ) {
  1612. return builder.getComponentType( this.node.getNodeType( builder ) );
  1613. }
  1614. /**
  1615. * This method is overwritten since the node type is inferred from requested components.
  1616. *
  1617. * @param {NodeBuilder} builder - The current node builder.
  1618. * @return {string} The node type.
  1619. */
  1620. getNodeType( builder ) {
  1621. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1622. }
  1623. generate( builder, output ) {
  1624. const node = this.node;
  1625. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1626. let snippet = null;
  1627. if ( nodeTypeLength > 1 ) {
  1628. let type = null;
  1629. const componentsLength = this.getVectorLength();
  1630. if ( componentsLength >= nodeTypeLength ) {
  1631. // needed expand the input node
  1632. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1633. }
  1634. const nodeSnippet = node.build( builder, type );
  1635. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1636. // unnecessary swizzle
  1637. snippet = builder.format( nodeSnippet, type, output );
  1638. } else {
  1639. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1640. }
  1641. } else {
  1642. // ignore .components if .node returns float/integer
  1643. snippet = node.build( builder, output );
  1644. }
  1645. return snippet;
  1646. }
  1647. serialize( data ) {
  1648. super.serialize( data );
  1649. data.components = this.components;
  1650. }
  1651. deserialize( data ) {
  1652. super.deserialize( data );
  1653. this.components = data.components;
  1654. }
  1655. }
  1656. /**
  1657. * This module is part of the TSL core and usually not used in app level code.
  1658. * `SetNode` represents a set operation which means it is used to implement any
  1659. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1660. * For example:
  1661. * ```js
  1662. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1663. * ```
  1664. *
  1665. * @augments TempNode
  1666. */
  1667. class SetNode extends TempNode {
  1668. static get type() {
  1669. return 'SetNode';
  1670. }
  1671. /**
  1672. * Constructs a new set node.
  1673. *
  1674. * @param {Node} sourceNode - The node that should be updated.
  1675. * @param {string} components - The components that should be updated.
  1676. * @param {Node} targetNode - The value node.
  1677. */
  1678. constructor( sourceNode, components, targetNode ) {
  1679. super();
  1680. /**
  1681. * The node that should be updated.
  1682. *
  1683. * @type {Node}
  1684. */
  1685. this.sourceNode = sourceNode;
  1686. /**
  1687. * The components that should be updated.
  1688. *
  1689. * @type {string}
  1690. */
  1691. this.components = components;
  1692. /**
  1693. * The value node.
  1694. *
  1695. * @type {Node}
  1696. */
  1697. this.targetNode = targetNode;
  1698. }
  1699. /**
  1700. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1701. *
  1702. * @param {NodeBuilder} builder - The current node builder.
  1703. * @return {string} The node type.
  1704. */
  1705. getNodeType( builder ) {
  1706. return this.sourceNode.getNodeType( builder );
  1707. }
  1708. generate( builder ) {
  1709. const { sourceNode, components, targetNode } = this;
  1710. const sourceType = this.getNodeType( builder );
  1711. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1712. const targetType = builder.getTypeFromLength( components.length, componentType );
  1713. const targetSnippet = targetNode.build( builder, targetType );
  1714. const sourceSnippet = sourceNode.build( builder, sourceType );
  1715. const length = builder.getTypeLength( sourceType );
  1716. const snippetValues = [];
  1717. for ( let i = 0; i < length; i ++ ) {
  1718. const component = vectorComponents[ i ];
  1719. if ( component === components[ 0 ] ) {
  1720. snippetValues.push( targetSnippet );
  1721. i += components.length - 1;
  1722. } else {
  1723. snippetValues.push( sourceSnippet + '.' + component );
  1724. }
  1725. }
  1726. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1727. }
  1728. }
  1729. /**
  1730. * This module is part of the TSL core and usually not used in app level code.
  1731. * It represents a flip operation during the shader generation process
  1732. * meaning it flips normalized values with the following formula:
  1733. * ```
  1734. * x = 1 - x;
  1735. * ```
  1736. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1737. * `flipSTPQ()` method invocations on node objects. For example:
  1738. * ```js
  1739. * uvNode = uvNode.flipY();
  1740. * ```
  1741. *
  1742. * @augments TempNode
  1743. */
  1744. class FlipNode extends TempNode {
  1745. static get type() {
  1746. return 'FlipNode';
  1747. }
  1748. /**
  1749. * Constructs a new flip node.
  1750. *
  1751. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1752. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1753. */
  1754. constructor( sourceNode, components ) {
  1755. super();
  1756. /**
  1757. * The node which component(s) should be flipped.
  1758. *
  1759. * @type {Node}
  1760. */
  1761. this.sourceNode = sourceNode;
  1762. /**
  1763. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1764. *
  1765. * @type {string}
  1766. */
  1767. this.components = components;
  1768. }
  1769. /**
  1770. * This method is overwritten since the node type is inferred from the source node.
  1771. *
  1772. * @param {NodeBuilder} builder - The current node builder.
  1773. * @return {string} The node type.
  1774. */
  1775. getNodeType( builder ) {
  1776. return this.sourceNode.getNodeType( builder );
  1777. }
  1778. generate( builder ) {
  1779. const { components, sourceNode } = this;
  1780. const sourceType = this.getNodeType( builder );
  1781. const sourceSnippet = sourceNode.build( builder );
  1782. const sourceCache = builder.getVarFromNode( this );
  1783. const sourceProperty = builder.getPropertyName( sourceCache );
  1784. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1785. const length = builder.getTypeLength( sourceType );
  1786. const snippetValues = [];
  1787. let componentIndex = 0;
  1788. for ( let i = 0; i < length; i ++ ) {
  1789. const component = vectorComponents[ i ];
  1790. if ( component === components[ componentIndex ] ) {
  1791. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1792. componentIndex ++;
  1793. } else {
  1794. snippetValues.push( sourceProperty + '.' + component );
  1795. }
  1796. }
  1797. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1798. }
  1799. }
  1800. /**
  1801. * Base class for representing data input nodes.
  1802. *
  1803. * @augments Node
  1804. */
  1805. class InputNode extends Node {
  1806. static get type() {
  1807. return 'InputNode';
  1808. }
  1809. /**
  1810. * Constructs a new input node.
  1811. *
  1812. * @param {any} value - The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1813. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1814. */
  1815. constructor( value, nodeType = null ) {
  1816. super( nodeType );
  1817. /**
  1818. * This flag can be used for type testing.
  1819. *
  1820. * @type {boolean}
  1821. * @readonly
  1822. * @default true
  1823. */
  1824. this.isInputNode = true;
  1825. /**
  1826. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1827. *
  1828. * @type {any}
  1829. */
  1830. this.value = value;
  1831. /**
  1832. * The precision of the value in the shader.
  1833. *
  1834. * @type {?('low'|'medium'|'high')}
  1835. * @default null
  1836. */
  1837. this.precision = null;
  1838. }
  1839. getNodeType( /*builder*/ ) {
  1840. if ( this.nodeType === null ) {
  1841. return getValueType( this.value );
  1842. }
  1843. return this.nodeType;
  1844. }
  1845. /**
  1846. * Returns the input type of the node which is by default the node type. Derived modules
  1847. * might overwrite this method and use a fixed type or compute one analytically.
  1848. *
  1849. * A typical example for different input and node types are textures. The input type of a
  1850. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1851. *
  1852. * @param {NodeBuilder} builder - The current node builder.
  1853. * @return {string} The input type.
  1854. */
  1855. getInputType( builder ) {
  1856. return this.getNodeType( builder );
  1857. }
  1858. /**
  1859. * Sets the precision to the given value. The method can be
  1860. * overwritten in derived classes if the final precision must be computed
  1861. * analytically.
  1862. *
  1863. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1864. * @return {InputNode} A reference to this node.
  1865. */
  1866. setPrecision( precision ) {
  1867. this.precision = precision;
  1868. return this;
  1869. }
  1870. serialize( data ) {
  1871. super.serialize( data );
  1872. data.value = this.value;
  1873. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1874. data.valueType = getValueType( this.value );
  1875. data.nodeType = this.nodeType;
  1876. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1877. data.precision = this.precision;
  1878. }
  1879. deserialize( data ) {
  1880. super.deserialize( data );
  1881. this.nodeType = data.nodeType;
  1882. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1883. this.precision = data.precision || null;
  1884. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1885. }
  1886. generate( /*builder, output*/ ) {
  1887. console.warn( 'Abstract function.' );
  1888. }
  1889. }
  1890. const _regNum = /float|u?int/;
  1891. /**
  1892. * Class for representing a constant value in the shader.
  1893. *
  1894. * @augments InputNode
  1895. */
  1896. class ConstNode extends InputNode {
  1897. static get type() {
  1898. return 'ConstNode';
  1899. }
  1900. /**
  1901. * Constructs a new input node.
  1902. *
  1903. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1904. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1905. */
  1906. constructor( value, nodeType = null ) {
  1907. super( value, nodeType );
  1908. /**
  1909. * This flag can be used for type testing.
  1910. *
  1911. * @type {boolean}
  1912. * @readonly
  1913. * @default true
  1914. */
  1915. this.isConstNode = true;
  1916. }
  1917. /**
  1918. * Generates the shader string of the value with the current node builder.
  1919. *
  1920. * @param {NodeBuilder} builder - The current node builder.
  1921. * @return {string} The generated value as a shader string.
  1922. */
  1923. generateConst( builder ) {
  1924. return builder.generateConst( this.getNodeType( builder ), this.value );
  1925. }
  1926. generate( builder, output ) {
  1927. const type = this.getNodeType( builder );
  1928. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  1929. return builder.generateConst( output, this.value );
  1930. }
  1931. return builder.format( this.generateConst( builder ), type, output );
  1932. }
  1933. }
  1934. /**
  1935. * Base class for representing member access on an object-like
  1936. * node data structures.
  1937. *
  1938. * @augments Node
  1939. */
  1940. class MemberNode extends Node {
  1941. static get type() {
  1942. return 'MemberNode';
  1943. }
  1944. /**
  1945. * Constructs an array element node.
  1946. *
  1947. * @param {Node} node - The array-like node.
  1948. * @param {string} property - The property name.
  1949. */
  1950. constructor( node, property ) {
  1951. super();
  1952. /**
  1953. * The array-like node.
  1954. *
  1955. * @type {Node}
  1956. */
  1957. this.node = node;
  1958. /**
  1959. * The property name.
  1960. *
  1961. * @type {Node}
  1962. */
  1963. this.property = property;
  1964. /**
  1965. * This flag can be used for type testing.
  1966. *
  1967. * @type {boolean}
  1968. * @readonly
  1969. * @default true
  1970. */
  1971. this.isMemberNode = true;
  1972. }
  1973. getNodeType( builder ) {
  1974. return this.node.getMemberType( builder, this.property );
  1975. }
  1976. generate( builder ) {
  1977. const propertyName = this.node.build( builder );
  1978. return propertyName + '.' + this.property;
  1979. }
  1980. }
  1981. let currentStack = null;
  1982. const NodeElements = new Map();
  1983. function addMethodChaining( name, nodeElement ) {
  1984. if ( NodeElements.has( name ) ) {
  1985. console.warn( `Redefinition of method chaining ${ name }` );
  1986. return;
  1987. }
  1988. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1989. NodeElements.set( name, nodeElement );
  1990. }
  1991. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1992. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1993. const shaderNodeHandler = {
  1994. setup( NodeClosure, params ) {
  1995. const inputs = params.shift();
  1996. return NodeClosure( nodeObjects( inputs ), ...params );
  1997. },
  1998. get( node, prop, nodeObj ) {
  1999. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2000. if ( node.isStackNode !== true && prop === 'assign' ) {
  2001. return ( ...params ) => {
  2002. currentStack.assign( nodeObj, ...params );
  2003. return nodeObj;
  2004. };
  2005. } else if ( NodeElements.has( prop ) ) {
  2006. const nodeElement = NodeElements.get( prop );
  2007. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2008. } else if ( prop === 'self' ) {
  2009. return node;
  2010. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2011. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2012. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2013. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2014. // accessing properties ( swizzle )
  2015. prop = parseSwizzle( prop );
  2016. return nodeObject( new SplitNode( nodeObj, prop ) );
  2017. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2018. // set properties ( swizzle ) and sort to xyzw sequence
  2019. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2020. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  2021. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2022. // set properties ( swizzle ) and sort to xyzw sequence
  2023. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2024. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2025. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2026. // accessing property
  2027. if ( prop === 'width' ) prop = 'x';
  2028. else if ( prop === 'height' ) prop = 'y';
  2029. else if ( prop === 'depth' ) prop = 'z';
  2030. return nodeObject( new SplitNode( node, prop ) );
  2031. } else if ( /^\d+$/.test( prop ) === true ) {
  2032. // accessing array
  2033. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2034. } else if ( /^get$/.test( prop ) === true ) {
  2035. // accessing properties
  2036. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2037. }
  2038. }
  2039. return Reflect.get( node, prop, nodeObj );
  2040. },
  2041. set( node, prop, value, nodeObj ) {
  2042. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2043. // setting properties
  2044. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2045. nodeObj[ prop ].assign( value );
  2046. return true;
  2047. }
  2048. }
  2049. return Reflect.set( node, prop, value, nodeObj );
  2050. }
  2051. };
  2052. const nodeObjectsCacheMap = new WeakMap();
  2053. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2054. const ShaderNodeObject = function ( obj, altType = null ) {
  2055. const type = getValueType( obj );
  2056. if ( type === 'node' ) {
  2057. let nodeObject = nodeObjectsCacheMap.get( obj );
  2058. if ( nodeObject === undefined ) {
  2059. nodeObject = new Proxy( obj, shaderNodeHandler );
  2060. nodeObjectsCacheMap.set( obj, nodeObject );
  2061. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2062. }
  2063. return nodeObject;
  2064. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2065. return nodeObject( getConstNode( obj, altType ) );
  2066. } else if ( type === 'shader' ) {
  2067. return Fn( obj );
  2068. }
  2069. return obj;
  2070. };
  2071. const ShaderNodeObjects = function ( objects, altType = null ) {
  2072. for ( const name in objects ) {
  2073. objects[ name ] = nodeObject( objects[ name ], altType );
  2074. }
  2075. return objects;
  2076. };
  2077. const ShaderNodeArray = function ( array, altType = null ) {
  2078. const len = array.length;
  2079. for ( let i = 0; i < len; i ++ ) {
  2080. array[ i ] = nodeObject( array[ i ], altType );
  2081. }
  2082. return array;
  2083. };
  2084. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2085. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2086. if ( scope === null ) {
  2087. return ( ...params ) => {
  2088. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2089. };
  2090. } else if ( factor !== null ) {
  2091. factor = nodeObject( factor );
  2092. return ( ...params ) => {
  2093. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2094. };
  2095. } else {
  2096. return ( ...params ) => {
  2097. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2098. };
  2099. }
  2100. };
  2101. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2102. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2103. };
  2104. class ShaderCallNodeInternal extends Node {
  2105. constructor( shaderNode, inputNodes ) {
  2106. super();
  2107. this.shaderNode = shaderNode;
  2108. this.inputNodes = inputNodes;
  2109. }
  2110. getNodeType( builder ) {
  2111. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2112. }
  2113. getMemberType( builder, name ) {
  2114. return this.getOutputNode( builder ).getMemberType( builder, name );
  2115. }
  2116. call( builder ) {
  2117. const { shaderNode, inputNodes } = this;
  2118. const properties = builder.getNodeProperties( shaderNode );
  2119. if ( properties.onceOutput ) return properties.onceOutput;
  2120. //
  2121. let result = null;
  2122. if ( shaderNode.layout ) {
  2123. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2124. if ( functionNodesCacheMap === undefined ) {
  2125. functionNodesCacheMap = new WeakMap();
  2126. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2127. }
  2128. let functionNode = functionNodesCacheMap.get( shaderNode );
  2129. if ( functionNode === undefined ) {
  2130. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2131. functionNodesCacheMap.set( shaderNode, functionNode );
  2132. }
  2133. builder.addInclude( functionNode );
  2134. result = nodeObject( functionNode.call( inputNodes ) );
  2135. } else {
  2136. const jsFunc = shaderNode.jsFunc;
  2137. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2138. result = nodeObject( outputNode );
  2139. }
  2140. if ( shaderNode.once ) {
  2141. properties.onceOutput = result;
  2142. }
  2143. return result;
  2144. }
  2145. getOutputNode( builder ) {
  2146. const properties = builder.getNodeProperties( this );
  2147. if ( properties.outputNode === null ) {
  2148. properties.outputNode = this.setupOutput( builder );
  2149. }
  2150. return properties.outputNode;
  2151. }
  2152. setup( builder ) {
  2153. return this.getOutputNode( builder );
  2154. }
  2155. setupOutput( builder ) {
  2156. builder.addStack();
  2157. builder.stack.outputNode = this.call( builder );
  2158. return builder.removeStack();
  2159. }
  2160. generate( builder, output ) {
  2161. const outputNode = this.getOutputNode( builder );
  2162. return outputNode.build( builder, output );
  2163. }
  2164. }
  2165. class ShaderNodeInternal extends Node {
  2166. constructor( jsFunc, nodeType ) {
  2167. super( nodeType );
  2168. this.jsFunc = jsFunc;
  2169. this.layout = null;
  2170. this.global = true;
  2171. this.once = false;
  2172. }
  2173. setLayout( layout ) {
  2174. this.layout = layout;
  2175. return this;
  2176. }
  2177. call( inputs = null ) {
  2178. nodeObjects( inputs );
  2179. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2180. }
  2181. setup() {
  2182. return this.call();
  2183. }
  2184. }
  2185. const bools = [ false, true ];
  2186. const uints = [ 0, 1, 2, 3 ];
  2187. const ints = [ -1, -2 ];
  2188. 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 ];
  2189. const boolsCacheMap = new Map();
  2190. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2191. const uintsCacheMap = new Map();
  2192. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2193. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2194. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2195. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2196. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2197. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2198. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2199. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2200. const getConstNode = ( value, type ) => {
  2201. if ( constNodesCacheMap.has( value ) ) {
  2202. return constNodesCacheMap.get( value );
  2203. } else if ( value.isNode === true ) {
  2204. return value;
  2205. } else {
  2206. return new ConstNode( value, type );
  2207. }
  2208. };
  2209. const safeGetNodeType = ( node ) => {
  2210. try {
  2211. return node.getNodeType();
  2212. } catch ( _ ) {
  2213. return undefined;
  2214. }
  2215. };
  2216. const ConvertType = function ( type, cacheMap = null ) {
  2217. return ( ...params ) => {
  2218. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2219. params = [ getValueFromType( type, ...params ) ];
  2220. }
  2221. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2222. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2223. }
  2224. if ( params.length === 1 ) {
  2225. const node = getConstNode( params[ 0 ], type );
  2226. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2227. return nodeObject( new ConvertNode( node, type ) );
  2228. }
  2229. const nodes = params.map( param => getConstNode( param ) );
  2230. return nodeObject( new JoinNode( nodes, type ) );
  2231. };
  2232. };
  2233. // exports
  2234. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2235. // utils
  2236. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2237. // shader node base
  2238. function ShaderNode( jsFunc, nodeType ) {
  2239. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2240. }
  2241. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2242. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2243. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2244. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2245. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2246. const Fn = ( jsFunc, nodeType ) => {
  2247. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2248. const fn = ( ...params ) => {
  2249. let inputs;
  2250. nodeObjects( params );
  2251. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2252. inputs = [ ...params ];
  2253. } else {
  2254. inputs = params[ 0 ];
  2255. }
  2256. return shaderNode.call( inputs );
  2257. };
  2258. fn.shaderNode = shaderNode;
  2259. fn.setLayout = ( layout ) => {
  2260. shaderNode.setLayout( layout );
  2261. return fn;
  2262. };
  2263. fn.once = () => {
  2264. shaderNode.once = true;
  2265. return fn;
  2266. };
  2267. return fn;
  2268. };
  2269. /**
  2270. * @tsl
  2271. * @function
  2272. * @deprecated since r168. Use {@link Fn} instead.
  2273. *
  2274. * @param {...any} params
  2275. * @returns {Function}
  2276. */
  2277. const tslFn = ( ...params ) => { // @deprecated, r168
  2278. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2279. return Fn( ...params );
  2280. };
  2281. //
  2282. addMethodChaining( 'toGlobal', ( node ) => {
  2283. node.global = true;
  2284. return node;
  2285. } );
  2286. //
  2287. const setCurrentStack = ( stack ) => {
  2288. currentStack = stack;
  2289. };
  2290. const getCurrentStack = () => currentStack;
  2291. const If = ( ...params ) => currentStack.If( ...params );
  2292. function append( node ) {
  2293. if ( currentStack ) currentStack.add( node );
  2294. return node;
  2295. }
  2296. addMethodChaining( 'append', append );
  2297. // types
  2298. const color = new ConvertType( 'color' );
  2299. const float = new ConvertType( 'float', cacheMaps.float );
  2300. const int = new ConvertType( 'int', cacheMaps.ints );
  2301. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2302. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2303. const vec2 = new ConvertType( 'vec2' );
  2304. const ivec2 = new ConvertType( 'ivec2' );
  2305. const uvec2 = new ConvertType( 'uvec2' );
  2306. const bvec2 = new ConvertType( 'bvec2' );
  2307. const vec3 = new ConvertType( 'vec3' );
  2308. const ivec3 = new ConvertType( 'ivec3' );
  2309. const uvec3 = new ConvertType( 'uvec3' );
  2310. const bvec3 = new ConvertType( 'bvec3' );
  2311. const vec4 = new ConvertType( 'vec4' );
  2312. const ivec4 = new ConvertType( 'ivec4' );
  2313. const uvec4 = new ConvertType( 'uvec4' );
  2314. const bvec4 = new ConvertType( 'bvec4' );
  2315. const mat2 = new ConvertType( 'mat2' );
  2316. const mat3 = new ConvertType( 'mat3' );
  2317. const mat4 = new ConvertType( 'mat4' );
  2318. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2319. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2320. addMethodChaining( 'toColor', color );
  2321. addMethodChaining( 'toFloat', float );
  2322. addMethodChaining( 'toInt', int );
  2323. addMethodChaining( 'toUint', uint );
  2324. addMethodChaining( 'toBool', bool );
  2325. addMethodChaining( 'toVec2', vec2 );
  2326. addMethodChaining( 'toIVec2', ivec2 );
  2327. addMethodChaining( 'toUVec2', uvec2 );
  2328. addMethodChaining( 'toBVec2', bvec2 );
  2329. addMethodChaining( 'toVec3', vec3 );
  2330. addMethodChaining( 'toIVec3', ivec3 );
  2331. addMethodChaining( 'toUVec3', uvec3 );
  2332. addMethodChaining( 'toBVec3', bvec3 );
  2333. addMethodChaining( 'toVec4', vec4 );
  2334. addMethodChaining( 'toIVec4', ivec4 );
  2335. addMethodChaining( 'toUVec4', uvec4 );
  2336. addMethodChaining( 'toBVec4', bvec4 );
  2337. addMethodChaining( 'toMat2', mat2 );
  2338. addMethodChaining( 'toMat3', mat3 );
  2339. addMethodChaining( 'toMat4', mat4 );
  2340. // basic nodes
  2341. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2342. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2343. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2344. addMethodChaining( 'element', element );
  2345. addMethodChaining( 'convert', convert );
  2346. /**
  2347. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  2348. * ```js
  2349. * const colors = array( [
  2350. * vec3( 1, 0, 0 ),
  2351. * vec3( 0, 1, 0 ),
  2352. * vec3( 0, 0, 1 )
  2353. * ] );
  2354. *
  2355. * const redColor = tintColors.element( 0 );
  2356. *
  2357. * @augments Node
  2358. */
  2359. class ArrayNode extends TempNode {
  2360. static get type() {
  2361. return 'ArrayNode';
  2362. }
  2363. /**
  2364. * Constructs a new array node.
  2365. *
  2366. * @param {string} [nodeType] - The data type of the elements.
  2367. * @param {number} [count] - Size of the array.
  2368. * @param {?Array<Node>} [values=null] - Array default values.
  2369. */
  2370. constructor( nodeType, count, values = null ) {
  2371. super( nodeType );
  2372. /**
  2373. * Array size.
  2374. *
  2375. * @type {number}
  2376. */
  2377. this.count = count;
  2378. /**
  2379. * Array default values.
  2380. *
  2381. * @type {?Array<Node>}
  2382. */
  2383. this.values = values;
  2384. /**
  2385. * This flag can be used for type testing.
  2386. *
  2387. * @type {boolean}
  2388. * @readonly
  2389. * @default true
  2390. */
  2391. this.isArrayNode = true;
  2392. }
  2393. getNodeType( builder ) {
  2394. if ( this.nodeType === null ) {
  2395. this.nodeType = this.values[ 0 ].getNodeType( builder );
  2396. }
  2397. return this.nodeType;
  2398. }
  2399. getElementType( builder ) {
  2400. return this.getNodeType( builder );
  2401. }
  2402. generate( builder ) {
  2403. const type = this.getNodeType( builder );
  2404. return builder.generateArray( type, this.count, this.values );
  2405. }
  2406. }
  2407. /**
  2408. * TSL function for creating an array node.
  2409. *
  2410. * @tsl
  2411. * @function
  2412. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  2413. * or an array containing the default values (e.g., [ vec3() ]).
  2414. * @param {?number} [count] - Size of the array.
  2415. * @returns {ArrayNode}
  2416. */
  2417. const array = ( ...params ) => {
  2418. let node;
  2419. if ( params.length === 1 ) {
  2420. const values = params[ 0 ];
  2421. node = new ArrayNode( null, values.length, values );
  2422. } else {
  2423. const nodeType = params[ 0 ];
  2424. const count = params[ 1 ];
  2425. node = new ArrayNode( nodeType, count );
  2426. }
  2427. return nodeObject( node );
  2428. };
  2429. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  2430. /**
  2431. * This node can be used to group single instances of {@link UniformNode}
  2432. * and manage them as a uniform buffer.
  2433. *
  2434. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2435. * will be used when defining the {@link UniformNode#groupNode} property.
  2436. *
  2437. * - `objectGroup`: Uniform buffer per object.
  2438. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2439. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2440. *
  2441. * @augments Node
  2442. */
  2443. class UniformGroupNode extends Node {
  2444. static get type() {
  2445. return 'UniformGroupNode';
  2446. }
  2447. /**
  2448. * Constructs a new uniform group node.
  2449. *
  2450. * @param {string} name - The name of the uniform group node.
  2451. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2452. * @param {number} [order=1] - Influences the internal sorting.
  2453. */
  2454. constructor( name, shared = false, order = 1 ) {
  2455. super( 'string' );
  2456. /**
  2457. * The name of the uniform group node.
  2458. *
  2459. * @type {string}
  2460. */
  2461. this.name = name;
  2462. /**
  2463. * Whether this uniform group node is shared or not.
  2464. *
  2465. * @type {boolean}
  2466. * @default false
  2467. */
  2468. this.shared = shared;
  2469. /**
  2470. * Influences the internal sorting.
  2471. * TODO: Add details when this property should be changed.
  2472. *
  2473. * @type {number}
  2474. * @default 1
  2475. */
  2476. this.order = order;
  2477. /**
  2478. * This flag can be used for type testing.
  2479. *
  2480. * @type {boolean}
  2481. * @readonly
  2482. * @default true
  2483. */
  2484. this.isUniformGroup = true;
  2485. }
  2486. serialize( data ) {
  2487. super.serialize( data );
  2488. data.name = this.name;
  2489. data.version = this.version;
  2490. data.shared = this.shared;
  2491. }
  2492. deserialize( data ) {
  2493. super.deserialize( data );
  2494. this.name = data.name;
  2495. this.version = data.version;
  2496. this.shared = data.shared;
  2497. }
  2498. }
  2499. /**
  2500. * TSL function for creating a uniform group node with the given name.
  2501. *
  2502. * @tsl
  2503. * @function
  2504. * @param {string} name - The name of the uniform group node.
  2505. * @returns {UniformGroupNode}
  2506. */
  2507. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2508. /**
  2509. * TSL function for creating a shared uniform group node with the given name and order.
  2510. *
  2511. * @tsl
  2512. * @function
  2513. * @param {string} name - The name of the uniform group node.
  2514. * @param {number} [order=0] - Influences the internal sorting.
  2515. * @returns {UniformGroupNode}
  2516. */
  2517. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2518. /**
  2519. * TSL object that represents a shared uniform group node which is updated once per frame.
  2520. *
  2521. * @tsl
  2522. * @type {UniformGroupNode}
  2523. */
  2524. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2525. /**
  2526. * TSL object that represents a shared uniform group node which is updated once per render.
  2527. *
  2528. * @tsl
  2529. * @type {UniformGroupNode}
  2530. */
  2531. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2532. /**
  2533. * TSL object that represents a uniform group node which is updated once per object.
  2534. *
  2535. * @tsl
  2536. * @type {UniformGroupNode}
  2537. */
  2538. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2539. /**
  2540. * Class for representing a uniform.
  2541. *
  2542. * @augments InputNode
  2543. */
  2544. class UniformNode extends InputNode {
  2545. static get type() {
  2546. return 'UniformNode';
  2547. }
  2548. /**
  2549. * Constructs a new uniform node.
  2550. *
  2551. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2552. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2553. */
  2554. constructor( value, nodeType = null ) {
  2555. super( value, nodeType );
  2556. /**
  2557. * This flag can be used for type testing.
  2558. *
  2559. * @type {boolean}
  2560. * @readonly
  2561. * @default true
  2562. */
  2563. this.isUniformNode = true;
  2564. /**
  2565. * The name or label of the uniform.
  2566. *
  2567. * @type {string}
  2568. * @default ''
  2569. */
  2570. this.name = '';
  2571. /**
  2572. * The uniform group of this uniform. By default, uniforms are
  2573. * managed per object but they might belong to a shared group
  2574. * which is updated per frame or render call.
  2575. *
  2576. * @type {UniformGroupNode}
  2577. */
  2578. this.groupNode = objectGroup;
  2579. }
  2580. /**
  2581. * Sets the {@link UniformNode#name} property.
  2582. *
  2583. * @param {string} name - The name of the uniform.
  2584. * @return {UniformNode} A reference to this node.
  2585. */
  2586. label( name ) {
  2587. this.name = name;
  2588. return this;
  2589. }
  2590. /**
  2591. * Sets the {@link UniformNode#groupNode} property.
  2592. *
  2593. * @param {UniformGroupNode} group - The uniform group.
  2594. * @return {UniformNode} A reference to this node.
  2595. */
  2596. setGroup( group ) {
  2597. this.groupNode = group;
  2598. return this;
  2599. }
  2600. /**
  2601. * Returns the {@link UniformNode#groupNode}.
  2602. *
  2603. * @return {UniformGroupNode} The uniform group.
  2604. */
  2605. getGroup() {
  2606. return this.groupNode;
  2607. }
  2608. /**
  2609. * By default, this method returns the result of {@link Node#getHash} but derived
  2610. * classes might overwrite this method with a different implementation.
  2611. *
  2612. * @param {NodeBuilder} builder - The current node builder.
  2613. * @return {string} The uniform hash.
  2614. */
  2615. getUniformHash( builder ) {
  2616. return this.getHash( builder );
  2617. }
  2618. onUpdate( callback, updateType ) {
  2619. const self = this.getSelf();
  2620. callback = callback.bind( self );
  2621. return super.onUpdate( ( frame ) => {
  2622. const value = callback( frame, self );
  2623. if ( value !== undefined ) {
  2624. this.value = value;
  2625. }
  2626. }, updateType );
  2627. }
  2628. generate( builder, output ) {
  2629. const type = this.getNodeType( builder );
  2630. const hash = this.getUniformHash( builder );
  2631. let sharedNode = builder.getNodeFromHash( hash );
  2632. if ( sharedNode === undefined ) {
  2633. builder.setHashNode( this, hash );
  2634. sharedNode = this;
  2635. }
  2636. const sharedNodeType = sharedNode.getInputType( builder );
  2637. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2638. const propertyName = builder.getPropertyName( nodeUniform );
  2639. if ( builder.context.label !== undefined ) delete builder.context.label;
  2640. return builder.format( propertyName, type, output );
  2641. }
  2642. }
  2643. /**
  2644. * TSL function for creating a uniform node.
  2645. *
  2646. * @tsl
  2647. * @function
  2648. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2649. * @param {?string} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2650. * @returns {UniformNode}
  2651. */
  2652. const uniform = ( arg1, arg2 ) => {
  2653. const nodeType = getConstNodeType( arg2 || arg1 );
  2654. // @TODO: get ConstNode from .traverse() in the future
  2655. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2656. return nodeObject( new UniformNode( value, nodeType ) );
  2657. };
  2658. /**
  2659. * This class represents a shader property. It can be used
  2660. * to explicitly define a property and assign a value to it.
  2661. *
  2662. * ```js
  2663. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2664. *```
  2665. * `PropertyNode` is used by the engine to predefined common material properties
  2666. * for TSL code.
  2667. *
  2668. * @augments Node
  2669. */
  2670. class PropertyNode extends Node {
  2671. static get type() {
  2672. return 'PropertyNode';
  2673. }
  2674. /**
  2675. * Constructs a new property node.
  2676. *
  2677. * @param {string} nodeType - The type of the node.
  2678. * @param {?string} [name=null] - The name of the property in the shader.
  2679. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2680. */
  2681. constructor( nodeType, name = null, varying = false ) {
  2682. super( nodeType );
  2683. /**
  2684. * The name of the property in the shader. If no name is defined,
  2685. * the node system auto-generates one.
  2686. *
  2687. * @type {?string}
  2688. * @default null
  2689. */
  2690. this.name = name;
  2691. /**
  2692. * Whether this property is a varying or not.
  2693. *
  2694. * @type {boolean}
  2695. * @default false
  2696. */
  2697. this.varying = varying;
  2698. /**
  2699. * This flag can be used for type testing.
  2700. *
  2701. * @type {boolean}
  2702. * @readonly
  2703. * @default true
  2704. */
  2705. this.isPropertyNode = true;
  2706. }
  2707. getHash( builder ) {
  2708. return this.name || super.getHash( builder );
  2709. }
  2710. /**
  2711. * The method is overwritten so it always returns `true`.
  2712. *
  2713. * @param {NodeBuilder} builder - The current node builder.
  2714. * @return {boolean} Whether this node is global or not.
  2715. */
  2716. isGlobal( /*builder*/ ) {
  2717. return true;
  2718. }
  2719. generate( builder ) {
  2720. let nodeVar;
  2721. if ( this.varying === true ) {
  2722. nodeVar = builder.getVaryingFromNode( this, this.name );
  2723. nodeVar.needsInterpolation = true;
  2724. } else {
  2725. nodeVar = builder.getVarFromNode( this, this.name );
  2726. }
  2727. return builder.getPropertyName( nodeVar );
  2728. }
  2729. }
  2730. /**
  2731. * TSL function for creating a property node.
  2732. *
  2733. * @tsl
  2734. * @function
  2735. * @param {string} type - The type of the node.
  2736. * @param {?string} [name=null] - The name of the property in the shader.
  2737. * @returns {PropertyNode}
  2738. */
  2739. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2740. /**
  2741. * TSL function for creating a varying property node.
  2742. *
  2743. * @tsl
  2744. * @function
  2745. * @param {string} type - The type of the node.
  2746. * @param {?string} [name=null] - The name of the varying in the shader.
  2747. * @returns {PropertyNode}
  2748. */
  2749. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2750. /**
  2751. * TSL object that represents the shader variable `DiffuseColor`.
  2752. *
  2753. * @tsl
  2754. * @type {PropertyNode<vec4>}
  2755. */
  2756. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2757. /**
  2758. * TSL object that represents the shader variable `EmissiveColor`.
  2759. *
  2760. * @tsl
  2761. * @type {PropertyNode<vec3>}
  2762. */
  2763. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2764. /**
  2765. * TSL object that represents the shader variable `Roughness`.
  2766. *
  2767. * @tsl
  2768. * @type {PropertyNode<float>}
  2769. */
  2770. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2771. /**
  2772. * TSL object that represents the shader variable `Metalness`.
  2773. *
  2774. * @tsl
  2775. * @type {PropertyNode<float>}
  2776. */
  2777. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2778. /**
  2779. * TSL object that represents the shader variable `Clearcoat`.
  2780. *
  2781. * @tsl
  2782. * @type {PropertyNode<float>}
  2783. */
  2784. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2785. /**
  2786. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2787. *
  2788. * @tsl
  2789. * @type {PropertyNode<float>}
  2790. */
  2791. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2792. /**
  2793. * TSL object that represents the shader variable `Sheen`.
  2794. *
  2795. * @tsl
  2796. * @type {PropertyNode<vec3>}
  2797. */
  2798. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2799. /**
  2800. * TSL object that represents the shader variable `SheenRoughness`.
  2801. *
  2802. * @tsl
  2803. * @type {PropertyNode<float>}
  2804. */
  2805. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2806. /**
  2807. * TSL object that represents the shader variable `Iridescence`.
  2808. *
  2809. * @tsl
  2810. * @type {PropertyNode<float>}
  2811. */
  2812. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2813. /**
  2814. * TSL object that represents the shader variable `IridescenceIOR`.
  2815. *
  2816. * @tsl
  2817. * @type {PropertyNode<float>}
  2818. */
  2819. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2820. /**
  2821. * TSL object that represents the shader variable `IridescenceThickness`.
  2822. *
  2823. * @tsl
  2824. * @type {PropertyNode<float>}
  2825. */
  2826. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2827. /**
  2828. * TSL object that represents the shader variable `AlphaT`.
  2829. *
  2830. * @tsl
  2831. * @type {PropertyNode<float>}
  2832. */
  2833. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2834. /**
  2835. * TSL object that represents the shader variable `Anisotropy`.
  2836. *
  2837. * @tsl
  2838. * @type {PropertyNode<float>}
  2839. */
  2840. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2841. /**
  2842. * TSL object that represents the shader variable `AnisotropyT`.
  2843. *
  2844. * @tsl
  2845. * @type {PropertyNode<vec3>}
  2846. */
  2847. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2848. /**
  2849. * TSL object that represents the shader variable `AnisotropyB`.
  2850. *
  2851. * @tsl
  2852. * @type {PropertyNode<vec3>}
  2853. */
  2854. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2855. /**
  2856. * TSL object that represents the shader variable `SpecularColor`.
  2857. *
  2858. * @tsl
  2859. * @type {PropertyNode<color>}
  2860. */
  2861. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2862. /**
  2863. * TSL object that represents the shader variable `SpecularF90`.
  2864. *
  2865. * @tsl
  2866. * @type {PropertyNode<float>}
  2867. */
  2868. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2869. /**
  2870. * TSL object that represents the shader variable `Shininess`.
  2871. *
  2872. * @tsl
  2873. * @type {PropertyNode<float>}
  2874. */
  2875. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2876. /**
  2877. * TSL object that represents the shader variable `Output`.
  2878. *
  2879. * @tsl
  2880. * @type {PropertyNode<vec4>}
  2881. */
  2882. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2883. /**
  2884. * TSL object that represents the shader variable `dashSize`.
  2885. *
  2886. * @tsl
  2887. * @type {PropertyNode<float>}
  2888. */
  2889. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2890. /**
  2891. * TSL object that represents the shader variable `gapSize`.
  2892. *
  2893. * @tsl
  2894. * @type {PropertyNode<float>}
  2895. */
  2896. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2897. /**
  2898. * TSL object that represents the shader variable `pointWidth`.
  2899. *
  2900. * @tsl
  2901. * @type {PropertyNode<float>}
  2902. */
  2903. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2904. /**
  2905. * TSL object that represents the shader variable `IOR`.
  2906. *
  2907. * @tsl
  2908. * @type {PropertyNode<float>}
  2909. */
  2910. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2911. /**
  2912. * TSL object that represents the shader variable `Transmission`.
  2913. *
  2914. * @tsl
  2915. * @type {PropertyNode<float>}
  2916. */
  2917. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2918. /**
  2919. * TSL object that represents the shader variable `Thickness`.
  2920. *
  2921. * @tsl
  2922. * @type {PropertyNode<float>}
  2923. */
  2924. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2925. /**
  2926. * TSL object that represents the shader variable `AttenuationDistance`.
  2927. *
  2928. * @tsl
  2929. * @type {PropertyNode<float>}
  2930. */
  2931. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2932. /**
  2933. * TSL object that represents the shader variable `AttenuationColor`.
  2934. *
  2935. * @tsl
  2936. * @type {PropertyNode<color>}
  2937. */
  2938. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2939. /**
  2940. * TSL object that represents the shader variable `Dispersion`.
  2941. *
  2942. * @tsl
  2943. * @type {PropertyNode<float>}
  2944. */
  2945. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2946. /**
  2947. * These node represents an assign operation. Meaning a node is assigned
  2948. * to another node.
  2949. *
  2950. * @augments TempNode
  2951. */
  2952. class AssignNode extends TempNode {
  2953. static get type() {
  2954. return 'AssignNode';
  2955. }
  2956. /**
  2957. * Constructs a new assign node.
  2958. *
  2959. * @param {Node} targetNode - The target node.
  2960. * @param {Node} sourceNode - The source type.
  2961. */
  2962. constructor( targetNode, sourceNode ) {
  2963. super();
  2964. /**
  2965. * The target node.
  2966. *
  2967. * @type {Node}
  2968. */
  2969. this.targetNode = targetNode;
  2970. /**
  2971. * The source node.
  2972. *
  2973. * @type {Node}
  2974. */
  2975. this.sourceNode = sourceNode;
  2976. }
  2977. /**
  2978. * Whether this node is used more than once in context of other nodes. This method
  2979. * is overwritten since it always returns `false` (assigns are unique).
  2980. *
  2981. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2982. */
  2983. hasDependencies() {
  2984. return false;
  2985. }
  2986. getNodeType( builder, output ) {
  2987. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2988. }
  2989. /**
  2990. * Whether a split is required when assigning source to target. This can happen when the component length of
  2991. * target and source data type does not match.
  2992. *
  2993. * @param {NodeBuilder} builder - The current node builder.
  2994. * @return {boolean} Whether a split is required when assigning source to target.
  2995. */
  2996. needsSplitAssign( builder ) {
  2997. const { targetNode } = this;
  2998. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2999. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3000. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3001. return assignDifferentVector;
  3002. }
  3003. return false;
  3004. }
  3005. generate( builder, output ) {
  3006. const { targetNode, sourceNode } = this;
  3007. const needsSplitAssign = this.needsSplitAssign( builder );
  3008. const targetType = targetNode.getNodeType( builder );
  3009. const target = targetNode.context( { assign: true } ).build( builder );
  3010. const source = sourceNode.build( builder, targetType );
  3011. const sourceType = sourceNode.getNodeType( builder );
  3012. const nodeData = builder.getDataFromNode( this );
  3013. //
  3014. let snippet;
  3015. if ( nodeData.initialized === true ) {
  3016. if ( output !== 'void' ) {
  3017. snippet = target;
  3018. }
  3019. } else if ( needsSplitAssign ) {
  3020. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3021. const sourceProperty = builder.getPropertyName( sourceVar );
  3022. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3023. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  3024. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  3025. const component = targetNode.components[ i ];
  3026. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3027. }
  3028. if ( output !== 'void' ) {
  3029. snippet = target;
  3030. }
  3031. } else {
  3032. snippet = `${ target } = ${ source }`;
  3033. if ( output === 'void' || sourceType === 'void' ) {
  3034. builder.addLineFlowCode( snippet, this );
  3035. if ( output !== 'void' ) {
  3036. snippet = target;
  3037. }
  3038. }
  3039. }
  3040. nodeData.initialized = true;
  3041. return builder.format( snippet, targetType, output );
  3042. }
  3043. }
  3044. /**
  3045. * TSL function for creating an assign node.
  3046. *
  3047. * @tsl
  3048. * @function
  3049. * @param {Node} targetNode - The target node.
  3050. * @param {Node} sourceNode - The source type.
  3051. * @returns {AssignNode}
  3052. */
  3053. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  3054. addMethodChaining( 'assign', assign );
  3055. /**
  3056. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3057. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3058. * this logic.
  3059. *
  3060. * @augments TempNode
  3061. */
  3062. class FunctionCallNode extends TempNode {
  3063. static get type() {
  3064. return 'FunctionCallNode';
  3065. }
  3066. /**
  3067. * Constructs a new function call node.
  3068. *
  3069. * @param {?FunctionNode} functionNode - The function node.
  3070. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3071. */
  3072. constructor( functionNode = null, parameters = {} ) {
  3073. super();
  3074. /**
  3075. * The function node.
  3076. *
  3077. * @type {?FunctionNode}
  3078. * @default null
  3079. */
  3080. this.functionNode = functionNode;
  3081. /**
  3082. * The parameters of the function call.
  3083. *
  3084. * @type {Object<string, Node>}
  3085. * @default {}
  3086. */
  3087. this.parameters = parameters;
  3088. }
  3089. /**
  3090. * Sets the parameters of the function call node.
  3091. *
  3092. * @param {Object<string, Node>} parameters - The parameters to set.
  3093. * @return {FunctionCallNode} A reference to this node.
  3094. */
  3095. setParameters( parameters ) {
  3096. this.parameters = parameters;
  3097. return this;
  3098. }
  3099. /**
  3100. * Returns the parameters of the function call node.
  3101. *
  3102. * @return {Object<string, Node>} The parameters of this node.
  3103. */
  3104. getParameters() {
  3105. return this.parameters;
  3106. }
  3107. getNodeType( builder ) {
  3108. return this.functionNode.getNodeType( builder );
  3109. }
  3110. generate( builder ) {
  3111. const params = [];
  3112. const functionNode = this.functionNode;
  3113. const inputs = functionNode.getInputs( builder );
  3114. const parameters = this.parameters;
  3115. const generateInput = ( node, inputNode ) => {
  3116. const type = inputNode.type;
  3117. const pointer = type === 'pointer';
  3118. let output;
  3119. if ( pointer ) output = '&' + node.build( builder );
  3120. else output = node.build( builder, type );
  3121. return output;
  3122. };
  3123. if ( Array.isArray( parameters ) ) {
  3124. for ( let i = 0; i < parameters.length; i ++ ) {
  3125. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3126. }
  3127. } else {
  3128. for ( const inputNode of inputs ) {
  3129. const node = parameters[ inputNode.name ];
  3130. if ( node !== undefined ) {
  3131. params.push( generateInput( node, inputNode ) );
  3132. } else {
  3133. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  3134. }
  3135. }
  3136. }
  3137. const functionName = functionNode.build( builder, 'property' );
  3138. return `${functionName}( ${params.join( ', ' )} )`;
  3139. }
  3140. }
  3141. const call = ( func, ...params ) => {
  3142. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3143. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3144. };
  3145. addMethodChaining( 'call', call );
  3146. /**
  3147. * This node represents basic mathematical and logical operations like addition,
  3148. * subtraction or comparisons (e.g. `equal()`).
  3149. *
  3150. * @augments TempNode
  3151. */
  3152. class OperatorNode extends TempNode {
  3153. static get type() {
  3154. return 'OperatorNode';
  3155. }
  3156. /**
  3157. * Constructs a new operator node.
  3158. *
  3159. * @param {string} op - The operator.
  3160. * @param {Node} aNode - The first input.
  3161. * @param {Node} bNode - The second input.
  3162. * @param {...Node} params - Additional input parameters.
  3163. */
  3164. constructor( op, aNode, bNode, ...params ) {
  3165. super();
  3166. if ( params.length > 0 ) {
  3167. let finalOp = new OperatorNode( op, aNode, bNode );
  3168. for ( let i = 0; i < params.length - 1; i ++ ) {
  3169. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3170. }
  3171. aNode = finalOp;
  3172. bNode = params[ params.length - 1 ];
  3173. }
  3174. /**
  3175. * The operator.
  3176. *
  3177. * @type {string}
  3178. */
  3179. this.op = op;
  3180. /**
  3181. * The first input.
  3182. *
  3183. * @type {Node}
  3184. */
  3185. this.aNode = aNode;
  3186. /**
  3187. * The second input.
  3188. *
  3189. * @type {Node}
  3190. */
  3191. this.bNode = bNode;
  3192. /**
  3193. * This flag can be used for type testing.
  3194. *
  3195. * @type {boolean}
  3196. * @readonly
  3197. * @default true
  3198. */
  3199. this.isOperatorNode = true;
  3200. }
  3201. /**
  3202. * This method is overwritten since the node type is inferred from the operator
  3203. * and the input node types.
  3204. *
  3205. * @param {NodeBuilder} builder - The current node builder.
  3206. * @param {string} output - The current output string.
  3207. * @return {string} The node type.
  3208. */
  3209. getNodeType( builder, output ) {
  3210. const op = this.op;
  3211. const aNode = this.aNode;
  3212. const bNode = this.bNode;
  3213. const typeA = aNode.getNodeType( builder );
  3214. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3215. if ( typeA === 'void' || typeB === 'void' ) {
  3216. return 'void';
  3217. } else if ( op === '%' ) {
  3218. return typeA;
  3219. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3220. return builder.getIntegerType( typeA );
  3221. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3222. return 'bool';
  3223. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3224. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3225. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3226. } else {
  3227. // Handle matrix operations
  3228. if ( builder.isMatrix( typeA ) ) {
  3229. if ( typeB === 'float' ) {
  3230. return typeA; // matrix * scalar = matrix
  3231. } else if ( builder.isVector( typeB ) ) {
  3232. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3233. } else if ( builder.isMatrix( typeB ) ) {
  3234. return typeA; // matrix * matrix
  3235. }
  3236. } else if ( builder.isMatrix( typeB ) ) {
  3237. if ( typeA === 'float' ) {
  3238. return typeB; // scalar * matrix = matrix
  3239. } else if ( builder.isVector( typeA ) ) {
  3240. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3241. }
  3242. }
  3243. // Handle non-matrix cases
  3244. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3245. // anytype x anytype: use the greater length vector
  3246. return typeB;
  3247. }
  3248. return typeA;
  3249. }
  3250. }
  3251. generate( builder, output ) {
  3252. const op = this.op;
  3253. const aNode = this.aNode;
  3254. const bNode = this.bNode;
  3255. const type = this.getNodeType( builder, output );
  3256. let typeA = null;
  3257. let typeB = null;
  3258. if ( type !== 'void' ) {
  3259. typeA = aNode.getNodeType( builder );
  3260. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3261. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3262. if ( builder.isVector( typeA ) ) {
  3263. typeB = typeA;
  3264. } else if ( typeA !== typeB ) {
  3265. typeA = typeB = 'float';
  3266. }
  3267. } else if ( op === '>>' || op === '<<' ) {
  3268. typeA = type;
  3269. typeB = builder.changeComponentType( typeB, 'uint' );
  3270. } else if ( builder.isMatrix( typeA ) ) {
  3271. if ( typeB === 'float' ) {
  3272. // Keep matrix type for typeA, but ensure typeB stays float
  3273. typeB = 'float';
  3274. } else if ( builder.isVector( typeB ) ) {
  3275. // matrix x vector
  3276. typeB = builder.getVectorFromMatrix( typeA );
  3277. } else if ( builder.isMatrix( typeB ) ) ; else {
  3278. typeA = typeB = type;
  3279. }
  3280. } else if ( builder.isMatrix( typeB ) ) {
  3281. if ( typeA === 'float' ) {
  3282. // Keep matrix type for typeB, but ensure typeA stays float
  3283. typeA = 'float';
  3284. } else if ( builder.isVector( typeA ) ) {
  3285. // vector x matrix
  3286. typeA = builder.getVectorFromMatrix( typeB );
  3287. } else {
  3288. typeA = typeB = type;
  3289. }
  3290. } else {
  3291. // anytype x anytype
  3292. typeA = typeB = type;
  3293. }
  3294. } else {
  3295. typeA = typeB = type;
  3296. }
  3297. const a = aNode.build( builder, typeA );
  3298. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3299. const outputLength = builder.getTypeLength( output );
  3300. const fnOpSnippet = builder.getFunctionOperator( op );
  3301. if ( output !== 'void' ) {
  3302. if ( op === '<' && outputLength > 1 ) {
  3303. if ( builder.useComparisonMethod ) {
  3304. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3305. } else {
  3306. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3307. }
  3308. } else if ( op === '<=' && outputLength > 1 ) {
  3309. if ( builder.useComparisonMethod ) {
  3310. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3311. } else {
  3312. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3313. }
  3314. } else if ( op === '>' && outputLength > 1 ) {
  3315. if ( builder.useComparisonMethod ) {
  3316. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3317. } else {
  3318. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3319. }
  3320. } else if ( op === '>=' && outputLength > 1 ) {
  3321. if ( builder.useComparisonMethod ) {
  3322. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3323. } else {
  3324. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3325. }
  3326. } else if ( op === '!' || op === '~' ) {
  3327. return builder.format( `(${op}${a})`, typeA, output );
  3328. } else if ( fnOpSnippet ) {
  3329. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3330. } else {
  3331. // Handle matrix operations
  3332. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3333. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3334. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3335. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3336. } else {
  3337. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3338. }
  3339. }
  3340. } else if ( typeA !== 'void' ) {
  3341. if ( fnOpSnippet ) {
  3342. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3343. } else {
  3344. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3345. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3346. } else {
  3347. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3348. }
  3349. }
  3350. }
  3351. }
  3352. serialize( data ) {
  3353. super.serialize( data );
  3354. data.op = this.op;
  3355. }
  3356. deserialize( data ) {
  3357. super.deserialize( data );
  3358. this.op = data.op;
  3359. }
  3360. }
  3361. /**
  3362. * Returns the addition of two or more value.
  3363. *
  3364. * @tsl
  3365. * @function
  3366. * @param {Node} aNode - The first input.
  3367. * @param {Node} bNode - The second input.
  3368. * @param {...Node} params - Additional input parameters.
  3369. * @returns {OperatorNode}
  3370. */
  3371. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3372. /**
  3373. * Returns the subtraction of two or more value.
  3374. *
  3375. * @tsl
  3376. * @function
  3377. * @param {Node} aNode - The first input.
  3378. * @param {Node} bNode - The second input.
  3379. * @param {...Node} params - Additional input parameters.
  3380. * @returns {OperatorNode}
  3381. */
  3382. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3383. /**
  3384. * Returns the multiplication of two or more value.
  3385. *
  3386. * @tsl
  3387. * @function
  3388. * @param {Node} aNode - The first input.
  3389. * @param {Node} bNode - The second input.
  3390. * @param {...Node} params - Additional input parameters.
  3391. * @returns {OperatorNode}
  3392. */
  3393. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3394. /**
  3395. * Returns the division of two or more value.
  3396. *
  3397. * @tsl
  3398. * @function
  3399. * @param {Node} aNode - The first input.
  3400. * @param {Node} bNode - The second input.
  3401. * @param {...Node} params - Additional input parameters.
  3402. * @returns {OperatorNode}
  3403. */
  3404. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3405. /**
  3406. * Computes the remainder of dividing the first node by the second, for integer values.
  3407. *
  3408. * @tsl
  3409. * @function
  3410. * @param {Node} aNode - The first input.
  3411. * @param {Node} bNode - The second input.
  3412. * @returns {OperatorNode}
  3413. */
  3414. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3415. /**
  3416. * Checks if two nodes are equal.
  3417. *
  3418. * @tsl
  3419. * @function
  3420. * @param {Node} aNode - The first input.
  3421. * @param {Node} bNode - The second input.
  3422. * @returns {OperatorNode}
  3423. */
  3424. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3425. /**
  3426. * Checks if two nodes are not equal.
  3427. *
  3428. * @tsl
  3429. * @function
  3430. * @param {Node} aNode - The first input.
  3431. * @param {Node} bNode - The second input.
  3432. * @returns {OperatorNode}
  3433. */
  3434. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3435. /**
  3436. * Checks if the first node is less than the second.
  3437. *
  3438. * @tsl
  3439. * @function
  3440. * @param {Node} aNode - The first input.
  3441. * @param {Node} bNode - The second input.
  3442. * @returns {OperatorNode}
  3443. */
  3444. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3445. /**
  3446. * Checks if the first node is greater than the second.
  3447. *
  3448. * @tsl
  3449. * @function
  3450. * @param {Node} aNode - The first input.
  3451. * @param {Node} bNode - The second input.
  3452. * @returns {OperatorNode}
  3453. */
  3454. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3455. /**
  3456. * Checks if the first node is less than or equal to the second.
  3457. *
  3458. * @tsl
  3459. * @function
  3460. * @param {Node} aNode - The first input.
  3461. * @param {Node} bNode - The second input.
  3462. * @returns {OperatorNode}
  3463. */
  3464. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3465. /**
  3466. * Checks if the first node is greater than or equal to the second.
  3467. *
  3468. * @tsl
  3469. * @function
  3470. * @param {Node} aNode - The first input.
  3471. * @param {Node} bNode - The second input.
  3472. * @returns {OperatorNode}
  3473. */
  3474. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3475. /**
  3476. * Performs logical AND on two nodes.
  3477. *
  3478. * @tsl
  3479. * @function
  3480. * @param {Node} aNode - The first input.
  3481. * @param {Node} bNode - The second input.
  3482. * @returns {OperatorNode}
  3483. */
  3484. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3485. /**
  3486. * Performs logical OR on two nodes.
  3487. *
  3488. * @tsl
  3489. * @function
  3490. * @param {Node} aNode - The first input.
  3491. * @param {Node} bNode - The second input.
  3492. * @returns {OperatorNode}
  3493. */
  3494. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3495. /**
  3496. * Performs logical NOT on a node.
  3497. *
  3498. * @tsl
  3499. * @function
  3500. * @param {Node} aNode - The first input.
  3501. * @param {Node} bNode - The second input.
  3502. * @returns {OperatorNode}
  3503. */
  3504. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3505. /**
  3506. * Performs logical XOR on two nodes.
  3507. *
  3508. * @tsl
  3509. * @function
  3510. * @param {Node} aNode - The first input.
  3511. * @param {Node} bNode - The second input.
  3512. * @returns {OperatorNode}
  3513. */
  3514. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3515. /**
  3516. * Performs bitwise AND on two nodes.
  3517. *
  3518. * @tsl
  3519. * @function
  3520. * @param {Node} aNode - The first input.
  3521. * @param {Node} bNode - The second input.
  3522. * @returns {OperatorNode}
  3523. */
  3524. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3525. /**
  3526. * Performs bitwise NOT on a node.
  3527. *
  3528. * @tsl
  3529. * @function
  3530. * @param {Node} aNode - The first input.
  3531. * @param {Node} bNode - The second input.
  3532. * @returns {OperatorNode}
  3533. */
  3534. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3535. /**
  3536. * Performs bitwise OR on two nodes.
  3537. *
  3538. * @tsl
  3539. * @function
  3540. * @param {Node} aNode - The first input.
  3541. * @param {Node} bNode - The second input.
  3542. * @returns {OperatorNode}
  3543. */
  3544. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3545. /**
  3546. * Performs bitwise XOR on two nodes.
  3547. *
  3548. * @tsl
  3549. * @function
  3550. * @param {Node} aNode - The first input.
  3551. * @param {Node} bNode - The second input.
  3552. * @returns {OperatorNode}
  3553. */
  3554. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3555. /**
  3556. * Shifts a node to the left.
  3557. *
  3558. * @tsl
  3559. * @function
  3560. * @param {Node} aNode - The node to shift.
  3561. * @param {Node} bNode - The value to shift.
  3562. * @returns {OperatorNode}
  3563. */
  3564. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3565. /**
  3566. * Shifts a node to the right.
  3567. *
  3568. * @tsl
  3569. * @function
  3570. * @param {Node} aNode - The node to shift.
  3571. * @param {Node} bNode - The value to shift.
  3572. * @returns {OperatorNode}
  3573. */
  3574. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3575. addMethodChaining( 'add', add );
  3576. addMethodChaining( 'sub', sub );
  3577. addMethodChaining( 'mul', mul );
  3578. addMethodChaining( 'div', div );
  3579. addMethodChaining( 'modInt', modInt );
  3580. addMethodChaining( 'equal', equal );
  3581. addMethodChaining( 'notEqual', notEqual );
  3582. addMethodChaining( 'lessThan', lessThan );
  3583. addMethodChaining( 'greaterThan', greaterThan );
  3584. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3585. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3586. addMethodChaining( 'and', and );
  3587. addMethodChaining( 'or', or );
  3588. addMethodChaining( 'not', not );
  3589. addMethodChaining( 'xor', xor );
  3590. addMethodChaining( 'bitAnd', bitAnd );
  3591. addMethodChaining( 'bitNot', bitNot );
  3592. addMethodChaining( 'bitOr', bitOr );
  3593. addMethodChaining( 'bitXor', bitXor );
  3594. addMethodChaining( 'shiftLeft', shiftLeft );
  3595. addMethodChaining( 'shiftRight', shiftRight );
  3596. /**
  3597. * @tsl
  3598. * @function
  3599. * @deprecated since r168. Use {@link modInt} instead.
  3600. *
  3601. * @param {...any} params
  3602. * @returns {Function}
  3603. */
  3604. const remainder = ( ...params ) => { // @deprecated, r168
  3605. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3606. return modInt( ...params );
  3607. };
  3608. addMethodChaining( 'remainder', remainder );
  3609. /**
  3610. * This node represents a variety of mathematical methods available in shaders.
  3611. * They are divided into three categories:
  3612. *
  3613. * - Methods with one input like `sin`, `cos` or `normalize`.
  3614. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3615. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3616. *
  3617. * @augments TempNode
  3618. */
  3619. class MathNode extends TempNode {
  3620. static get type() {
  3621. return 'MathNode';
  3622. }
  3623. /**
  3624. * Constructs a new math node.
  3625. *
  3626. * @param {string} method - The method name.
  3627. * @param {Node} aNode - The first input.
  3628. * @param {?Node} [bNode=null] - The second input.
  3629. * @param {?Node} [cNode=null] - The third input.
  3630. */
  3631. constructor( method, aNode, bNode = null, cNode = null ) {
  3632. super();
  3633. /**
  3634. * The method name.
  3635. *
  3636. * @type {string}
  3637. */
  3638. this.method = method;
  3639. /**
  3640. * The first input.
  3641. *
  3642. * @type {Node}
  3643. */
  3644. this.aNode = aNode;
  3645. /**
  3646. * The second input.
  3647. *
  3648. * @type {?Node}
  3649. * @default null
  3650. */
  3651. this.bNode = bNode;
  3652. /**
  3653. * The third input.
  3654. *
  3655. * @type {?Node}
  3656. * @default null
  3657. */
  3658. this.cNode = cNode;
  3659. /**
  3660. * This flag can be used for type testing.
  3661. *
  3662. * @type {boolean}
  3663. * @readonly
  3664. * @default true
  3665. */
  3666. this.isMathNode = true;
  3667. }
  3668. /**
  3669. * The input type is inferred from the node types of the input nodes.
  3670. *
  3671. * @param {NodeBuilder} builder - The current node builder.
  3672. * @return {string} The input type.
  3673. */
  3674. getInputType( builder ) {
  3675. const aType = this.aNode.getNodeType( builder );
  3676. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3677. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3678. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3679. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3680. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3681. if ( aLen > bLen && aLen > cLen ) {
  3682. return aType;
  3683. } else if ( bLen > cLen ) {
  3684. return bType;
  3685. } else if ( cLen > aLen ) {
  3686. return cType;
  3687. }
  3688. return aType;
  3689. }
  3690. /**
  3691. * The selected method as well as the input type determine the node type of this node.
  3692. *
  3693. * @param {NodeBuilder} builder - The current node builder.
  3694. * @return {string} The node type.
  3695. */
  3696. getNodeType( builder ) {
  3697. const method = this.method;
  3698. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3699. return 'float';
  3700. } else if ( method === MathNode.CROSS ) {
  3701. return 'vec3';
  3702. } else if ( method === MathNode.ALL ) {
  3703. return 'bool';
  3704. } else if ( method === MathNode.EQUALS ) {
  3705. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3706. } else if ( method === MathNode.MOD ) {
  3707. return this.aNode.getNodeType( builder );
  3708. } else {
  3709. return this.getInputType( builder );
  3710. }
  3711. }
  3712. generate( builder, output ) {
  3713. let method = this.method;
  3714. const type = this.getNodeType( builder );
  3715. const inputType = this.getInputType( builder );
  3716. const a = this.aNode;
  3717. const b = this.bNode;
  3718. const c = this.cNode;
  3719. const coordinateSystem = builder.renderer.coordinateSystem;
  3720. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3721. // dir can be either a direction vector or a normal vector
  3722. // upper-left 3x3 of matrix is assumed to be orthogonal
  3723. let tA = a;
  3724. let tB = b;
  3725. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3726. tB = vec4( vec3( tB ), 0.0 );
  3727. } else {
  3728. tA = vec4( vec3( tA ), 0.0 );
  3729. }
  3730. const mulNode = mul( tA, tB ).xyz;
  3731. return normalize( mulNode ).build( builder, output );
  3732. } else if ( method === MathNode.NEGATE ) {
  3733. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3734. } else if ( method === MathNode.ONE_MINUS ) {
  3735. return sub( 1.0, a ).build( builder, output );
  3736. } else if ( method === MathNode.RECIPROCAL ) {
  3737. return div( 1.0, a ).build( builder, output );
  3738. } else if ( method === MathNode.DIFFERENCE ) {
  3739. return abs( sub( a, b ) ).build( builder, output );
  3740. } else {
  3741. const params = [];
  3742. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3743. params.push(
  3744. a.build( builder, type ),
  3745. b.build( builder, type )
  3746. );
  3747. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3748. params.push(
  3749. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3750. b.build( builder, inputType )
  3751. );
  3752. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3753. params.push(
  3754. a.build( builder, inputType ),
  3755. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3756. );
  3757. } else if ( method === MathNode.REFRACT ) {
  3758. params.push(
  3759. a.build( builder, inputType ),
  3760. b.build( builder, inputType ),
  3761. c.build( builder, 'float' )
  3762. );
  3763. } else if ( method === MathNode.MIX ) {
  3764. params.push(
  3765. a.build( builder, inputType ),
  3766. b.build( builder, inputType ),
  3767. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3768. );
  3769. } else {
  3770. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3771. method = 'atan2';
  3772. }
  3773. params.push( a.build( builder, inputType ) );
  3774. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3775. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3776. }
  3777. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3778. }
  3779. }
  3780. serialize( data ) {
  3781. super.serialize( data );
  3782. data.method = this.method;
  3783. }
  3784. deserialize( data ) {
  3785. super.deserialize( data );
  3786. this.method = data.method;
  3787. }
  3788. }
  3789. // 1 input
  3790. MathNode.ALL = 'all';
  3791. MathNode.ANY = 'any';
  3792. MathNode.RADIANS = 'radians';
  3793. MathNode.DEGREES = 'degrees';
  3794. MathNode.EXP = 'exp';
  3795. MathNode.EXP2 = 'exp2';
  3796. MathNode.LOG = 'log';
  3797. MathNode.LOG2 = 'log2';
  3798. MathNode.SQRT = 'sqrt';
  3799. MathNode.INVERSE_SQRT = 'inversesqrt';
  3800. MathNode.FLOOR = 'floor';
  3801. MathNode.CEIL = 'ceil';
  3802. MathNode.NORMALIZE = 'normalize';
  3803. MathNode.FRACT = 'fract';
  3804. MathNode.SIN = 'sin';
  3805. MathNode.COS = 'cos';
  3806. MathNode.TAN = 'tan';
  3807. MathNode.ASIN = 'asin';
  3808. MathNode.ACOS = 'acos';
  3809. MathNode.ATAN = 'atan';
  3810. MathNode.ABS = 'abs';
  3811. MathNode.SIGN = 'sign';
  3812. MathNode.LENGTH = 'length';
  3813. MathNode.NEGATE = 'negate';
  3814. MathNode.ONE_MINUS = 'oneMinus';
  3815. MathNode.DFDX = 'dFdx';
  3816. MathNode.DFDY = 'dFdy';
  3817. MathNode.ROUND = 'round';
  3818. MathNode.RECIPROCAL = 'reciprocal';
  3819. MathNode.TRUNC = 'trunc';
  3820. MathNode.FWIDTH = 'fwidth';
  3821. MathNode.TRANSPOSE = 'transpose';
  3822. // 2 inputs
  3823. MathNode.BITCAST = 'bitcast';
  3824. MathNode.EQUALS = 'equals';
  3825. MathNode.MIN = 'min';
  3826. MathNode.MAX = 'max';
  3827. MathNode.MOD = 'mod';
  3828. MathNode.STEP = 'step';
  3829. MathNode.REFLECT = 'reflect';
  3830. MathNode.DISTANCE = 'distance';
  3831. MathNode.DIFFERENCE = 'difference';
  3832. MathNode.DOT = 'dot';
  3833. MathNode.CROSS = 'cross';
  3834. MathNode.POW = 'pow';
  3835. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3836. // 3 inputs
  3837. MathNode.MIX = 'mix';
  3838. MathNode.CLAMP = 'clamp';
  3839. MathNode.REFRACT = 'refract';
  3840. MathNode.SMOOTHSTEP = 'smoothstep';
  3841. MathNode.FACEFORWARD = 'faceforward';
  3842. // 1 inputs
  3843. /**
  3844. * A small value used to handle floating-point precision errors.
  3845. *
  3846. * @tsl
  3847. * @type {Node<float>}
  3848. */
  3849. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3850. /**
  3851. * Represents infinity.
  3852. *
  3853. * @tsl
  3854. * @type {Node<float>}
  3855. */
  3856. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3857. /**
  3858. * Represents PI.
  3859. *
  3860. * @tsl
  3861. * @type {Node<float>}
  3862. */
  3863. const PI = /*@__PURE__*/ float( Math.PI );
  3864. /**
  3865. * Represents PI * 2.
  3866. *
  3867. * @tsl
  3868. * @type {Node<float>}
  3869. */
  3870. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3871. /**
  3872. * Returns `true` if all components of `x` are `true`.
  3873. *
  3874. * @tsl
  3875. * @function
  3876. * @param {Node | number} x - The parameter.
  3877. * @returns {Node<bool>}
  3878. */
  3879. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3880. /**
  3881. * Returns `true` if any components of `x` are `true`.
  3882. *
  3883. * @tsl
  3884. * @function
  3885. * @param {Node | number} x - The parameter.
  3886. * @returns {Node<bool>}
  3887. */
  3888. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3889. /**
  3890. * Converts a quantity in degrees to radians.
  3891. *
  3892. * @tsl
  3893. * @function
  3894. * @param {Node | number} x - The input in degrees.
  3895. * @returns {Node}
  3896. */
  3897. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3898. /**
  3899. * Convert a quantity in radians to degrees.
  3900. *
  3901. * @tsl
  3902. * @function
  3903. * @param {Node | number} x - The input in radians.
  3904. * @returns {Node}
  3905. */
  3906. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3907. /**
  3908. * Returns the natural exponentiation of the parameter.
  3909. *
  3910. * @tsl
  3911. * @function
  3912. * @param {Node | number} x - The parameter.
  3913. * @returns {Node}
  3914. */
  3915. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3916. /**
  3917. * Returns 2 raised to the power of the parameter.
  3918. *
  3919. * @tsl
  3920. * @function
  3921. * @param {Node | number} x - The parameter.
  3922. * @returns {Node}
  3923. */
  3924. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3925. /**
  3926. * Returns the natural logarithm of the parameter.
  3927. *
  3928. * @tsl
  3929. * @function
  3930. * @param {Node | number} x - The parameter.
  3931. * @returns {Node}
  3932. */
  3933. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3934. /**
  3935. * Returns the base 2 logarithm of the parameter.
  3936. *
  3937. * @tsl
  3938. * @function
  3939. * @param {Node | number} x - The parameter.
  3940. * @returns {Node}
  3941. */
  3942. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3943. /**
  3944. * Returns the square root of the parameter.
  3945. *
  3946. * @tsl
  3947. * @function
  3948. * @param {Node | number} x - The parameter.
  3949. * @returns {Node}
  3950. */
  3951. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3952. /**
  3953. * Returns the inverse of the square root of the parameter.
  3954. *
  3955. * @tsl
  3956. * @function
  3957. * @param {Node | number} x - The parameter.
  3958. * @returns {Node}
  3959. */
  3960. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3961. /**
  3962. * Finds the nearest integer less than or equal to the parameter.
  3963. *
  3964. * @tsl
  3965. * @function
  3966. * @param {Node | number} x - The parameter.
  3967. * @returns {Node}
  3968. */
  3969. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3970. /**
  3971. * Finds the nearest integer that is greater than or equal to the parameter.
  3972. *
  3973. * @tsl
  3974. * @function
  3975. * @param {Node | number} x - The parameter.
  3976. * @returns {Node}
  3977. */
  3978. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3979. /**
  3980. * Calculates the unit vector in the same direction as the original vector.
  3981. *
  3982. * @tsl
  3983. * @function
  3984. * @param {Node} x - The input vector.
  3985. * @returns {Node}
  3986. */
  3987. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3988. /**
  3989. * Computes the fractional part of the parameter.
  3990. *
  3991. * @tsl
  3992. * @function
  3993. * @param {Node | number} x - The parameter.
  3994. * @returns {Node}
  3995. */
  3996. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3997. /**
  3998. * Returns the sine of the parameter.
  3999. *
  4000. * @tsl
  4001. * @function
  4002. * @param {Node | number} x - The parameter.
  4003. * @returns {Node}
  4004. */
  4005. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  4006. /**
  4007. * Returns the cosine of the parameter.
  4008. *
  4009. * @tsl
  4010. * @function
  4011. * @param {Node | number} x - The parameter.
  4012. * @returns {Node}
  4013. */
  4014. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  4015. /**
  4016. * Returns the tangent of the parameter.
  4017. *
  4018. * @tsl
  4019. * @function
  4020. * @param {Node | number} x - The parameter.
  4021. * @returns {Node}
  4022. */
  4023. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  4024. /**
  4025. * Returns the arcsine of the parameter.
  4026. *
  4027. * @tsl
  4028. * @function
  4029. * @param {Node | number} x - The parameter.
  4030. * @returns {Node}
  4031. */
  4032. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  4033. /**
  4034. * Returns the arccosine of the parameter.
  4035. *
  4036. * @tsl
  4037. * @function
  4038. * @param {Node | number} x - The parameter.
  4039. * @returns {Node}
  4040. */
  4041. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  4042. /**
  4043. * Returns the arc-tangent of the parameter.
  4044. * If two parameters are provided, the result is `atan2(y/x)`.
  4045. *
  4046. * @tsl
  4047. * @function
  4048. * @param {Node | number} y - The y parameter.
  4049. * @param {?(Node | number)} x - The x parameter.
  4050. * @returns {Node}
  4051. */
  4052. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  4053. /**
  4054. * Returns the absolute value of the parameter.
  4055. *
  4056. * @tsl
  4057. * @function
  4058. * @param {Node | number} x - The parameter.
  4059. * @returns {Node}
  4060. */
  4061. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  4062. /**
  4063. * Extracts the sign of the parameter.
  4064. *
  4065. * @tsl
  4066. * @function
  4067. * @param {Node | number} x - The parameter.
  4068. * @returns {Node}
  4069. */
  4070. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  4071. /**
  4072. * Calculates the length of a vector.
  4073. *
  4074. * @tsl
  4075. * @function
  4076. * @param {Node} x - The parameter.
  4077. * @returns {Node<float>}
  4078. */
  4079. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  4080. /**
  4081. * Negates the value of the parameter (-x).
  4082. *
  4083. * @tsl
  4084. * @function
  4085. * @param {Node | number} x - The parameter.
  4086. * @returns {Node}
  4087. */
  4088. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  4089. /**
  4090. * Return `1` minus the parameter.
  4091. *
  4092. * @tsl
  4093. * @function
  4094. * @param {Node | number} x - The parameter.
  4095. * @returns {Node}
  4096. */
  4097. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  4098. /**
  4099. * Returns the partial derivative of the parameter with respect to x.
  4100. *
  4101. * @tsl
  4102. * @function
  4103. * @param {Node | number} x - The parameter.
  4104. * @returns {Node}
  4105. */
  4106. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  4107. /**
  4108. * Returns the partial derivative of the parameter with respect to y.
  4109. *
  4110. * @tsl
  4111. * @function
  4112. * @param {Node | number} x - The parameter.
  4113. * @returns {Node}
  4114. */
  4115. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  4116. /**
  4117. * Rounds the parameter to the nearest integer.
  4118. *
  4119. * @tsl
  4120. * @function
  4121. * @param {Node | number} x - The parameter.
  4122. * @returns {Node}
  4123. */
  4124. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  4125. /**
  4126. * Returns the reciprocal of the parameter `(1/x)`.
  4127. *
  4128. * @tsl
  4129. * @function
  4130. * @param {Node | number} x - The parameter.
  4131. * @returns {Node}
  4132. */
  4133. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  4134. /**
  4135. * Truncates the parameter, removing the fractional part.
  4136. *
  4137. * @tsl
  4138. * @function
  4139. * @param {Node | number} x - The parameter.
  4140. * @returns {Node}
  4141. */
  4142. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  4143. /**
  4144. * Returns the sum of the absolute derivatives in x and y.
  4145. *
  4146. * @tsl
  4147. * @function
  4148. * @param {Node | number} x - The parameter.
  4149. * @returns {Node}
  4150. */
  4151. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  4152. /**
  4153. * Returns the transpose of a matrix.
  4154. *
  4155. * @tsl
  4156. * @function
  4157. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4158. * @returns {Node}
  4159. */
  4160. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  4161. // 2 inputs
  4162. /**
  4163. * Reinterpret the bit representation of a value in one type as a value in another type.
  4164. *
  4165. * @tsl
  4166. * @function
  4167. * @param {Node | number} x - The parameter.
  4168. * @param {string} y - The new type.
  4169. * @returns {Node}
  4170. */
  4171. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  4172. /**
  4173. * Returns `true` if `x` equals `y`.
  4174. *
  4175. * @tsl
  4176. * @function
  4177. * @param {Node | number} x - The first parameter.
  4178. * @param {Node | number} y - The second parameter.
  4179. * @returns {Node<bool>}
  4180. */
  4181. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  4182. /**
  4183. * Returns the lesser of two values.
  4184. *
  4185. * @tsl
  4186. * @function
  4187. * @param {Node | number} x - The y parameter.
  4188. * @param {Node | number} y - The x parameter.
  4189. * @returns {Node}
  4190. */
  4191. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  4192. /**
  4193. * Returns the greater of two values.
  4194. *
  4195. * @tsl
  4196. * @function
  4197. * @param {Node | number} x - The y parameter.
  4198. * @param {Node | number} y - The x parameter.
  4199. * @returns {Node}
  4200. */
  4201. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  4202. /**
  4203. * Computes the remainder of dividing the first node by the second one.
  4204. *
  4205. * @tsl
  4206. * @function
  4207. * @param {Node | number} x - The y parameter.
  4208. * @param {Node | number} y - The x parameter.
  4209. * @returns {Node}
  4210. */
  4211. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  4212. /**
  4213. * Generate a step function by comparing two values.
  4214. *
  4215. * @tsl
  4216. * @function
  4217. * @param {Node | number} x - The y parameter.
  4218. * @param {Node | number} y - The x parameter.
  4219. * @returns {Node}
  4220. */
  4221. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  4222. /**
  4223. * Calculates the reflection direction for an incident vector.
  4224. *
  4225. * @tsl
  4226. * @function
  4227. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4228. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4229. * @returns {Node<vec2|vec3|vec4>}
  4230. */
  4231. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  4232. /**
  4233. * Calculates the distance between two points.
  4234. *
  4235. * @tsl
  4236. * @function
  4237. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4238. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4239. * @returns {Node<float>}
  4240. */
  4241. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  4242. /**
  4243. * Calculates the absolute difference between two values.
  4244. *
  4245. * @tsl
  4246. * @function
  4247. * @param {Node | number} x - The first parameter.
  4248. * @param {Node | number} y - The second parameter.
  4249. * @returns {Node}
  4250. */
  4251. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  4252. /**
  4253. * Calculates the dot product of two vectors.
  4254. *
  4255. * @tsl
  4256. * @function
  4257. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4258. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4259. * @returns {Node<float>}
  4260. */
  4261. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  4262. /**
  4263. * Calculates the cross product of two vectors.
  4264. *
  4265. * @tsl
  4266. * @function
  4267. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4268. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4269. * @returns {Node<vec2|vec3|vec4>}
  4270. */
  4271. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  4272. /**
  4273. * Return the value of the first parameter raised to the power of the second one.
  4274. *
  4275. * @tsl
  4276. * @function
  4277. * @param {Node | number} x - The first parameter.
  4278. * @param {Node | number} y - The second parameter.
  4279. * @returns {Node}
  4280. */
  4281. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  4282. /**
  4283. * Returns the square of the parameter.
  4284. *
  4285. * @tsl
  4286. * @function
  4287. * @param {Node | number} x - The first parameter.
  4288. * @returns {Node}
  4289. */
  4290. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4291. /**
  4292. * Returns the cube of the parameter.
  4293. *
  4294. * @tsl
  4295. * @function
  4296. * @param {Node | number} x - The first parameter.
  4297. * @returns {Node}
  4298. */
  4299. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4300. /**
  4301. * Returns the fourth power of the parameter.
  4302. *
  4303. * @tsl
  4304. * @function
  4305. * @param {Node | number} x - The first parameter.
  4306. * @returns {Node}
  4307. */
  4308. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4309. /**
  4310. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4311. *
  4312. * @tsl
  4313. * @function
  4314. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4315. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4316. * @returns {Node}
  4317. */
  4318. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4319. /**
  4320. * Returns the cube root of a number.
  4321. *
  4322. * @tsl
  4323. * @function
  4324. * @param {Node | number} a - The first parameter.
  4325. * @returns {Node}
  4326. */
  4327. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4328. /**
  4329. * Calculate the squared length of a vector.
  4330. *
  4331. * @tsl
  4332. * @function
  4333. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4334. * @returns {Node<float>}
  4335. */
  4336. const lengthSq = ( a ) => dot( a, a );
  4337. /**
  4338. * Linearly interpolates between two values.
  4339. *
  4340. * @tsl
  4341. * @function
  4342. * @param {Node | number} a - The first parameter.
  4343. * @param {Node | number} b - The second parameter.
  4344. * @param {Node | number} t - The interpolation value.
  4345. * @returns {Node}
  4346. */
  4347. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4348. /**
  4349. * Constrains a value to lie between two further values.
  4350. *
  4351. * @tsl
  4352. * @function
  4353. * @param {Node | number} value - The value to constrain.
  4354. * @param {Node | number} [low=0] - The lower bound.
  4355. * @param {Node | number} [high=1] - The upper bound.
  4356. * @returns {Node}
  4357. */
  4358. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4359. /**
  4360. * Constrains a value between `0` and `1`.
  4361. *
  4362. * @tsl
  4363. * @function
  4364. * @param {Node | number} value - The value to constrain.
  4365. * @returns {Node}
  4366. */
  4367. const saturate = ( value ) => clamp( value );
  4368. /**
  4369. * Calculates the refraction direction for an incident vector.
  4370. *
  4371. * @tsl
  4372. * @function
  4373. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4374. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4375. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4376. * @returns {Node<vec2|vec3|vec4>}
  4377. */
  4378. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4379. /**
  4380. * Performs a Hermite interpolation between two values.
  4381. *
  4382. * @tsl
  4383. * @function
  4384. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4385. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4386. * @param {Node | number} x - The source value for interpolation.
  4387. * @returns {Node}
  4388. */
  4389. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4390. /**
  4391. * Returns a vector pointing in the same direction as another.
  4392. *
  4393. * @tsl
  4394. * @function
  4395. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4396. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4397. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4398. * @returns {Node<vec2|vec3|vec4>}
  4399. */
  4400. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4401. /**
  4402. * Returns a random value for the given uv.
  4403. *
  4404. * @tsl
  4405. * @function
  4406. * @param {Node<vec2>} uv - The uv node.
  4407. * @returns {Node<float>}
  4408. */
  4409. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4410. const a = 12.9898, b = 78.233, c = 43758.5453;
  4411. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4412. return fract( sin( sn ).mul( c ) );
  4413. } );
  4414. /**
  4415. * Alias for `mix()` with a different parameter order.
  4416. *
  4417. * @tsl
  4418. * @function
  4419. * @param {Node | number} t - The interpolation value.
  4420. * @param {Node | number} e1 - The first parameter.
  4421. * @param {Node | number} e2 - The second parameter.
  4422. * @returns {Node}
  4423. */
  4424. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4425. /**
  4426. * Alias for `smoothstep()` with a different parameter order.
  4427. *
  4428. * @tsl
  4429. * @function
  4430. * @param {Node | number} x - The source value for interpolation.
  4431. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4432. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4433. * @returns {Node}
  4434. */
  4435. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4436. /**
  4437. * Returns the arc-tangent of the quotient of its parameters.
  4438. *
  4439. * @tsl
  4440. * @function
  4441. * @deprecated since r172. Use {@link atan} instead.
  4442. *
  4443. * @param {Node | number} y - The y parameter.
  4444. * @param {Node | number} x - The x parameter.
  4445. * @returns {Node}
  4446. */
  4447. const atan2 = ( y, x ) => { // @deprecated, r172
  4448. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4449. return atan( y, x );
  4450. };
  4451. // GLSL alias function
  4452. const faceforward = faceForward;
  4453. const inversesqrt = inverseSqrt;
  4454. // Method chaining
  4455. addMethodChaining( 'all', all );
  4456. addMethodChaining( 'any', any );
  4457. addMethodChaining( 'equals', equals );
  4458. addMethodChaining( 'radians', radians );
  4459. addMethodChaining( 'degrees', degrees );
  4460. addMethodChaining( 'exp', exp );
  4461. addMethodChaining( 'exp2', exp2 );
  4462. addMethodChaining( 'log', log );
  4463. addMethodChaining( 'log2', log2 );
  4464. addMethodChaining( 'sqrt', sqrt );
  4465. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4466. addMethodChaining( 'floor', floor );
  4467. addMethodChaining( 'ceil', ceil );
  4468. addMethodChaining( 'normalize', normalize );
  4469. addMethodChaining( 'fract', fract );
  4470. addMethodChaining( 'sin', sin );
  4471. addMethodChaining( 'cos', cos );
  4472. addMethodChaining( 'tan', tan );
  4473. addMethodChaining( 'asin', asin );
  4474. addMethodChaining( 'acos', acos );
  4475. addMethodChaining( 'atan', atan );
  4476. addMethodChaining( 'abs', abs );
  4477. addMethodChaining( 'sign', sign );
  4478. addMethodChaining( 'length', length );
  4479. addMethodChaining( 'lengthSq', lengthSq );
  4480. addMethodChaining( 'negate', negate );
  4481. addMethodChaining( 'oneMinus', oneMinus );
  4482. addMethodChaining( 'dFdx', dFdx );
  4483. addMethodChaining( 'dFdy', dFdy );
  4484. addMethodChaining( 'round', round );
  4485. addMethodChaining( 'reciprocal', reciprocal );
  4486. addMethodChaining( 'trunc', trunc );
  4487. addMethodChaining( 'fwidth', fwidth );
  4488. addMethodChaining( 'atan2', atan2 );
  4489. addMethodChaining( 'min', min$1 );
  4490. addMethodChaining( 'max', max$1 );
  4491. addMethodChaining( 'mod', mod );
  4492. addMethodChaining( 'step', step );
  4493. addMethodChaining( 'reflect', reflect );
  4494. addMethodChaining( 'distance', distance );
  4495. addMethodChaining( 'dot', dot );
  4496. addMethodChaining( 'cross', cross );
  4497. addMethodChaining( 'pow', pow );
  4498. addMethodChaining( 'pow2', pow2 );
  4499. addMethodChaining( 'pow3', pow3 );
  4500. addMethodChaining( 'pow4', pow4 );
  4501. addMethodChaining( 'transformDirection', transformDirection );
  4502. addMethodChaining( 'mix', mixElement );
  4503. addMethodChaining( 'clamp', clamp );
  4504. addMethodChaining( 'refract', refract );
  4505. addMethodChaining( 'smoothstep', smoothstepElement );
  4506. addMethodChaining( 'faceForward', faceForward );
  4507. addMethodChaining( 'difference', difference );
  4508. addMethodChaining( 'saturate', saturate );
  4509. addMethodChaining( 'cbrt', cbrt );
  4510. addMethodChaining( 'transpose', transpose );
  4511. addMethodChaining( 'rand', rand );
  4512. /**
  4513. * Represents a logical `if/else` statement. Can be used as an alternative
  4514. * to the `If()`/`Else()` syntax.
  4515. *
  4516. * The corresponding TSL `select()` looks like so:
  4517. * ```js
  4518. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4519. * ```
  4520. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4521. * determine the outcome of the entire statement.
  4522. *
  4523. * @augments Node
  4524. */
  4525. class ConditionalNode extends Node {
  4526. static get type() {
  4527. return 'ConditionalNode';
  4528. }
  4529. /**
  4530. * Constructs a new conditional node.
  4531. *
  4532. * @param {Node} condNode - The node that defines the condition.
  4533. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4534. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4535. */
  4536. constructor( condNode, ifNode, elseNode = null ) {
  4537. super();
  4538. /**
  4539. * The node that defines the condition.
  4540. *
  4541. * @type {Node}
  4542. */
  4543. this.condNode = condNode;
  4544. /**
  4545. * The node that is evaluate when the condition ends up `true`.
  4546. *
  4547. * @type {Node}
  4548. */
  4549. this.ifNode = ifNode;
  4550. /**
  4551. * The node that is evaluate when the condition ends up `false`.
  4552. *
  4553. * @type {?Node}
  4554. * @default null
  4555. */
  4556. this.elseNode = elseNode;
  4557. }
  4558. /**
  4559. * This method is overwritten since the node type is inferred from the if/else
  4560. * nodes.
  4561. *
  4562. * @param {NodeBuilder} builder - The current node builder.
  4563. * @return {string} The node type.
  4564. */
  4565. getNodeType( builder ) {
  4566. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4567. if ( ifNode === undefined ) {
  4568. // fallback setup
  4569. this.setup( builder );
  4570. return this.getNodeType( builder );
  4571. }
  4572. const ifType = ifNode.getNodeType( builder );
  4573. if ( elseNode !== null ) {
  4574. const elseType = elseNode.getNodeType( builder );
  4575. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4576. return elseType;
  4577. }
  4578. }
  4579. return ifType;
  4580. }
  4581. setup( builder ) {
  4582. const condNode = this.condNode.cache();
  4583. const ifNode = this.ifNode.cache();
  4584. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4585. //
  4586. const currentNodeBlock = builder.context.nodeBlock;
  4587. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4588. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4589. //
  4590. const properties = builder.getNodeProperties( this );
  4591. properties.condNode = condNode;
  4592. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4593. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4594. }
  4595. generate( builder, output ) {
  4596. const type = this.getNodeType( builder );
  4597. const nodeData = builder.getDataFromNode( this );
  4598. if ( nodeData.nodeProperty !== undefined ) {
  4599. return nodeData.nodeProperty;
  4600. }
  4601. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4602. const needsOutput = output !== 'void';
  4603. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4604. nodeData.nodeProperty = nodeProperty;
  4605. const nodeSnippet = condNode.build( builder, 'bool' );
  4606. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4607. let ifSnippet = ifNode.build( builder, type );
  4608. if ( ifSnippet ) {
  4609. if ( needsOutput ) {
  4610. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4611. } else {
  4612. ifSnippet = 'return ' + ifSnippet + ';';
  4613. }
  4614. }
  4615. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4616. if ( elseNode !== null ) {
  4617. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4618. let elseSnippet = elseNode.build( builder, type );
  4619. if ( elseSnippet ) {
  4620. if ( needsOutput ) {
  4621. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4622. } else {
  4623. elseSnippet = 'return ' + elseSnippet + ';';
  4624. }
  4625. }
  4626. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4627. } else {
  4628. builder.addFlowCode( '\n\n' );
  4629. }
  4630. return builder.format( nodeProperty, type, output );
  4631. }
  4632. }
  4633. /**
  4634. * TSL function for creating a conditional node.
  4635. *
  4636. * @tsl
  4637. * @function
  4638. * @param {Node} condNode - The node that defines the condition.
  4639. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4640. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4641. * @returns {ConditionalNode}
  4642. */
  4643. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4644. addMethodChaining( 'select', select );
  4645. // Deprecated
  4646. /**
  4647. * @tsl
  4648. * @function
  4649. * @deprecated since r168. Use {@link select} instead.
  4650. *
  4651. * @param {...any} params
  4652. * @returns {ConditionalNode}
  4653. */
  4654. const cond = ( ...params ) => { // @deprecated, r168
  4655. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4656. return select( ...params );
  4657. };
  4658. addMethodChaining( 'cond', cond );
  4659. /**
  4660. * This node can be used as a context management component for another node.
  4661. * {@link NodeBuilder} performs its node building process in a specific context and
  4662. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4663. *
  4664. * ```js
  4665. *node.context( { getUV: () => customCoord } );
  4666. *```
  4667. * @augments Node
  4668. */
  4669. class ContextNode extends Node {
  4670. static get type() {
  4671. return 'ContextNode';
  4672. }
  4673. /**
  4674. * Constructs a new context node.
  4675. *
  4676. * @param {Node} node - The node whose context should be modified.
  4677. * @param {Object} [value={}] - The modified context data.
  4678. */
  4679. constructor( node, value = {} ) {
  4680. super();
  4681. /**
  4682. * This flag can be used for type testing.
  4683. *
  4684. * @type {boolean}
  4685. * @readonly
  4686. * @default true
  4687. */
  4688. this.isContextNode = true;
  4689. /**
  4690. * The node whose context should be modified.
  4691. *
  4692. * @type {Node}
  4693. */
  4694. this.node = node;
  4695. /**
  4696. * The modified context data.
  4697. *
  4698. * @type {Object}
  4699. * @default {}
  4700. */
  4701. this.value = value;
  4702. }
  4703. /**
  4704. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  4705. *
  4706. * @return {Node} A reference to {@link ContextNode#node}.
  4707. */
  4708. getScope() {
  4709. return this.node.getScope();
  4710. }
  4711. /**
  4712. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  4713. *
  4714. * @param {NodeBuilder} builder - The current node builder.
  4715. * @return {string} The node type.
  4716. */
  4717. getNodeType( builder ) {
  4718. return this.node.getNodeType( builder );
  4719. }
  4720. analyze( builder ) {
  4721. this.node.build( builder );
  4722. }
  4723. setup( builder ) {
  4724. const previousContext = builder.getContext();
  4725. builder.setContext( { ...builder.context, ...this.value } );
  4726. const node = this.node.build( builder );
  4727. builder.setContext( previousContext );
  4728. return node;
  4729. }
  4730. generate( builder, output ) {
  4731. const previousContext = builder.getContext();
  4732. builder.setContext( { ...builder.context, ...this.value } );
  4733. const snippet = this.node.build( builder, output );
  4734. builder.setContext( previousContext );
  4735. return snippet;
  4736. }
  4737. }
  4738. /**
  4739. * TSL function for creating a context node.
  4740. *
  4741. * @tsl
  4742. * @function
  4743. * @param {Node} node - The node whose context should be modified.
  4744. * @param {Object} [value={}] - The modified context data.
  4745. * @returns {ContextNode}
  4746. */
  4747. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4748. /**
  4749. * TSL function for defining a label context value for a given node.
  4750. *
  4751. * @tsl
  4752. * @function
  4753. * @param {Node} node - The node whose context should be modified.
  4754. * @param {string} name - The name/label to set.
  4755. * @returns {ContextNode}
  4756. */
  4757. const label = ( node, name ) => context( node, { label: name } );
  4758. addMethodChaining( 'context', context );
  4759. addMethodChaining( 'label', label );
  4760. /**
  4761. * Class for representing shader variables as nodes. Variables are created from
  4762. * existing nodes like the following:
  4763. *
  4764. * ```js
  4765. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4766. * ```
  4767. *
  4768. * @augments Node
  4769. */
  4770. class VarNode extends Node {
  4771. static get type() {
  4772. return 'VarNode';
  4773. }
  4774. /**
  4775. * Constructs a new variable node.
  4776. *
  4777. * @param {Node} node - The node for which a variable should be created.
  4778. * @param {?string} name - The name of the variable in the shader.
  4779. * @param {?boolean} readOnly - The read-only flag.
  4780. */
  4781. constructor( node, name = null, readOnly = false ) {
  4782. super();
  4783. /**
  4784. * The node for which a variable should be created.
  4785. *
  4786. * @type {Node}
  4787. */
  4788. this.node = node;
  4789. /**
  4790. * The name of the variable in the shader. If no name is defined,
  4791. * the node system auto-generates one.
  4792. *
  4793. * @type {?string}
  4794. * @default null
  4795. */
  4796. this.name = name;
  4797. /**
  4798. * `VarNode` sets this property to `true` by default.
  4799. *
  4800. * @type {boolean}
  4801. * @default true
  4802. */
  4803. this.global = true;
  4804. /**
  4805. * This flag can be used for type testing.
  4806. *
  4807. * @type {boolean}
  4808. * @readonly
  4809. * @default true
  4810. */
  4811. this.isVarNode = true;
  4812. /**
  4813. *
  4814. * The read-only flag.
  4815. *
  4816. * @type {boolean}
  4817. * @default false
  4818. */
  4819. this.readOnly = readOnly;
  4820. }
  4821. getHash( builder ) {
  4822. return this.name || super.getHash( builder );
  4823. }
  4824. getMemberType( builder, name ) {
  4825. return this.node.getMemberType( builder, name );
  4826. }
  4827. getElementType( builder ) {
  4828. return this.node.getElementType( builder );
  4829. }
  4830. getNodeType( builder ) {
  4831. return this.node.getNodeType( builder );
  4832. }
  4833. generate( builder ) {
  4834. const { node, name, readOnly } = this;
  4835. const { renderer } = builder;
  4836. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4837. let isDeterministic = false;
  4838. let shouldTreatAsReadOnly = false;
  4839. if ( readOnly ) {
  4840. isDeterministic = builder.isDeterministic( node );
  4841. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4842. }
  4843. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4844. const snippet = node.build( builder, vectorType );
  4845. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4846. const propertyName = builder.getPropertyName( nodeVar );
  4847. let declarationPrefix = propertyName;
  4848. if ( shouldTreatAsReadOnly ) {
  4849. if ( isWebGPUBackend ) {
  4850. declarationPrefix = isDeterministic
  4851. ? `const ${ propertyName }`
  4852. : `let ${ propertyName }`;
  4853. } else {
  4854. const count = builder.getArrayCount( node );
  4855. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  4856. }
  4857. }
  4858. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4859. return propertyName;
  4860. }
  4861. }
  4862. /**
  4863. * TSL function for creating a var node.
  4864. *
  4865. * @tsl
  4866. * @function
  4867. * @param {Node} node - The node for which a variable should be created.
  4868. * @param {?string} name - The name of the variable in the shader.
  4869. * @returns {VarNode}
  4870. */
  4871. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4872. /**
  4873. * TSL function for creating a var node.
  4874. *
  4875. * @tsl
  4876. * @function
  4877. * @param {Node} node - The node for which a variable should be created.
  4878. * @param {?string} name - The name of the variable in the shader.
  4879. * @returns {VarNode}
  4880. */
  4881. const Var = ( node, name = null ) => createVar( node, name ).append();
  4882. /**
  4883. * TSL function for creating a const node.
  4884. *
  4885. * @tsl
  4886. * @function
  4887. * @param {Node} node - The node for which a constant should be created.
  4888. * @param {?string} name - The name of the constant in the shader.
  4889. * @returns {VarNode}
  4890. */
  4891. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4892. // Method chaining
  4893. addMethodChaining( 'toVar', Var );
  4894. addMethodChaining( 'toConst', Const );
  4895. // Deprecated
  4896. /**
  4897. * @tsl
  4898. * @function
  4899. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4900. *
  4901. * @param {any} node
  4902. * @returns {VarNode}
  4903. */
  4904. const temp = ( node ) => { // @deprecated, r170
  4905. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4906. return createVar( node );
  4907. };
  4908. addMethodChaining( 'temp', temp );
  4909. /**
  4910. * Class for representing shader varyings as nodes. Varyings are create from
  4911. * existing nodes like the following:
  4912. *
  4913. * ```js
  4914. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4915. * ```
  4916. *
  4917. * @augments Node
  4918. */
  4919. class VaryingNode extends Node {
  4920. static get type() {
  4921. return 'VaryingNode';
  4922. }
  4923. /**
  4924. * Constructs a new varying node.
  4925. *
  4926. * @param {Node} node - The node for which a varying should be created.
  4927. * @param {?string} name - The name of the varying in the shader.
  4928. */
  4929. constructor( node, name = null ) {
  4930. super();
  4931. /**
  4932. * The node for which a varying should be created.
  4933. *
  4934. * @type {Node}
  4935. */
  4936. this.node = node;
  4937. /**
  4938. * The name of the varying in the shader. If no name is defined,
  4939. * the node system auto-generates one.
  4940. *
  4941. * @type {?string}
  4942. * @default null
  4943. */
  4944. this.name = name;
  4945. /**
  4946. * This flag can be used for type testing.
  4947. *
  4948. * @type {boolean}
  4949. * @readonly
  4950. * @default true
  4951. */
  4952. this.isVaryingNode = true;
  4953. }
  4954. /**
  4955. * The method is overwritten so it always returns `true`.
  4956. *
  4957. * @param {NodeBuilder} builder - The current node builder.
  4958. * @return {boolean} Whether this node is global or not.
  4959. */
  4960. isGlobal( /*builder*/ ) {
  4961. return true;
  4962. }
  4963. getHash( builder ) {
  4964. return this.name || super.getHash( builder );
  4965. }
  4966. getNodeType( builder ) {
  4967. // VaryingNode is auto type
  4968. return this.node.getNodeType( builder );
  4969. }
  4970. /**
  4971. * This method performs the setup of a varying node with the current node builder.
  4972. *
  4973. * @param {NodeBuilder} builder - The current node builder.
  4974. * @return {NodeVarying} The node varying from the node builder.
  4975. */
  4976. setupVarying( builder ) {
  4977. const properties = builder.getNodeProperties( this );
  4978. let varying = properties.varying;
  4979. if ( varying === undefined ) {
  4980. const name = this.name;
  4981. const type = this.getNodeType( builder );
  4982. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4983. properties.node = this.node;
  4984. }
  4985. // this property can be used to check if the varying can be optimized for a variable
  4986. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4987. return varying;
  4988. }
  4989. setup( builder ) {
  4990. this.setupVarying( builder );
  4991. }
  4992. analyze( builder ) {
  4993. this.setupVarying( builder );
  4994. return this.node.analyze( builder );
  4995. }
  4996. generate( builder ) {
  4997. const properties = builder.getNodeProperties( this );
  4998. const varying = this.setupVarying( builder );
  4999. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  5000. if ( properties.propertyName === undefined || needsReassign ) {
  5001. const type = this.getNodeType( builder );
  5002. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5003. // force node run in vertex stage
  5004. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5005. properties.propertyName = propertyName;
  5006. if ( needsReassign ) {
  5007. // once reassign varying in fragment stage
  5008. properties.reassignPosition = false;
  5009. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  5010. properties.reassignPosition = true;
  5011. }
  5012. }
  5013. return builder.getPropertyName( varying );
  5014. }
  5015. }
  5016. /**
  5017. * TSL function for creating a varying node.
  5018. *
  5019. * @tsl
  5020. * @function
  5021. * @param {Node} node - The node for which a varying should be created.
  5022. * @param {?string} name - The name of the varying in the shader.
  5023. * @returns {VaryingNode}
  5024. */
  5025. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  5026. /**
  5027. * Computes a node in the vertex stage.
  5028. *
  5029. * @tsl
  5030. * @function
  5031. * @param {Node} node - The node which should be executed in the vertex stage.
  5032. * @returns {VaryingNode}
  5033. */
  5034. const vertexStage = ( node ) => varying( node );
  5035. addMethodChaining( 'toVarying', varying );
  5036. addMethodChaining( 'toVertexStage', vertexStage );
  5037. // Deprecated
  5038. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5039. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  5040. return varying( ...params );
  5041. } );
  5042. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5043. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  5044. return varying( ...params );
  5045. } );
  5046. /**
  5047. * Converts the given color value from sRGB to linear-sRGB color space.
  5048. *
  5049. * @tsl
  5050. * @function
  5051. * @param {Node<vec3>} color - The sRGB color.
  5052. * @return {Node<vec3>} The linear-sRGB color.
  5053. */
  5054. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5055. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5056. const b = color.mul( 0.0773993808 );
  5057. const factor = color.lessThanEqual( 0.04045 );
  5058. const rgbResult = mix( a, b, factor );
  5059. return rgbResult;
  5060. } ).setLayout( {
  5061. name: 'sRGBTransferEOTF',
  5062. type: 'vec3',
  5063. inputs: [
  5064. { name: 'color', type: 'vec3' }
  5065. ]
  5066. } );
  5067. /**
  5068. * Converts the given color value from linear-sRGB to sRGB color space.
  5069. *
  5070. * @tsl
  5071. * @function
  5072. * @param {Node<vec3>} color - The linear-sRGB color.
  5073. * @return {Node<vec3>} The sRGB color.
  5074. */
  5075. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5076. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5077. const b = color.mul( 12.92 );
  5078. const factor = color.lessThanEqual( 0.0031308 );
  5079. const rgbResult = mix( a, b, factor );
  5080. return rgbResult;
  5081. } ).setLayout( {
  5082. name: 'sRGBTransferOETF',
  5083. type: 'vec3',
  5084. inputs: [
  5085. { name: 'color', type: 'vec3' }
  5086. ]
  5087. } );
  5088. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5089. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5090. /**
  5091. * This node represents a color space conversion. Meaning it converts
  5092. * a color value from a source to a target color space.
  5093. *
  5094. * @augments TempNode
  5095. */
  5096. class ColorSpaceNode extends TempNode {
  5097. static get type() {
  5098. return 'ColorSpaceNode';
  5099. }
  5100. /**
  5101. * Constructs a new color space node.
  5102. *
  5103. * @param {Node} colorNode - Represents the color to convert.
  5104. * @param {string} source - The source color space.
  5105. * @param {string} target - The target color space.
  5106. */
  5107. constructor( colorNode, source, target ) {
  5108. super( 'vec4' );
  5109. /**
  5110. * Represents the color to convert.
  5111. *
  5112. * @type {Node}
  5113. */
  5114. this.colorNode = colorNode;
  5115. /**
  5116. * The source color space.
  5117. *
  5118. * @type {string}
  5119. */
  5120. this.source = source;
  5121. /**
  5122. * The target color space.
  5123. *
  5124. * @type {string}
  5125. */
  5126. this.target = target;
  5127. }
  5128. /**
  5129. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5130. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5131. * color management and renderer.
  5132. *
  5133. * @param {NodeBuilder} builder - The current node builder.
  5134. * @param {string} colorSpace - The color space to resolve.
  5135. * @return {string} The resolved color space.
  5136. */
  5137. resolveColorSpace( builder, colorSpace ) {
  5138. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5139. return ColorManagement.workingColorSpace;
  5140. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5141. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5142. }
  5143. return colorSpace;
  5144. }
  5145. setup( builder ) {
  5146. const { colorNode } = this;
  5147. const source = this.resolveColorSpace( builder, this.source );
  5148. const target = this.resolveColorSpace( builder, this.target );
  5149. let outputNode = colorNode;
  5150. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5151. return outputNode;
  5152. }
  5153. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5154. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5155. }
  5156. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5157. outputNode = vec4(
  5158. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5159. outputNode.a
  5160. );
  5161. }
  5162. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5163. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5164. }
  5165. return outputNode;
  5166. }
  5167. }
  5168. /**
  5169. * TSL function for converting a given color node to the current output color space.
  5170. *
  5171. * @tsl
  5172. * @function
  5173. * @param {Node} node - Represents the node to convert.
  5174. * @returns {ColorSpaceNode}
  5175. */
  5176. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  5177. /**
  5178. * TSL function for converting a given color node to the current working color space.
  5179. *
  5180. * @tsl
  5181. * @function
  5182. * @param {Node} node - Represents the node to convert.
  5183. * @returns {ColorSpaceNode}
  5184. */
  5185. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5186. /**
  5187. * TSL function for converting a given color node from the current working color space to the given color space.
  5188. *
  5189. * @tsl
  5190. * @function
  5191. * @param {Node} node - Represents the node to convert.
  5192. * @param {string} colorSpace - The target color space.
  5193. * @returns {ColorSpaceNode}
  5194. */
  5195. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5196. /**
  5197. * TSL function for converting a given color node from the given color space to the current working color space.
  5198. *
  5199. * @tsl
  5200. * @function
  5201. * @param {Node} node - Represents the node to convert.
  5202. * @param {string} colorSpace - The source color space.
  5203. * @returns {ColorSpaceNode}
  5204. */
  5205. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5206. /**
  5207. * TSL function for converting a given color node from one color space to another one.
  5208. *
  5209. * @tsl
  5210. * @function
  5211. * @param {Node} node - Represents the node to convert.
  5212. * @param {string} sourceColorSpace - The source color space.
  5213. * @param {string} targetColorSpace - The target color space.
  5214. * @returns {ColorSpaceNode}
  5215. */
  5216. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5217. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5218. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5219. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5220. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5221. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5222. /**
  5223. * This class is only relevant if the referenced property is array-like.
  5224. * In this case, `ReferenceElementNode` allows to refer to a specific
  5225. * element inside the data structure via an index.
  5226. *
  5227. * @augments ArrayElementNode
  5228. */
  5229. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5230. static get type() {
  5231. return 'ReferenceElementNode';
  5232. }
  5233. /**
  5234. * Constructs a new reference element node.
  5235. *
  5236. * @param {?ReferenceBaseNode} referenceNode - The reference node.
  5237. * @param {Node} indexNode - The index node that defines the element access.
  5238. */
  5239. constructor( referenceNode, indexNode ) {
  5240. super( referenceNode, indexNode );
  5241. /**
  5242. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5243. * property references to the current node.
  5244. *
  5245. * @type {?ReferenceBaseNode}
  5246. * @default null
  5247. */
  5248. this.referenceNode = referenceNode;
  5249. /**
  5250. * This flag can be used for type testing.
  5251. *
  5252. * @type {boolean}
  5253. * @readonly
  5254. * @default true
  5255. */
  5256. this.isReferenceElementNode = true;
  5257. }
  5258. /**
  5259. * This method is overwritten since the node type is inferred from
  5260. * the uniform type of the reference node.
  5261. *
  5262. * @return {string} The node type.
  5263. */
  5264. getNodeType() {
  5265. return this.referenceNode.uniformType;
  5266. }
  5267. generate( builder ) {
  5268. const snippet = super.generate( builder );
  5269. const arrayType = this.referenceNode.getNodeType();
  5270. const elementType = this.getNodeType();
  5271. return builder.format( snippet, arrayType, elementType );
  5272. }
  5273. };
  5274. /**
  5275. * Base class for nodes which establishes a reference to a property of another object.
  5276. * In this way, the value of the node is automatically linked to the value of
  5277. * referenced object. Reference nodes internally represent the linked value
  5278. * as a uniform.
  5279. *
  5280. * @augments Node
  5281. */
  5282. class ReferenceBaseNode extends Node {
  5283. static get type() {
  5284. return 'ReferenceBaseNode';
  5285. }
  5286. /**
  5287. * Constructs a new reference base node.
  5288. *
  5289. * @param {string} property - The name of the property the node refers to.
  5290. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5291. * @param {?Object} [object=null] - The object the property belongs to.
  5292. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5293. */
  5294. constructor( property, uniformType, object = null, count = null ) {
  5295. super();
  5296. /**
  5297. * The name of the property the node refers to.
  5298. *
  5299. * @type {string}
  5300. */
  5301. this.property = property;
  5302. /**
  5303. * The uniform type that should be used to represent the property value.
  5304. *
  5305. * @type {string}
  5306. */
  5307. this.uniformType = uniformType;
  5308. /**
  5309. * The object the property belongs to.
  5310. *
  5311. * @type {?Object}
  5312. * @default null
  5313. */
  5314. this.object = object;
  5315. /**
  5316. * When the linked property is an array, this parameter defines its length.
  5317. *
  5318. * @type {?number}
  5319. * @default null
  5320. */
  5321. this.count = count;
  5322. /**
  5323. * The property name might have dots so nested properties can be referred.
  5324. * The hierarchy of the names is stored inside this array.
  5325. *
  5326. * @type {Array<string>}
  5327. */
  5328. this.properties = property.split( '.' );
  5329. /**
  5330. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5331. * since the final reference might be updated from calling code.
  5332. *
  5333. * @type {?Object}
  5334. * @default null
  5335. */
  5336. this.reference = object;
  5337. /**
  5338. * The uniform node that holds the value of the reference node.
  5339. *
  5340. * @type {UniformNode}
  5341. * @default null
  5342. */
  5343. this.node = null;
  5344. /**
  5345. * The uniform group of the internal uniform.
  5346. *
  5347. * @type {UniformGroupNode}
  5348. * @default null
  5349. */
  5350. this.group = null;
  5351. /**
  5352. * Overwritten since reference nodes are updated per object.
  5353. *
  5354. * @type {string}
  5355. * @default 'object'
  5356. */
  5357. this.updateType = NodeUpdateType.OBJECT;
  5358. }
  5359. /**
  5360. * Sets the uniform group for this reference node.
  5361. *
  5362. * @param {UniformGroupNode} group - The uniform group to set.
  5363. * @return {ReferenceBaseNode} A reference to this node.
  5364. */
  5365. setGroup( group ) {
  5366. this.group = group;
  5367. return this;
  5368. }
  5369. /**
  5370. * When the referred property is array-like, this method can be used
  5371. * to access elements via an index node.
  5372. *
  5373. * @param {IndexNode} indexNode - indexNode.
  5374. * @return {ReferenceElementNode} A reference to an element.
  5375. */
  5376. element( indexNode ) {
  5377. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5378. }
  5379. /**
  5380. * Sets the node type which automatically defines the internal
  5381. * uniform type.
  5382. *
  5383. * @param {string} uniformType - The type to set.
  5384. */
  5385. setNodeType( uniformType ) {
  5386. const node = uniform( null, uniformType ).getSelf();
  5387. if ( this.group !== null ) {
  5388. node.setGroup( this.group );
  5389. }
  5390. this.node = node;
  5391. }
  5392. /**
  5393. * This method is overwritten since the node type is inferred from
  5394. * the type of the reference node.
  5395. *
  5396. * @param {NodeBuilder} builder - The current node builder.
  5397. * @return {string} The node type.
  5398. */
  5399. getNodeType( builder ) {
  5400. if ( this.node === null ) {
  5401. this.updateReference( builder );
  5402. this.updateValue();
  5403. }
  5404. return this.node.getNodeType( builder );
  5405. }
  5406. /**
  5407. * Returns the property value from the given referred object.
  5408. *
  5409. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5410. * @return {any} The value.
  5411. */
  5412. getValueFromReference( object = this.reference ) {
  5413. const { properties } = this;
  5414. let value = object[ properties[ 0 ] ];
  5415. for ( let i = 1; i < properties.length; i ++ ) {
  5416. value = value[ properties[ i ] ];
  5417. }
  5418. return value;
  5419. }
  5420. /**
  5421. * Allows to update the reference based on the given state. The state is only
  5422. * evaluated {@link ReferenceBaseNode#object} is not set.
  5423. *
  5424. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5425. * @return {Object} The updated reference.
  5426. */
  5427. updateReference( state ) {
  5428. this.reference = this.object !== null ? this.object : state.object;
  5429. return this.reference;
  5430. }
  5431. /**
  5432. * The output of the reference node is the internal uniform node.
  5433. *
  5434. * @return {UniformNode} The output node.
  5435. */
  5436. setup() {
  5437. this.updateValue();
  5438. return this.node;
  5439. }
  5440. /**
  5441. * Overwritten to to update the internal uniform value.
  5442. *
  5443. * @param {NodeFrame} frame - A reference to the current node frame.
  5444. */
  5445. update( /*frame*/ ) {
  5446. this.updateValue();
  5447. }
  5448. /**
  5449. * Retrieves the value from the referred object property and uses it
  5450. * to updated the internal uniform.
  5451. */
  5452. updateValue() {
  5453. if ( this.node === null ) this.setNodeType( this.uniformType );
  5454. const value = this.getValueFromReference();
  5455. if ( Array.isArray( value ) ) {
  5456. this.node.array = value;
  5457. } else {
  5458. this.node.value = value;
  5459. }
  5460. }
  5461. }
  5462. /**
  5463. * TSL function for creating a reference base node.
  5464. *
  5465. * @tsl
  5466. * @function
  5467. * @param {string} name - The name of the property the node refers to.
  5468. * @param {string} type - The uniform type that should be used to represent the property value.
  5469. * @param {Object} object - The object the property belongs to.
  5470. * @returns {ReferenceBaseNode}
  5471. */
  5472. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5473. /**
  5474. * This node is a special type of reference node which is intended
  5475. * for linking renderer properties with node values.
  5476. * ```js
  5477. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5478. * ```
  5479. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5480. * automatically be updated.
  5481. *
  5482. * @augments ReferenceBaseNode
  5483. */
  5484. class RendererReferenceNode extends ReferenceBaseNode {
  5485. static get type() {
  5486. return 'RendererReferenceNode';
  5487. }
  5488. /**
  5489. * Constructs a new renderer reference node.
  5490. *
  5491. * @param {string} property - The name of the property the node refers to.
  5492. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5493. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5494. * the node refers to the renderer of the current state.
  5495. */
  5496. constructor( property, inputType, renderer = null ) {
  5497. super( property, inputType, renderer );
  5498. /**
  5499. * The renderer the property belongs to. When no renderer is set,
  5500. * the node refers to the renderer of the current state.
  5501. *
  5502. * @type {?Renderer}
  5503. * @default null
  5504. */
  5505. this.renderer = renderer;
  5506. this.setGroup( renderGroup );
  5507. }
  5508. /**
  5509. * Updates the reference based on the given state. The state is only evaluated
  5510. * {@link RendererReferenceNode#renderer} is not set.
  5511. *
  5512. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5513. * @return {Object} The updated reference.
  5514. */
  5515. updateReference( state ) {
  5516. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5517. return this.reference;
  5518. }
  5519. }
  5520. /**
  5521. * TSL function for creating a renderer reference node.
  5522. *
  5523. * @tsl
  5524. * @function
  5525. * @param {string} name - The name of the property the node refers to.
  5526. * @param {string} type - The uniform type that should be used to represent the property value.
  5527. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5528. * the node refers to the renderer of the current state.
  5529. * @returns {RendererReferenceNode}
  5530. */
  5531. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5532. /**
  5533. * This node represents a tone mapping operation.
  5534. *
  5535. * @augments TempNode
  5536. */
  5537. class ToneMappingNode extends TempNode {
  5538. static get type() {
  5539. return 'ToneMappingNode';
  5540. }
  5541. /**
  5542. * Constructs a new tone mapping node.
  5543. *
  5544. * @param {number} toneMapping - The tone mapping type.
  5545. * @param {Node} exposureNode - The tone mapping exposure.
  5546. * @param {Node} [colorNode=null] - The color node to process.
  5547. */
  5548. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5549. super( 'vec3' );
  5550. /**
  5551. * The tone mapping type.
  5552. *
  5553. * @type {number}
  5554. */
  5555. this.toneMapping = toneMapping;
  5556. /**
  5557. * The tone mapping exposure.
  5558. *
  5559. * @type {Node}
  5560. * @default null
  5561. */
  5562. this.exposureNode = exposureNode;
  5563. /**
  5564. * Represents the color to process.
  5565. *
  5566. * @type {?Node}
  5567. * @default null
  5568. */
  5569. this.colorNode = colorNode;
  5570. }
  5571. /**
  5572. * Overwrites the default `customCacheKey()` implementation by including the tone
  5573. * mapping type into the cache key.
  5574. *
  5575. * @return {number} The hash.
  5576. */
  5577. customCacheKey() {
  5578. return hash$1( this.toneMapping );
  5579. }
  5580. setup( builder ) {
  5581. const colorNode = this.colorNode || builder.context.color;
  5582. const toneMapping = this.toneMapping;
  5583. if ( toneMapping === NoToneMapping ) return colorNode;
  5584. let outputNode = null;
  5585. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5586. if ( toneMappingFn !== null ) {
  5587. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5588. } else {
  5589. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5590. outputNode = colorNode;
  5591. }
  5592. return outputNode;
  5593. }
  5594. }
  5595. /**
  5596. * TSL function for creating a tone mapping node.
  5597. *
  5598. * @tsl
  5599. * @function
  5600. * @param {number} mapping - The tone mapping type.
  5601. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5602. * @param {Node<vec3> | Color} color - The color node to process.
  5603. * @returns {ToneMappingNode<vec3>}
  5604. */
  5605. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5606. /**
  5607. * TSL object that represents the global tone mapping exposure of the renderer.
  5608. *
  5609. * @tsl
  5610. * @type {RendererReferenceNode<vec3>}
  5611. */
  5612. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5613. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5614. /**
  5615. * In earlier `three.js` versions it was only possible to define attribute data
  5616. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5617. * on the node level.
  5618. * ```js
  5619. * const geometry = new THREE.PlaneGeometry();
  5620. * const positionAttribute = geometry.getAttribute( 'position' );
  5621. *
  5622. * const colors = [];
  5623. * for ( let i = 0; i < position.count; i ++ ) {
  5624. * colors.push( 1, 0, 0 );
  5625. * }
  5626. *
  5627. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5628. * ```
  5629. * This new approach is especially interesting when geometry data are generated via
  5630. * compute shaders. The below line converts a storage buffer into an attribute node.
  5631. * ```js
  5632. * material.positionNode = positionBuffer.toAttribute();
  5633. * ```
  5634. * @augments InputNode
  5635. */
  5636. class BufferAttributeNode extends InputNode {
  5637. static get type() {
  5638. return 'BufferAttributeNode';
  5639. }
  5640. /**
  5641. * Constructs a new buffer attribute node.
  5642. *
  5643. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5644. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5645. * @param {number} [bufferStride=0] - The buffer stride.
  5646. * @param {number} [bufferOffset=0] - The buffer offset.
  5647. */
  5648. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5649. super( value, bufferType );
  5650. /**
  5651. * This flag can be used for type testing.
  5652. *
  5653. * @type {boolean}
  5654. * @readonly
  5655. * @default true
  5656. */
  5657. this.isBufferNode = true;
  5658. /**
  5659. * The buffer type (e.g. `'vec3'`).
  5660. *
  5661. * @type {string}
  5662. * @default null
  5663. */
  5664. this.bufferType = bufferType;
  5665. /**
  5666. * The buffer stride.
  5667. *
  5668. * @type {number}
  5669. * @default 0
  5670. */
  5671. this.bufferStride = bufferStride;
  5672. /**
  5673. * The buffer offset.
  5674. *
  5675. * @type {number}
  5676. * @default 0
  5677. */
  5678. this.bufferOffset = bufferOffset;
  5679. /**
  5680. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5681. * if you are planning to update the attribute data per frame.
  5682. *
  5683. * @type {number}
  5684. * @default StaticDrawUsage
  5685. */
  5686. this.usage = StaticDrawUsage;
  5687. /**
  5688. * Whether the attribute is instanced or not.
  5689. *
  5690. * @type {boolean}
  5691. * @default false
  5692. */
  5693. this.instanced = false;
  5694. /**
  5695. * A reference to the buffer attribute.
  5696. *
  5697. * @type {?BufferAttribute}
  5698. * @default null
  5699. */
  5700. this.attribute = null;
  5701. /**
  5702. * `BufferAttributeNode` sets this property to `true` by default.
  5703. *
  5704. * @type {boolean}
  5705. * @default true
  5706. */
  5707. this.global = true;
  5708. if ( value && value.isBufferAttribute === true ) {
  5709. this.attribute = value;
  5710. this.usage = value.usage;
  5711. this.instanced = value.isInstancedBufferAttribute;
  5712. }
  5713. }
  5714. /**
  5715. * This method is overwritten since the attribute data might be shared
  5716. * and thus the hash should be shared as well.
  5717. *
  5718. * @param {NodeBuilder} builder - The current node builder.
  5719. * @return {string} The hash.
  5720. */
  5721. getHash( builder ) {
  5722. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5723. let bufferData = builder.globalCache.getData( this.value );
  5724. if ( bufferData === undefined ) {
  5725. bufferData = {
  5726. node: this
  5727. };
  5728. builder.globalCache.setData( this.value, bufferData );
  5729. }
  5730. return bufferData.node.uuid;
  5731. }
  5732. return this.uuid;
  5733. }
  5734. /**
  5735. * This method is overwritten since the node type is inferred from
  5736. * the buffer attribute.
  5737. *
  5738. * @param {NodeBuilder} builder - The current node builder.
  5739. * @return {string} The node type.
  5740. */
  5741. getNodeType( builder ) {
  5742. if ( this.bufferType === null ) {
  5743. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5744. }
  5745. return this.bufferType;
  5746. }
  5747. /**
  5748. * Depending on which value was passed to the node, `setup()` behaves
  5749. * differently. If no instance of `BufferAttribute` was passed, the method
  5750. * creates an internal attribute and configures it respectively.
  5751. *
  5752. * @param {NodeBuilder} builder - The current node builder.
  5753. */
  5754. setup( builder ) {
  5755. if ( this.attribute !== null ) return;
  5756. const type = this.getNodeType( builder );
  5757. const array = this.value;
  5758. const itemSize = builder.getTypeLength( type );
  5759. const stride = this.bufferStride || itemSize;
  5760. const offset = this.bufferOffset;
  5761. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5762. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5763. buffer.setUsage( this.usage );
  5764. this.attribute = bufferAttribute;
  5765. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5766. }
  5767. /**
  5768. * Generates the code snippet of the buffer attribute node.
  5769. *
  5770. * @param {NodeBuilder} builder - The current node builder.
  5771. * @return {string} The generated code snippet.
  5772. */
  5773. generate( builder ) {
  5774. const nodeType = this.getNodeType( builder );
  5775. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5776. const propertyName = builder.getPropertyName( nodeAttribute );
  5777. let output = null;
  5778. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5779. this.name = propertyName;
  5780. output = propertyName;
  5781. } else {
  5782. const nodeVarying = varying( this );
  5783. output = nodeVarying.build( builder, nodeType );
  5784. }
  5785. return output;
  5786. }
  5787. /**
  5788. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5789. *
  5790. * @param {NodeBuilder} builder - The current node builder.
  5791. * @return {string} The input type.
  5792. */
  5793. getInputType( /*builder*/ ) {
  5794. return 'bufferAttribute';
  5795. }
  5796. /**
  5797. * Sets the `usage` property to the given value.
  5798. *
  5799. * @param {number} value - The usage to set.
  5800. * @return {BufferAttributeNode} A reference to this node.
  5801. */
  5802. setUsage( value ) {
  5803. this.usage = value;
  5804. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5805. this.attribute.usage = value;
  5806. }
  5807. return this;
  5808. }
  5809. /**
  5810. * Sets the `instanced` property to the given value.
  5811. *
  5812. * @param {boolean} value - The value to set.
  5813. * @return {BufferAttributeNode} A reference to this node.
  5814. */
  5815. setInstanced( value ) {
  5816. this.instanced = value;
  5817. return this;
  5818. }
  5819. }
  5820. /**
  5821. * TSL function for creating a buffer attribute node.
  5822. *
  5823. * @tsl
  5824. * @function
  5825. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5826. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5827. * @param {number} [stride=0] - The buffer stride.
  5828. * @param {number} [offset=0] - The buffer offset.
  5829. * @returns {BufferAttributeNode}
  5830. */
  5831. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5832. /**
  5833. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5834. * Use this function if attribute data are updated per frame.
  5835. *
  5836. * @tsl
  5837. * @function
  5838. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5839. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5840. * @param {number} [stride=0] - The buffer stride.
  5841. * @param {number} [offset=0] - The buffer offset.
  5842. * @returns {BufferAttributeNode}
  5843. */
  5844. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5845. /**
  5846. * TSL function for creating a buffer attribute node but with enabled instancing
  5847. *
  5848. * @tsl
  5849. * @function
  5850. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5851. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5852. * @param {number} [stride=0] - The buffer stride.
  5853. * @param {number} [offset=0] - The buffer offset.
  5854. * @returns {BufferAttributeNode}
  5855. */
  5856. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5857. /**
  5858. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5859. *
  5860. * @tsl
  5861. * @function
  5862. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5863. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5864. * @param {number} [stride=0] - The buffer stride.
  5865. * @param {number} [offset=0] - The buffer offset.
  5866. * @returns {BufferAttributeNode}
  5867. */
  5868. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5869. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5870. /**
  5871. * TODO
  5872. *
  5873. * @augments Node
  5874. */
  5875. class ComputeNode extends Node {
  5876. static get type() {
  5877. return 'ComputeNode';
  5878. }
  5879. /**
  5880. * Constructs a new compute node.
  5881. *
  5882. * @param {Node} computeNode - TODO
  5883. * @param {number} count - TODO.
  5884. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  5885. */
  5886. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5887. super( 'void' );
  5888. /**
  5889. * This flag can be used for type testing.
  5890. *
  5891. * @type {boolean}
  5892. * @readonly
  5893. * @default true
  5894. */
  5895. this.isComputeNode = true;
  5896. /**
  5897. * TODO
  5898. *
  5899. * @type {Node}
  5900. */
  5901. this.computeNode = computeNode;
  5902. /**
  5903. * TODO
  5904. *
  5905. * @type {number}
  5906. */
  5907. this.count = count;
  5908. /**
  5909. * TODO
  5910. *
  5911. * @type {Array<number>}
  5912. * @default [64]
  5913. */
  5914. this.workgroupSize = workgroupSize;
  5915. /**
  5916. * TODO
  5917. *
  5918. * @type {number}
  5919. */
  5920. this.dispatchCount = 0;
  5921. /**
  5922. * TODO
  5923. *
  5924. * @type {number}
  5925. */
  5926. this.version = 1;
  5927. /**
  5928. * The name or label of the uniform.
  5929. *
  5930. * @type {string}
  5931. * @default ''
  5932. */
  5933. this.name = '';
  5934. /**
  5935. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5936. * is executed once per object by default.
  5937. *
  5938. * @type {string}
  5939. * @default 'object'
  5940. */
  5941. this.updateBeforeType = NodeUpdateType.OBJECT;
  5942. /**
  5943. * TODO
  5944. *
  5945. * @type {Function}
  5946. */
  5947. this.onInitFunction = null;
  5948. this.updateDispatchCount();
  5949. }
  5950. /**
  5951. * Executes the `dispose` event for this node.
  5952. */
  5953. dispose() {
  5954. this.dispatchEvent( { type: 'dispose' } );
  5955. }
  5956. /**
  5957. * Sets the {@link ComputeNode#name} property.
  5958. *
  5959. * @param {string} name - The name of the uniform.
  5960. * @return {ComputeNode} A reference to this node.
  5961. */
  5962. label( name ) {
  5963. this.name = name;
  5964. return this;
  5965. }
  5966. /**
  5967. * TODO
  5968. */
  5969. updateDispatchCount() {
  5970. const { count, workgroupSize } = this;
  5971. let size = workgroupSize[ 0 ];
  5972. for ( let i = 1; i < workgroupSize.length; i ++ )
  5973. size *= workgroupSize[ i ];
  5974. this.dispatchCount = Math.ceil( count / size );
  5975. }
  5976. /**
  5977. * TODO
  5978. *
  5979. * @param {Function} callback - TODO.
  5980. * @return {ComputeNode} A reference to this node.
  5981. */
  5982. onInit( callback ) {
  5983. this.onInitFunction = callback;
  5984. return this;
  5985. }
  5986. /**
  5987. * The method execute the compute for this node.
  5988. *
  5989. * @param {NodeFrame} frame - A reference to the current node frame.
  5990. */
  5991. updateBefore( { renderer } ) {
  5992. renderer.compute( this );
  5993. }
  5994. generate( builder ) {
  5995. const { shaderStage } = builder;
  5996. if ( shaderStage === 'compute' ) {
  5997. const snippet = this.computeNode.build( builder, 'void' );
  5998. if ( snippet !== '' ) {
  5999. builder.addLineFlowCode( snippet, this );
  6000. }
  6001. }
  6002. }
  6003. }
  6004. /**
  6005. * TSL function for creating a compute node.
  6006. *
  6007. * @tsl
  6008. * @function
  6009. * @param {Node} node - TODO
  6010. * @param {number} count - TODO.
  6011. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6012. * @returns {AtomicFunctionNode}
  6013. */
  6014. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6015. addMethodChaining( 'compute', compute );
  6016. /**
  6017. * This node can be used as a cache management component for another node.
  6018. * Caching is in general used by default in {@link NodeBuilder} but this node
  6019. * allows the usage of a shared parent cache during the build process.
  6020. *
  6021. * @augments Node
  6022. */
  6023. class CacheNode extends Node {
  6024. static get type() {
  6025. return 'CacheNode';
  6026. }
  6027. /**
  6028. * Constructs a new cache node.
  6029. *
  6030. * @param {Node} node - The node that should be cached.
  6031. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6032. */
  6033. constructor( node, parent = true ) {
  6034. super();
  6035. /**
  6036. * The node that should be cached.
  6037. *
  6038. * @type {Node}
  6039. */
  6040. this.node = node;
  6041. /**
  6042. * Whether this node refers to a shared parent cache or not.
  6043. *
  6044. * @type {boolean}
  6045. * @default true
  6046. */
  6047. this.parent = parent;
  6048. /**
  6049. * This flag can be used for type testing.
  6050. *
  6051. * @type {boolean}
  6052. * @readonly
  6053. * @default true
  6054. */
  6055. this.isCacheNode = true;
  6056. }
  6057. getNodeType( builder ) {
  6058. const previousCache = builder.getCache();
  6059. const cache = builder.getCacheFromNode( this, this.parent );
  6060. builder.setCache( cache );
  6061. const nodeType = this.node.getNodeType( builder );
  6062. builder.setCache( previousCache );
  6063. return nodeType;
  6064. }
  6065. build( builder, ...params ) {
  6066. const previousCache = builder.getCache();
  6067. const cache = builder.getCacheFromNode( this, this.parent );
  6068. builder.setCache( cache );
  6069. const data = this.node.build( builder, ...params );
  6070. builder.setCache( previousCache );
  6071. return data;
  6072. }
  6073. }
  6074. /**
  6075. * TSL function for creating a cache node.
  6076. *
  6077. * @tsl
  6078. * @function
  6079. * @param {Node} node - The node that should be cached.
  6080. * @param {boolean} parent - Whether this node refers to a shared parent cache or not.
  6081. * @returns {CacheNode}
  6082. */
  6083. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6084. addMethodChaining( 'cache', cache );
  6085. /**
  6086. * The class generates the code of a given node but returns another node in the output.
  6087. * This can be used to call a method or node that does not return a value, i.e.
  6088. * type `void` on an input where returning a value is required. Example:
  6089. *
  6090. * ```js
  6091. * material.colorNode = myColor.bypass( runVoidFn() )
  6092. *```
  6093. *
  6094. * @augments Node
  6095. */
  6096. class BypassNode extends Node {
  6097. static get type() {
  6098. return 'BypassNode';
  6099. }
  6100. /**
  6101. * Constructs a new bypass node.
  6102. *
  6103. * @param {Node} outputNode - The output node.
  6104. * @param {Node} callNode - The call node.
  6105. */
  6106. constructor( outputNode, callNode ) {
  6107. super();
  6108. /**
  6109. * This flag can be used for type testing.
  6110. *
  6111. * @type {boolean}
  6112. * @readonly
  6113. * @default true
  6114. */
  6115. this.isBypassNode = true;
  6116. /**
  6117. * The output node.
  6118. *
  6119. * @type {Node}
  6120. */
  6121. this.outputNode = outputNode;
  6122. /**
  6123. * The call node.
  6124. *
  6125. * @type {Node}
  6126. */
  6127. this.callNode = callNode;
  6128. }
  6129. getNodeType( builder ) {
  6130. return this.outputNode.getNodeType( builder );
  6131. }
  6132. generate( builder ) {
  6133. const snippet = this.callNode.build( builder, 'void' );
  6134. if ( snippet !== '' ) {
  6135. builder.addLineFlowCode( snippet, this );
  6136. }
  6137. return this.outputNode.build( builder );
  6138. }
  6139. }
  6140. /**
  6141. * TSL function for creating a bypass node.
  6142. *
  6143. * @tsl
  6144. * @function
  6145. * @param {Node} outputNode - The output node.
  6146. * @param {Node} callNode - The call node.
  6147. * @returns {BypassNode}
  6148. */
  6149. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  6150. addMethodChaining( 'bypass', bypass );
  6151. /**
  6152. * This node allows to remap a node value from one range into another. E.g a value of
  6153. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6154. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6155. *
  6156. * @augments Node
  6157. */
  6158. class RemapNode extends Node {
  6159. static get type() {
  6160. return 'RemapNode';
  6161. }
  6162. /**
  6163. * Constructs a new remap node.
  6164. *
  6165. * @param {Node} node - The node that should be remapped.
  6166. * @param {Node} inLowNode - The source or current lower bound of the range.
  6167. * @param {Node} inHighNode - The source or current upper bound of the range.
  6168. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6169. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6170. */
  6171. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6172. super();
  6173. /**
  6174. * The node that should be remapped.
  6175. *
  6176. * @type {Node}
  6177. */
  6178. this.node = node;
  6179. /**
  6180. * The source or current lower bound of the range.
  6181. *
  6182. * @type {Node}
  6183. */
  6184. this.inLowNode = inLowNode;
  6185. /**
  6186. * The source or current upper bound of the range.
  6187. *
  6188. * @type {Node}
  6189. */
  6190. this.inHighNode = inHighNode;
  6191. /**
  6192. * The target lower bound of the range.
  6193. *
  6194. * @type {Node}
  6195. * @default float(0)
  6196. */
  6197. this.outLowNode = outLowNode;
  6198. /**
  6199. * The target upper bound of the range.
  6200. *
  6201. * @type {Node}
  6202. * @default float(1)
  6203. */
  6204. this.outHighNode = outHighNode;
  6205. /**
  6206. * Whether the node value should be clamped before
  6207. * remapping it to the target range.
  6208. *
  6209. * @type {boolean}
  6210. * @default true
  6211. */
  6212. this.doClamp = true;
  6213. }
  6214. setup() {
  6215. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6216. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6217. if ( doClamp === true ) t = t.clamp();
  6218. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6219. }
  6220. }
  6221. /**
  6222. * TSL function for creating a remap node.
  6223. *
  6224. * @tsl
  6225. * @function
  6226. * @param {Node} node - The node that should be remapped.
  6227. * @param {Node} inLowNode - The source or current lower bound of the range.
  6228. * @param {Node} inHighNode - The source or current upper bound of the range.
  6229. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6230. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6231. * @returns {RemapNode}
  6232. */
  6233. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  6234. /**
  6235. * TSL function for creating a remap node, but with enabled clamping.
  6236. *
  6237. * @tsl
  6238. * @function
  6239. * @param {Node} node - The node that should be remapped.
  6240. * @param {Node} inLowNode - The source or current lower bound of the range.
  6241. * @param {Node} inHighNode - The source or current upper bound of the range.
  6242. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6243. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6244. * @returns {RemapNode}
  6245. */
  6246. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  6247. addMethodChaining( 'remap', remap );
  6248. addMethodChaining( 'remapClamp', remapClamp );
  6249. /**
  6250. * This class can be used to implement basic expressions in shader code.
  6251. * Basic examples for that are `return`, `continue` or `discard` statements.
  6252. *
  6253. * @augments Node
  6254. */
  6255. class ExpressionNode extends Node {
  6256. static get type() {
  6257. return 'ExpressionNode';
  6258. }
  6259. /**
  6260. * Constructs a new expression node.
  6261. *
  6262. * @param {string} [snippet=''] - The native code snippet.
  6263. * @param {string} [nodeType='void'] - The node type.
  6264. */
  6265. constructor( snippet = '', nodeType = 'void' ) {
  6266. super( nodeType );
  6267. /**
  6268. * The native code snippet.
  6269. *
  6270. * @type {string}
  6271. * @default ''
  6272. */
  6273. this.snippet = snippet;
  6274. }
  6275. generate( builder, output ) {
  6276. const type = this.getNodeType( builder );
  6277. const snippet = this.snippet;
  6278. if ( type === 'void' ) {
  6279. builder.addLineFlowCode( snippet, this );
  6280. } else {
  6281. return builder.format( `( ${ snippet } )`, type, output );
  6282. }
  6283. }
  6284. }
  6285. /**
  6286. * TSL function for creating an expression node.
  6287. *
  6288. * @tsl
  6289. * @function
  6290. * @param {string} [snippet=''] - The native code snippet.
  6291. * @param {string} [nodeType='void'] - The node type.
  6292. * @returns {ExpressionNode}
  6293. */
  6294. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  6295. /**
  6296. * Represents a `discard` shader operation in TSL.
  6297. *
  6298. * @tsl
  6299. * @function
  6300. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6301. * @return {Node} The `discard` expression.
  6302. */
  6303. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  6304. /**
  6305. * Represents a `return` shader operation in TSL.
  6306. *
  6307. * @tsl
  6308. * @function
  6309. * @return {ExpressionNode} The `return` expression.
  6310. */
  6311. const Return = () => expression( 'return' ).append();
  6312. addMethodChaining( 'discard', Discard );
  6313. /**
  6314. * Normally, tone mapping and color conversion happens automatically
  6315. * before outputting pixel too the default (screen) framebuffer. In certain
  6316. * post processing setups this happens to late because certain effects
  6317. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6318. * to apply tone mapping and color space conversion at an arbitrary point
  6319. * in the effect chain.
  6320. *
  6321. * When applying tone mapping and color space conversion manually with this node,
  6322. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6323. *
  6324. * ```js
  6325. * const postProcessing = new PostProcessing( renderer );
  6326. * postProcessing.outputColorTransform = false;
  6327. *
  6328. * const scenePass = pass( scene, camera );
  6329. * const outputPass = renderOutput( scenePass );
  6330. *
  6331. * postProcessing.outputNode = outputPass;
  6332. * ```
  6333. *
  6334. * @augments TempNode
  6335. */
  6336. class RenderOutputNode extends TempNode {
  6337. static get type() {
  6338. return 'RenderOutputNode';
  6339. }
  6340. /**
  6341. * Constructs a new render output node.
  6342. *
  6343. * @param {Node} colorNode - The color node to process.
  6344. * @param {number} toneMapping - The tone mapping type.
  6345. * @param {string} outputColorSpace - The output color space.
  6346. */
  6347. constructor( colorNode, toneMapping, outputColorSpace ) {
  6348. super( 'vec4' );
  6349. /**
  6350. * The color node to process.
  6351. *
  6352. * @type {Node}
  6353. */
  6354. this.colorNode = colorNode;
  6355. /**
  6356. * The tone mapping type.
  6357. *
  6358. * @type {?number}
  6359. */
  6360. this.toneMapping = toneMapping;
  6361. /**
  6362. * The output color space.
  6363. *
  6364. * @type {?string}
  6365. */
  6366. this.outputColorSpace = outputColorSpace;
  6367. /**
  6368. * This flag can be used for type testing.
  6369. *
  6370. * @type {boolean}
  6371. * @readonly
  6372. * @default true
  6373. */
  6374. this.isRenderOutputNode = true;
  6375. }
  6376. setup( { context } ) {
  6377. let outputNode = this.colorNode || context.color;
  6378. // tone mapping
  6379. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6380. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6381. if ( toneMapping !== NoToneMapping ) {
  6382. outputNode = outputNode.toneMapping( toneMapping );
  6383. }
  6384. // working to output color space
  6385. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6386. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6387. }
  6388. return outputNode;
  6389. }
  6390. }
  6391. /**
  6392. * TSL function for creating a posterize node.
  6393. *
  6394. * @tsl
  6395. * @function
  6396. * @param {Node} color - The color node to process.
  6397. * @param {?number} [toneMapping=null] - The tone mapping type.
  6398. * @param {?string} [outputColorSpace=null] - The output color space.
  6399. * @returns {RenderOutputNode}
  6400. */
  6401. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6402. addMethodChaining( 'renderOutput', renderOutput );
  6403. // Non-PURE exports list, side-effects are required here.
  6404. // TSL Base Syntax
  6405. function addNodeElement( name/*, nodeElement*/ ) {
  6406. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6407. }
  6408. /**
  6409. * Base class for representing shader attributes as nodes.
  6410. *
  6411. * @augments Node
  6412. */
  6413. class AttributeNode extends Node {
  6414. static get type() {
  6415. return 'AttributeNode';
  6416. }
  6417. /**
  6418. * Constructs a new attribute node.
  6419. *
  6420. * @param {string} attributeName - The name of the attribute.
  6421. * @param {?string} nodeType - The node type.
  6422. */
  6423. constructor( attributeName, nodeType = null ) {
  6424. super( nodeType );
  6425. /**
  6426. * `AttributeNode` sets this property to `true` by default.
  6427. *
  6428. * @type {boolean}
  6429. * @default true
  6430. */
  6431. this.global = true;
  6432. this._attributeName = attributeName;
  6433. }
  6434. getHash( builder ) {
  6435. return this.getAttributeName( builder );
  6436. }
  6437. getNodeType( builder ) {
  6438. let nodeType = this.nodeType;
  6439. if ( nodeType === null ) {
  6440. const attributeName = this.getAttributeName( builder );
  6441. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6442. const attribute = builder.geometry.getAttribute( attributeName );
  6443. nodeType = builder.getTypeFromAttribute( attribute );
  6444. } else {
  6445. nodeType = 'float';
  6446. }
  6447. }
  6448. return nodeType;
  6449. }
  6450. /**
  6451. * Sets the attribute name to the given value. The method can be
  6452. * overwritten in derived classes if the final name must be computed
  6453. * analytically.
  6454. *
  6455. * @param {string} attributeName - The name of the attribute.
  6456. * @return {AttributeNode} A reference to this node.
  6457. */
  6458. setAttributeName( attributeName ) {
  6459. this._attributeName = attributeName;
  6460. return this;
  6461. }
  6462. /**
  6463. * Returns the attribute name of this node. The method can be
  6464. * overwritten in derived classes if the final name must be computed
  6465. * analytically.
  6466. *
  6467. * @param {NodeBuilder} builder - The current node builder.
  6468. * @return {string} The attribute name.
  6469. */
  6470. getAttributeName( /*builder*/ ) {
  6471. return this._attributeName;
  6472. }
  6473. generate( builder ) {
  6474. const attributeName = this.getAttributeName( builder );
  6475. const nodeType = this.getNodeType( builder );
  6476. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6477. if ( geometryAttribute === true ) {
  6478. const attribute = builder.geometry.getAttribute( attributeName );
  6479. const attributeType = builder.getTypeFromAttribute( attribute );
  6480. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6481. if ( builder.shaderStage === 'vertex' ) {
  6482. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6483. } else {
  6484. const nodeVarying = varying( this );
  6485. return nodeVarying.build( builder, nodeType );
  6486. }
  6487. } else {
  6488. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6489. return builder.generateConst( nodeType );
  6490. }
  6491. }
  6492. serialize( data ) {
  6493. super.serialize( data );
  6494. data.global = this.global;
  6495. data._attributeName = this._attributeName;
  6496. }
  6497. deserialize( data ) {
  6498. super.deserialize( data );
  6499. this.global = data.global;
  6500. this._attributeName = data._attributeName;
  6501. }
  6502. }
  6503. /**
  6504. * TSL function for creating an attribute node.
  6505. *
  6506. * @tsl
  6507. * @function
  6508. * @param {string} name - The name of the attribute.
  6509. * @param {?string} nodeType - The node type.
  6510. * @returns {AttributeNode}
  6511. */
  6512. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6513. /**
  6514. * TSL function for creating an uv attribute node with the given index.
  6515. *
  6516. * @tsl
  6517. * @function
  6518. * @param {number} [index=0] - The uv index.
  6519. * @return {AttributeNode<vec2>} The uv attribute node.
  6520. */
  6521. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6522. /**
  6523. * A node that represents the dimensions of a texture. The texture size is
  6524. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6525. * or `textureSize()`.
  6526. *
  6527. * @augments Node
  6528. */
  6529. class TextureSizeNode extends Node {
  6530. static get type() {
  6531. return 'TextureSizeNode';
  6532. }
  6533. /**
  6534. * Constructs a new texture size node.
  6535. *
  6536. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6537. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6538. */
  6539. constructor( textureNode, levelNode = null ) {
  6540. super( 'uvec2' );
  6541. /**
  6542. * This flag can be used for type testing.
  6543. *
  6544. * @type {boolean}
  6545. * @readonly
  6546. * @default true
  6547. */
  6548. this.isTextureSizeNode = true;
  6549. /**
  6550. * A texture node which size should be retrieved.
  6551. *
  6552. * @type {TextureNode}
  6553. */
  6554. this.textureNode = textureNode;
  6555. /**
  6556. * A level node which defines the requested mip.
  6557. *
  6558. * @type {Node<int>}
  6559. * @default null
  6560. */
  6561. this.levelNode = levelNode;
  6562. }
  6563. generate( builder, output ) {
  6564. const textureProperty = this.textureNode.build( builder, 'property' );
  6565. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6566. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6567. }
  6568. }
  6569. /**
  6570. * TSL function for creating a texture size node.
  6571. *
  6572. * @tsl
  6573. * @function
  6574. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6575. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6576. * @returns {TextureSizeNode}
  6577. */
  6578. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6579. /**
  6580. * A special type of uniform node that computes the
  6581. * maximum mipmap level for a given texture node.
  6582. *
  6583. * ```js
  6584. * const level = maxMipLevel( textureNode );
  6585. * ```
  6586. *
  6587. * @augments UniformNode
  6588. */
  6589. class MaxMipLevelNode extends UniformNode {
  6590. static get type() {
  6591. return 'MaxMipLevelNode';
  6592. }
  6593. /**
  6594. * Constructs a new max mip level node.
  6595. *
  6596. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6597. */
  6598. constructor( textureNode ) {
  6599. super( 0 );
  6600. /**
  6601. * The texture node to compute the max mip level for.
  6602. *
  6603. * @private
  6604. * @type {TextureNode}
  6605. */
  6606. this._textureNode = textureNode;
  6607. /**
  6608. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6609. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6610. *
  6611. * @type {string}
  6612. * @default 'frame'
  6613. */
  6614. this.updateType = NodeUpdateType.FRAME;
  6615. }
  6616. /**
  6617. * The texture node to compute the max mip level for.
  6618. *
  6619. * @readonly
  6620. * @type {TextureNode}
  6621. */
  6622. get textureNode() {
  6623. return this._textureNode;
  6624. }
  6625. /**
  6626. * The texture.
  6627. *
  6628. * @readonly
  6629. * @type {Texture}
  6630. */
  6631. get texture() {
  6632. return this._textureNode.value;
  6633. }
  6634. update() {
  6635. const texture = this.texture;
  6636. const images = texture.images;
  6637. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6638. if ( image && image.width !== undefined ) {
  6639. const { width, height } = image;
  6640. this.value = Math.log2( Math.max( width, height ) );
  6641. }
  6642. }
  6643. }
  6644. /**
  6645. * TSL function for creating a max mip level node.
  6646. *
  6647. * @tsl
  6648. * @function
  6649. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6650. * @returns {MaxMipLevelNode}
  6651. */
  6652. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6653. /**
  6654. * This type of uniform node represents a 2D texture.
  6655. *
  6656. * @augments UniformNode
  6657. */
  6658. class TextureNode extends UniformNode {
  6659. static get type() {
  6660. return 'TextureNode';
  6661. }
  6662. /**
  6663. * Constructs a new texture node.
  6664. *
  6665. * @param {Texture} value - The texture.
  6666. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  6667. * @param {?Node<int>} [levelNode=null] - The level node.
  6668. * @param {?Node<float>} [biasNode=null] - The bias node.
  6669. */
  6670. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6671. super( value );
  6672. /**
  6673. * This flag can be used for type testing.
  6674. *
  6675. * @type {boolean}
  6676. * @readonly
  6677. * @default true
  6678. */
  6679. this.isTextureNode = true;
  6680. /**
  6681. * Represents the texture coordinates.
  6682. *
  6683. * @type {?Node<vec2|vec3>}
  6684. * @default null
  6685. */
  6686. this.uvNode = uvNode;
  6687. /**
  6688. * Represents the mip level that should be selected.
  6689. *
  6690. * @type {?Node<int>}
  6691. * @default null
  6692. */
  6693. this.levelNode = levelNode;
  6694. /**
  6695. * Represents the bias to be applied during level-of-detail computation.
  6696. *
  6697. * @type {?Node<float>}
  6698. * @default null
  6699. */
  6700. this.biasNode = biasNode;
  6701. /**
  6702. * Represents a reference value a texture sample is compared to.
  6703. *
  6704. * @type {?Node<float>}
  6705. * @default null
  6706. */
  6707. this.compareNode = null;
  6708. /**
  6709. * When using texture arrays, the depth node defines the layer to select.
  6710. *
  6711. * @type {?Node<int>}
  6712. * @default null
  6713. */
  6714. this.depthNode = null;
  6715. /**
  6716. * When defined, a texture is sampled using explicit gradients.
  6717. *
  6718. * @type {?Array<Node<vec2>>}
  6719. * @default null
  6720. */
  6721. this.gradNode = null;
  6722. /**
  6723. * Whether texture values should be sampled or fetched.
  6724. *
  6725. * @type {boolean}
  6726. * @default true
  6727. */
  6728. this.sampler = true;
  6729. /**
  6730. * Whether the uv transformation matrix should be
  6731. * automatically updated or not. Use `setUpdateMatrix()`
  6732. * if you want to change the value of the property.
  6733. *
  6734. * @type {boolean}
  6735. * @default false
  6736. */
  6737. this.updateMatrix = false;
  6738. /**
  6739. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6740. * sets the value to `frame` when the uv transformation matrix should
  6741. * automatically be updated.
  6742. *
  6743. * @type {string}
  6744. * @default 'none'
  6745. */
  6746. this.updateType = NodeUpdateType.NONE;
  6747. /**
  6748. * The reference node.
  6749. *
  6750. * @type {?Node}
  6751. * @default null
  6752. */
  6753. this.referenceNode = null;
  6754. /**
  6755. * The texture value is stored in a private property.
  6756. *
  6757. * @private
  6758. * @type {Texture}
  6759. */
  6760. this._value = value;
  6761. /**
  6762. * The uniform node that represents the uv transformation matrix.
  6763. *
  6764. * @private
  6765. * @type {?UniformNode<mat3>}
  6766. */
  6767. this._matrixUniform = null;
  6768. this.setUpdateMatrix( uvNode === null );
  6769. }
  6770. set value( value ) {
  6771. if ( this.referenceNode ) {
  6772. this.referenceNode.value = value;
  6773. } else {
  6774. this._value = value;
  6775. }
  6776. }
  6777. /**
  6778. * The texture value.
  6779. *
  6780. * @type {Texture}
  6781. */
  6782. get value() {
  6783. return this.referenceNode ? this.referenceNode.value : this._value;
  6784. }
  6785. /**
  6786. * Overwritten since the uniform hash is defined by the texture's UUID.
  6787. *
  6788. * @param {NodeBuilder} builder - The current node builder.
  6789. * @return {string} The uniform hash.
  6790. */
  6791. getUniformHash( /*builder*/ ) {
  6792. return this.value.uuid;
  6793. }
  6794. /**
  6795. * Overwritten since the node type is inferred from the texture type.
  6796. *
  6797. * @param {NodeBuilder} builder - The current node builder.
  6798. * @return {string} The node type.
  6799. */
  6800. getNodeType( /*builder*/ ) {
  6801. if ( this.value.isDepthTexture === true ) return 'float';
  6802. if ( this.value.type === UnsignedIntType ) {
  6803. return 'uvec4';
  6804. } else if ( this.value.type === IntType ) {
  6805. return 'ivec4';
  6806. }
  6807. return 'vec4';
  6808. }
  6809. /**
  6810. * Overwrites the default implementation to return a fixed value `'texture'`.
  6811. *
  6812. * @param {NodeBuilder} builder - The current node builder.
  6813. * @return {string} The input type.
  6814. */
  6815. getInputType( /*builder*/ ) {
  6816. return 'texture';
  6817. }
  6818. /**
  6819. * Returns a default uvs based on the current texture's channel.
  6820. *
  6821. * @return {AttributeNode<vec2>} The default uvs.
  6822. */
  6823. getDefaultUV() {
  6824. return uv( this.value.channel );
  6825. }
  6826. /**
  6827. * Overwritten to always return the texture reference of the node.
  6828. *
  6829. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6830. * @return {Texture} The texture reference.
  6831. */
  6832. updateReference( /*state*/ ) {
  6833. return this.value;
  6834. }
  6835. /**
  6836. * Transforms the given uv node with the texture transformation matrix.
  6837. *
  6838. * @param {Node} uvNode - The uv node to transform.
  6839. * @return {Node} The transformed uv node.
  6840. */
  6841. getTransformedUV( uvNode ) {
  6842. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6843. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6844. }
  6845. /**
  6846. * Defines whether the uv transformation matrix should automatically be updated or not.
  6847. *
  6848. * @param {boolean} value - The update toggle.
  6849. * @return {TextureNode} A reference to this node.
  6850. */
  6851. setUpdateMatrix( value ) {
  6852. this.updateMatrix = value;
  6853. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6854. return this;
  6855. }
  6856. /**
  6857. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6858. * to modify the uv node for correct sampling.
  6859. *
  6860. * @param {NodeBuilder} builder - The current node builder.
  6861. * @param {Node} uvNode - The uv node to setup.
  6862. * @return {Node} The updated uv node.
  6863. */
  6864. setupUV( builder, uvNode ) {
  6865. const texture = this.value;
  6866. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6867. if ( this.sampler ) {
  6868. uvNode = uvNode.flipY();
  6869. } else {
  6870. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6871. }
  6872. }
  6873. return uvNode;
  6874. }
  6875. /**
  6876. * Setups texture node by preparing the internal nodes for code generation.
  6877. *
  6878. * @param {NodeBuilder} builder - The current node builder.
  6879. */
  6880. setup( builder ) {
  6881. const properties = builder.getNodeProperties( this );
  6882. properties.referenceNode = this.referenceNode;
  6883. //
  6884. const texture = this.value;
  6885. if ( ! texture || texture.isTexture !== true ) {
  6886. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6887. }
  6888. //
  6889. let uvNode = this.uvNode;
  6890. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6891. uvNode = builder.context.getUV( this );
  6892. }
  6893. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6894. if ( this.updateMatrix === true ) {
  6895. uvNode = this.getTransformedUV( uvNode );
  6896. }
  6897. uvNode = this.setupUV( builder, uvNode );
  6898. //
  6899. let levelNode = this.levelNode;
  6900. if ( levelNode === null && builder.context.getTextureLevel ) {
  6901. levelNode = builder.context.getTextureLevel( this );
  6902. }
  6903. //
  6904. properties.uvNode = uvNode;
  6905. properties.levelNode = levelNode;
  6906. properties.biasNode = this.biasNode;
  6907. properties.compareNode = this.compareNode;
  6908. properties.gradNode = this.gradNode;
  6909. properties.depthNode = this.depthNode;
  6910. }
  6911. /**
  6912. * Generates the uv code snippet.
  6913. *
  6914. * @param {NodeBuilder} builder - The current node builder.
  6915. * @param {Node} uvNode - The uv node to generate code for.
  6916. * @return {string} The generated code snippet.
  6917. */
  6918. generateUV( builder, uvNode ) {
  6919. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6920. }
  6921. /**
  6922. * Generates the snippet for the texture sampling.
  6923. *
  6924. * @param {NodeBuilder} builder - The current node builder.
  6925. * @param {string} textureProperty - The texture property.
  6926. * @param {string} uvSnippet - The uv snippet.
  6927. * @param {?string} levelSnippet - The level snippet.
  6928. * @param {?string} biasSnippet - The bias snippet.
  6929. * @param {?string} depthSnippet - The depth snippet.
  6930. * @param {?string} compareSnippet - The compare snippet.
  6931. * @param {?Array<string>} gradSnippet - The grad snippet.
  6932. * @return {string} The generated code snippet.
  6933. */
  6934. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6935. const texture = this.value;
  6936. let snippet;
  6937. if ( levelSnippet ) {
  6938. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6939. } else if ( biasSnippet ) {
  6940. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6941. } else if ( gradSnippet ) {
  6942. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6943. } else if ( compareSnippet ) {
  6944. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6945. } else if ( this.sampler === false ) {
  6946. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6947. } else {
  6948. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6949. }
  6950. return snippet;
  6951. }
  6952. /**
  6953. * Generates the code snippet of the texture node.
  6954. *
  6955. * @param {NodeBuilder} builder - The current node builder.
  6956. * @param {string} output - The current output.
  6957. * @return {string} The generated code snippet.
  6958. */
  6959. generate( builder, output ) {
  6960. const texture = this.value;
  6961. const properties = builder.getNodeProperties( this );
  6962. const textureProperty = super.generate( builder, 'property' );
  6963. if ( output === 'sampler' ) {
  6964. return textureProperty + '_sampler';
  6965. } else if ( builder.isReference( output ) ) {
  6966. return textureProperty;
  6967. } else {
  6968. const nodeData = builder.getDataFromNode( this );
  6969. let propertyName = nodeData.propertyName;
  6970. if ( propertyName === undefined ) {
  6971. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6972. const uvSnippet = this.generateUV( builder, uvNode );
  6973. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6974. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6975. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6976. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6977. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6978. const nodeVar = builder.getVarFromNode( this );
  6979. propertyName = builder.getPropertyName( nodeVar );
  6980. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6981. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6982. nodeData.snippet = snippet;
  6983. nodeData.propertyName = propertyName;
  6984. }
  6985. let snippet = propertyName;
  6986. const nodeType = this.getNodeType( builder );
  6987. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6988. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6989. }
  6990. return builder.format( snippet, nodeType, output );
  6991. }
  6992. }
  6993. /**
  6994. * Sets the sampler value.
  6995. *
  6996. * @param {boolean} value - The sampler value to set.
  6997. * @return {TextureNode} A reference to this texture node.
  6998. */
  6999. setSampler( value ) {
  7000. this.sampler = value;
  7001. return this;
  7002. }
  7003. /**
  7004. * Returns the sampler value.
  7005. *
  7006. * @return {boolean} The sampler value.
  7007. */
  7008. getSampler() {
  7009. return this.sampler;
  7010. }
  7011. // @TODO: Move to TSL
  7012. /**
  7013. * @function
  7014. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7015. *
  7016. * @param {Node} uvNode - The uv node.
  7017. * @return {TextureNode} A texture node representing the texture sample.
  7018. */
  7019. uv( uvNode ) { // @deprecated, r172
  7020. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7021. return this.sample( uvNode );
  7022. }
  7023. /**
  7024. * Samples the texture with the given uv node.
  7025. *
  7026. * @param {Node} uvNode - The uv node.
  7027. * @return {TextureNode} A texture node representing the texture sample.
  7028. */
  7029. sample( uvNode ) {
  7030. const textureNode = this.clone();
  7031. textureNode.uvNode = nodeObject( uvNode );
  7032. textureNode.referenceNode = this.getSelf();
  7033. return nodeObject( textureNode );
  7034. }
  7035. /**
  7036. * Samples a blurred version of the texture by defining an internal bias.
  7037. *
  7038. * @param {Node<float>} amountNode - How blurred the texture should be.
  7039. * @return {TextureNode} A texture node representing the texture sample.
  7040. */
  7041. blur( amountNode ) {
  7042. const textureNode = this.clone();
  7043. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7044. textureNode.referenceNode = this.getSelf();
  7045. return nodeObject( textureNode );
  7046. }
  7047. /**
  7048. * Samples a specific mip of the texture.
  7049. *
  7050. * @param {Node<int>} levelNode - The mip level to sample.
  7051. * @return {TextureNode} A texture node representing the texture sample.
  7052. */
  7053. level( levelNode ) {
  7054. const textureNode = this.clone();
  7055. textureNode.levelNode = nodeObject( levelNode );
  7056. textureNode.referenceNode = this.getSelf();
  7057. return nodeObject( textureNode );
  7058. }
  7059. /**
  7060. * Returns the texture size of the requested level.
  7061. *
  7062. * @param {Node<int>} levelNode - The level to compute the size for.
  7063. * @return {TextureSizeNode} The texture size.
  7064. */
  7065. size( levelNode ) {
  7066. return textureSize( this, levelNode );
  7067. }
  7068. /**
  7069. * Samples the texture with the given bias.
  7070. *
  7071. * @param {Node<float>} biasNode - The bias node.
  7072. * @return {TextureNode} A texture node representing the texture sample.
  7073. */
  7074. bias( biasNode ) {
  7075. const textureNode = this.clone();
  7076. textureNode.biasNode = nodeObject( biasNode );
  7077. textureNode.referenceNode = this.getSelf();
  7078. return nodeObject( textureNode );
  7079. }
  7080. /**
  7081. * Samples the texture by executing a compare operation.
  7082. *
  7083. * @param {Node<float>} compareNode - The node that defines the compare value.
  7084. * @return {TextureNode} A texture node representing the texture sample.
  7085. */
  7086. compare( compareNode ) {
  7087. const textureNode = this.clone();
  7088. textureNode.compareNode = nodeObject( compareNode );
  7089. textureNode.referenceNode = this.getSelf();
  7090. return nodeObject( textureNode );
  7091. }
  7092. /**
  7093. * Samples the texture using an explicit gradient.
  7094. *
  7095. * @param {Node<vec2>} gradNodeX - The gradX node.
  7096. * @param {Node<vec2>} gradNodeY - The gradY node.
  7097. * @return {TextureNode} A texture node representing the texture sample.
  7098. */
  7099. grad( gradNodeX, gradNodeY ) {
  7100. const textureNode = this.clone();
  7101. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7102. textureNode.referenceNode = this.getSelf();
  7103. return nodeObject( textureNode );
  7104. }
  7105. /**
  7106. * Samples the texture by defining a depth node.
  7107. *
  7108. * @param {Node<int>} depthNode - The depth node.
  7109. * @return {TextureNode} A texture node representing the texture sample.
  7110. */
  7111. depth( depthNode ) {
  7112. const textureNode = this.clone();
  7113. textureNode.depthNode = nodeObject( depthNode );
  7114. textureNode.referenceNode = this.getSelf();
  7115. return nodeObject( textureNode );
  7116. }
  7117. // --
  7118. serialize( data ) {
  7119. super.serialize( data );
  7120. data.value = this.value.toJSON( data.meta ).uuid;
  7121. data.sampler = this.sampler;
  7122. data.updateMatrix = this.updateMatrix;
  7123. data.updateType = this.updateType;
  7124. }
  7125. deserialize( data ) {
  7126. super.deserialize( data );
  7127. this.value = data.meta.textures[ data.value ];
  7128. this.sampler = data.sampler;
  7129. this.updateMatrix = data.updateMatrix;
  7130. this.updateType = data.updateType;
  7131. }
  7132. /**
  7133. * The update is used to implement the update of the uv transformation matrix.
  7134. */
  7135. update() {
  7136. const texture = this.value;
  7137. const matrixUniform = this._matrixUniform;
  7138. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7139. if ( texture.matrixAutoUpdate === true ) {
  7140. texture.updateMatrix();
  7141. }
  7142. }
  7143. /**
  7144. * Clones the texture node.
  7145. *
  7146. * @return {TextureNode} The cloned texture node.
  7147. */
  7148. clone() {
  7149. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7150. newNode.sampler = this.sampler;
  7151. return newNode;
  7152. }
  7153. }
  7154. /**
  7155. * TSL function for creating a texture node.
  7156. *
  7157. * @tsl
  7158. * @function
  7159. * @param {Texture} value - The texture.
  7160. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7161. * @param {?Node<int>} [levelNode=null] - The level node.
  7162. * @param {?Node<float>} [biasNode=null] - The bias node.
  7163. * @returns {TextureNode}
  7164. */
  7165. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  7166. /**
  7167. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7168. *
  7169. * @tsl
  7170. * @function
  7171. * @param {Texture} value - The texture.
  7172. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7173. * @param {?Node<int>} [levelNode=null] - The level node.
  7174. * @param {?Node<float>} [biasNode=null] - The bias node.
  7175. * @returns {TextureNode}
  7176. */
  7177. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7178. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7179. /**
  7180. * Converts a texture or texture node to a sampler.
  7181. *
  7182. * @tsl
  7183. * @function
  7184. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  7185. * @returns {Node}
  7186. */
  7187. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  7188. /**
  7189. * A special type of uniform node which represents array-like data
  7190. * as uniform buffers. The access usually happens via `element()`
  7191. * which returns an instance of {@link ArrayElementNode}. For example:
  7192. *
  7193. * ```js
  7194. * const bufferNode = buffer( array, 'mat4', count );
  7195. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7196. * ```
  7197. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7198. * since it handles more input types and automatically cares about buffer paddings.
  7199. *
  7200. * @augments UniformNode
  7201. */
  7202. class BufferNode extends UniformNode {
  7203. static get type() {
  7204. return 'BufferNode';
  7205. }
  7206. /**
  7207. * Constructs a new buffer node.
  7208. *
  7209. * @param {Array<number>} value - Array-like buffer data.
  7210. * @param {string} bufferType - The data type of the buffer.
  7211. * @param {number} [bufferCount=0] - The count of buffer elements.
  7212. */
  7213. constructor( value, bufferType, bufferCount = 0 ) {
  7214. super( value, bufferType );
  7215. /**
  7216. * This flag can be used for type testing.
  7217. *
  7218. * @type {boolean}
  7219. * @readonly
  7220. * @default true
  7221. */
  7222. this.isBufferNode = true;
  7223. /**
  7224. * The data type of the buffer.
  7225. *
  7226. * @type {string}
  7227. */
  7228. this.bufferType = bufferType;
  7229. /**
  7230. * The uniform node that holds the value of the reference node.
  7231. *
  7232. * @type {number}
  7233. * @default 0
  7234. */
  7235. this.bufferCount = bufferCount;
  7236. }
  7237. /**
  7238. * The data type of the buffer elements.
  7239. *
  7240. * @param {NodeBuilder} builder - The current node builder.
  7241. * @return {string} The element type.
  7242. */
  7243. getElementType( builder ) {
  7244. return this.getNodeType( builder );
  7245. }
  7246. /**
  7247. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7248. *
  7249. * @param {NodeBuilder} builder - The current node builder.
  7250. * @return {string} The input type.
  7251. */
  7252. getInputType( /*builder*/ ) {
  7253. return 'buffer';
  7254. }
  7255. }
  7256. /**
  7257. * TSL function for creating a buffer node.
  7258. *
  7259. * @tsl
  7260. * @function
  7261. * @param {Array} value - Array-like buffer data.
  7262. * @param {string} type - The data type of a buffer element.
  7263. * @param {number} count - The count of buffer elements.
  7264. * @returns {BufferNode}
  7265. */
  7266. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7267. /**
  7268. * Represents the element access on uniform array nodes.
  7269. *
  7270. * @augments ArrayElementNode
  7271. */
  7272. class UniformArrayElementNode extends ArrayElementNode {
  7273. static get type() {
  7274. return 'UniformArrayElementNode';
  7275. }
  7276. /**
  7277. * Constructs a new buffer node.
  7278. *
  7279. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7280. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7281. */
  7282. constructor( uniformArrayNode, indexNode ) {
  7283. super( uniformArrayNode, indexNode );
  7284. /**
  7285. * This flag can be used for type testing.
  7286. *
  7287. * @type {boolean}
  7288. * @readonly
  7289. * @default true
  7290. */
  7291. this.isArrayBufferElementNode = true;
  7292. }
  7293. generate( builder ) {
  7294. const snippet = super.generate( builder );
  7295. const type = this.getNodeType();
  7296. const paddedType = this.node.getPaddedType();
  7297. return builder.format( snippet, paddedType, type );
  7298. }
  7299. }
  7300. /**
  7301. * Similar to {@link BufferNode} this module represents array-like data as
  7302. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7303. * data types in the array (e.g `three.js` primitives) and automatically
  7304. * manage buffer padding. It should be the first choice when working with
  7305. * uniforms buffers.
  7306. * ```js
  7307. * const tintColors = uniformArray( [
  7308. * new Color( 1, 0, 0 ),
  7309. * new Color( 0, 1, 0 ),
  7310. * new Color( 0, 0, 1 )
  7311. * ], 'color' );
  7312. *
  7313. * const redColor = tintColors.element( 0 );
  7314. *
  7315. * @augments BufferNode
  7316. */
  7317. class UniformArrayNode extends BufferNode {
  7318. static get type() {
  7319. return 'UniformArrayNode';
  7320. }
  7321. /**
  7322. * Constructs a new uniform array node.
  7323. *
  7324. * @param {Array<any>} value - Array holding the buffer data.
  7325. * @param {?string} [elementType=null] - The data type of a buffer element.
  7326. */
  7327. constructor( value, elementType = null ) {
  7328. super( null );
  7329. /**
  7330. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7331. * hold number primitives as well as three.js objects like vectors, matrices
  7332. * or colors.
  7333. *
  7334. * @type {Array<any>}
  7335. */
  7336. this.array = value;
  7337. /**
  7338. * The data type of an array element.
  7339. *
  7340. * @type {string}
  7341. */
  7342. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7343. /**
  7344. * The padded type. Uniform buffers must conform to a certain buffer layout
  7345. * so a separate type is computed to ensure correct buffer size.
  7346. *
  7347. * @type {string}
  7348. */
  7349. this.paddedType = this.getPaddedType();
  7350. /**
  7351. * Overwritten since uniform array nodes are updated per render.
  7352. *
  7353. * @type {string}
  7354. * @default 'render'
  7355. */
  7356. this.updateType = NodeUpdateType.RENDER;
  7357. /**
  7358. * This flag can be used for type testing.
  7359. *
  7360. * @type {boolean}
  7361. * @readonly
  7362. * @default true
  7363. */
  7364. this.isArrayBufferNode = true;
  7365. }
  7366. /**
  7367. * This method is overwritten since the node type is inferred from the
  7368. * {@link UniformArrayNode#paddedType}.
  7369. *
  7370. * @param {NodeBuilder} builder - The current node builder.
  7371. * @return {string} The node type.
  7372. */
  7373. getNodeType( /*builder*/ ) {
  7374. return this.paddedType;
  7375. }
  7376. /**
  7377. * The data type of the array elements.
  7378. *
  7379. * @param {NodeBuilder} builder - The current node builder.
  7380. * @return {string} The element type.
  7381. */
  7382. getElementType() {
  7383. return this.elementType;
  7384. }
  7385. /**
  7386. * Returns the padded type based on the element type.
  7387. *
  7388. * @return {string} The padded type.
  7389. */
  7390. getPaddedType() {
  7391. const elementType = this.elementType;
  7392. let paddedType = 'vec4';
  7393. if ( elementType === 'mat2' ) {
  7394. paddedType = 'mat2';
  7395. } else if ( /mat/.test( elementType ) === true ) {
  7396. paddedType = 'mat4';
  7397. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7398. paddedType = 'ivec4';
  7399. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7400. paddedType = 'uvec4';
  7401. }
  7402. return paddedType;
  7403. }
  7404. /**
  7405. * The update makes sure to correctly transfer the data from the (complex) objects
  7406. * in the array to the internal, correctly padded value buffer.
  7407. *
  7408. * @param {NodeFrame} frame - A reference to the current node frame.
  7409. */
  7410. update( /*frame*/ ) {
  7411. const { array, value } = this;
  7412. const elementType = this.elementType;
  7413. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7414. for ( let i = 0; i < array.length; i ++ ) {
  7415. const index = i * 4;
  7416. value[ index ] = array[ i ];
  7417. }
  7418. } else if ( elementType === 'color' ) {
  7419. for ( let i = 0; i < array.length; i ++ ) {
  7420. const index = i * 4;
  7421. const vector = array[ i ];
  7422. value[ index ] = vector.r;
  7423. value[ index + 1 ] = vector.g;
  7424. value[ index + 2 ] = vector.b || 0;
  7425. //value[ index + 3 ] = vector.a || 0;
  7426. }
  7427. } else if ( elementType === 'mat2' ) {
  7428. for ( let i = 0; i < array.length; i ++ ) {
  7429. const index = i * 4;
  7430. const matrix = array[ i ];
  7431. value[ index ] = matrix.elements[ 0 ];
  7432. value[ index + 1 ] = matrix.elements[ 1 ];
  7433. value[ index + 2 ] = matrix.elements[ 2 ];
  7434. value[ index + 3 ] = matrix.elements[ 3 ];
  7435. }
  7436. } else if ( elementType === 'mat3' ) {
  7437. for ( let i = 0; i < array.length; i ++ ) {
  7438. const index = i * 16;
  7439. const matrix = array[ i ];
  7440. value[ index ] = matrix.elements[ 0 ];
  7441. value[ index + 1 ] = matrix.elements[ 1 ];
  7442. value[ index + 2 ] = matrix.elements[ 2 ];
  7443. value[ index + 4 ] = matrix.elements[ 3 ];
  7444. value[ index + 5 ] = matrix.elements[ 4 ];
  7445. value[ index + 6 ] = matrix.elements[ 5 ];
  7446. value[ index + 8 ] = matrix.elements[ 6 ];
  7447. value[ index + 9 ] = matrix.elements[ 7 ];
  7448. value[ index + 10 ] = matrix.elements[ 8 ];
  7449. value[ index + 15 ] = 1;
  7450. }
  7451. } else if ( elementType === 'mat4' ) {
  7452. for ( let i = 0; i < array.length; i ++ ) {
  7453. const index = i * 16;
  7454. const matrix = array[ i ];
  7455. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7456. value[ index + i ] = matrix.elements[ i ];
  7457. }
  7458. }
  7459. } else {
  7460. for ( let i = 0; i < array.length; i ++ ) {
  7461. const index = i * 4;
  7462. const vector = array[ i ];
  7463. value[ index ] = vector.x;
  7464. value[ index + 1 ] = vector.y;
  7465. value[ index + 2 ] = vector.z || 0;
  7466. value[ index + 3 ] = vector.w || 0;
  7467. }
  7468. }
  7469. }
  7470. /**
  7471. * Implement the value buffer creation based on the array data.
  7472. *
  7473. * @param {NodeBuilder} builder - A reference to the current node builder.
  7474. * @return {null}
  7475. */
  7476. setup( builder ) {
  7477. const length = this.array.length;
  7478. const elementType = this.elementType;
  7479. let arrayType = Float32Array;
  7480. const paddedType = this.paddedType;
  7481. const paddedElementLength = builder.getTypeLength( paddedType );
  7482. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7483. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7484. this.value = new arrayType( length * paddedElementLength );
  7485. this.bufferCount = length;
  7486. this.bufferType = paddedType;
  7487. return super.setup( builder );
  7488. }
  7489. /**
  7490. * Overwrites the default `element()` method to provide element access
  7491. * based on {@link UniformArrayNode}.
  7492. *
  7493. * @param {IndexNode} indexNode - The index node.
  7494. * @return {UniformArrayElementNode}
  7495. */
  7496. element( indexNode ) {
  7497. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7498. }
  7499. }
  7500. /**
  7501. * TSL function for creating an uniform array node.
  7502. *
  7503. * @tsl
  7504. * @function
  7505. * @param {Array<any>} values - Array-like data.
  7506. * @param {?string} nodeType - The data type of the array elements.
  7507. * @returns {UniformArrayNode}
  7508. */
  7509. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7510. /**
  7511. * @tsl
  7512. * @function
  7513. * @deprecated since r168. Use {@link uniformArray} instead.
  7514. *
  7515. * @param {Array<any>} values - Array-like data.
  7516. * @param {string} nodeType - The data type of the array elements.
  7517. * @returns {UniformArrayNode}
  7518. */
  7519. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7520. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7521. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7522. };
  7523. /**
  7524. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7525. *
  7526. * @tsl
  7527. * @type {UniformNode<uint>}
  7528. */
  7529. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7530. /**
  7531. * TSL object that represents the `near` value of the camera used for the current render.
  7532. *
  7533. * @tsl
  7534. * @type {UniformNode<float>}
  7535. */
  7536. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7537. /**
  7538. * TSL object that represents the `far` value of the camera used for the current render.
  7539. *
  7540. * @tsl
  7541. * @type {UniformNode<float>}
  7542. */
  7543. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7544. /**
  7545. * TSL object that represents the projection matrix of the camera used for the current render.
  7546. *
  7547. * @tsl
  7548. * @type {UniformNode<mat4>}
  7549. */
  7550. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7551. let cameraProjectionMatrix;
  7552. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7553. const matrices = [];
  7554. for ( const subCamera of camera.cameras ) {
  7555. matrices.push( subCamera.projectionMatrix );
  7556. }
  7557. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7558. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7559. } else {
  7560. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7561. }
  7562. return cameraProjectionMatrix;
  7563. } ).once() )();
  7564. /**
  7565. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7566. *
  7567. * @tsl
  7568. * @type {UniformNode<mat4>}
  7569. */
  7570. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7571. /**
  7572. * TSL object that represents the view matrix of the camera used for the current render.
  7573. *
  7574. * @tsl
  7575. * @type {UniformNode<mat4>}
  7576. */
  7577. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7578. let cameraViewMatrix;
  7579. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7580. const matrices = [];
  7581. for ( const subCamera of camera.cameras ) {
  7582. matrices.push( subCamera.matrixWorldInverse );
  7583. }
  7584. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7585. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7586. } else {
  7587. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7588. }
  7589. return cameraViewMatrix;
  7590. } ).once() )();
  7591. /**
  7592. * TSL object that represents the world matrix of the camera used for the current render.
  7593. *
  7594. * @tsl
  7595. * @type {UniformNode<mat4>}
  7596. */
  7597. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7598. /**
  7599. * TSL object that represents the normal matrix of the camera used for the current render.
  7600. *
  7601. * @tsl
  7602. * @type {UniformNode<mat3>}
  7603. */
  7604. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7605. /**
  7606. * TSL object that represents the position in world space of the camera used for the current render.
  7607. *
  7608. * @tsl
  7609. * @type {UniformNode<vec3>}
  7610. */
  7611. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7612. /**
  7613. * This node can be used to access transformation related metrics of 3D objects.
  7614. * Depending on the selected scope, a different metric is represented as a uniform
  7615. * in the shader. The following scopes are supported:
  7616. *
  7617. * - `POSITION`: The object's position in world space.
  7618. * - `VIEW_POSITION`: The object's position in view/camera space.
  7619. * - `DIRECTION`: The object's direction in world space.
  7620. * - `SCALE`: The object's scale in world space.
  7621. * - `WORLD_MATRIX`: The object's matrix in world space.
  7622. *
  7623. * @augments Node
  7624. */
  7625. class Object3DNode extends Node {
  7626. static get type() {
  7627. return 'Object3DNode';
  7628. }
  7629. /**
  7630. * Constructs a new object 3D node.
  7631. *
  7632. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7633. * @param {?Object3D} [object3d=null] - The 3D object.
  7634. */
  7635. constructor( scope, object3d = null ) {
  7636. super();
  7637. /**
  7638. * The node reports a different type of transformation depending on the scope.
  7639. *
  7640. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7641. */
  7642. this.scope = scope;
  7643. /**
  7644. * The 3D object.
  7645. *
  7646. * @type {?Object3D}
  7647. * @default null
  7648. */
  7649. this.object3d = object3d;
  7650. /**
  7651. * Overwritten since this type of node is updated per object.
  7652. *
  7653. * @type {string}
  7654. * @default 'object'
  7655. */
  7656. this.updateType = NodeUpdateType.OBJECT;
  7657. /**
  7658. * Holds the value of the node as a uniform.
  7659. *
  7660. * @private
  7661. * @type {UniformNode}
  7662. */
  7663. this._uniformNode = new UniformNode( null );
  7664. }
  7665. /**
  7666. * Overwritten since the node type is inferred from the scope.
  7667. *
  7668. * @return {string} The node type.
  7669. */
  7670. getNodeType() {
  7671. const scope = this.scope;
  7672. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7673. return 'mat4';
  7674. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7675. return 'vec3';
  7676. }
  7677. }
  7678. /**
  7679. * Updates the uniform value depending on the scope.
  7680. *
  7681. * @param {NodeFrame} frame - The current node frame.
  7682. */
  7683. update( frame ) {
  7684. const object = this.object3d;
  7685. const uniformNode = this._uniformNode;
  7686. const scope = this.scope;
  7687. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7688. uniformNode.value = object.matrixWorld;
  7689. } else if ( scope === Object3DNode.POSITION ) {
  7690. uniformNode.value = uniformNode.value || new Vector3();
  7691. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7692. } else if ( scope === Object3DNode.SCALE ) {
  7693. uniformNode.value = uniformNode.value || new Vector3();
  7694. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7695. } else if ( scope === Object3DNode.DIRECTION ) {
  7696. uniformNode.value = uniformNode.value || new Vector3();
  7697. object.getWorldDirection( uniformNode.value );
  7698. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7699. const camera = frame.camera;
  7700. uniformNode.value = uniformNode.value || new Vector3();
  7701. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7702. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7703. }
  7704. }
  7705. /**
  7706. * Generates the code snippet of the uniform node. The node type of the uniform
  7707. * node also depends on the selected scope.
  7708. *
  7709. * @param {NodeBuilder} builder - The current node builder.
  7710. * @return {string} The generated code snippet.
  7711. */
  7712. generate( builder ) {
  7713. const scope = this.scope;
  7714. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7715. this._uniformNode.nodeType = 'mat4';
  7716. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7717. this._uniformNode.nodeType = 'vec3';
  7718. }
  7719. return this._uniformNode.build( builder );
  7720. }
  7721. serialize( data ) {
  7722. super.serialize( data );
  7723. data.scope = this.scope;
  7724. }
  7725. deserialize( data ) {
  7726. super.deserialize( data );
  7727. this.scope = data.scope;
  7728. }
  7729. }
  7730. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7731. Object3DNode.POSITION = 'position';
  7732. Object3DNode.SCALE = 'scale';
  7733. Object3DNode.VIEW_POSITION = 'viewPosition';
  7734. Object3DNode.DIRECTION = 'direction';
  7735. /**
  7736. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7737. *
  7738. * @tsl
  7739. * @function
  7740. * @param {?Object3D} [object3d=null] - The 3D object.
  7741. * @returns {Object3DNode<vec3>}
  7742. */
  7743. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7744. /**
  7745. * TSL function for creating an object 3D node that represents the object's world matrix.
  7746. *
  7747. * @tsl
  7748. * @function
  7749. * @param {?Object3D} [object3d=null] - The 3D object.
  7750. * @returns {Object3DNode<mat4>}
  7751. */
  7752. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7753. /**
  7754. * TSL function for creating an object 3D node that represents the object's position in world space.
  7755. *
  7756. * @tsl
  7757. * @function
  7758. * @param {?Object3D} [object3d=null] - The 3D object.
  7759. * @returns {Object3DNode<vec3>}
  7760. */
  7761. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7762. /**
  7763. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7764. *
  7765. * @tsl
  7766. * @function
  7767. * @param {?Object3D} [object3d=null] - The 3D object.
  7768. * @returns {Object3DNode<vec3>}
  7769. */
  7770. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7771. /**
  7772. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7773. *
  7774. * @tsl
  7775. * @function
  7776. * @param {?Object3D} [object3d=null] - The 3D object.
  7777. * @returns {Object3DNode<vec3>}
  7778. */
  7779. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7780. /**
  7781. * This type of node is a specialized version of `Object3DNode`
  7782. * with larger set of model related metrics. Unlike `Object3DNode`,
  7783. * `ModelNode` extracts the reference to the 3D object from the
  7784. * current node frame state.
  7785. *
  7786. * @augments Object3DNode
  7787. */
  7788. class ModelNode extends Object3DNode {
  7789. static get type() {
  7790. return 'ModelNode';
  7791. }
  7792. /**
  7793. * Constructs a new object model node.
  7794. *
  7795. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7796. */
  7797. constructor( scope ) {
  7798. super( scope );
  7799. }
  7800. /**
  7801. * Extracts the model reference from the frame state and then
  7802. * updates the uniform value depending on the scope.
  7803. *
  7804. * @param {NodeFrame} frame - The current node frame.
  7805. */
  7806. update( frame ) {
  7807. this.object3d = frame.object;
  7808. super.update( frame );
  7809. }
  7810. }
  7811. /**
  7812. * TSL object that represents the object's direction in world space.
  7813. *
  7814. * @tsl
  7815. * @type {ModelNode<vec3>}
  7816. */
  7817. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7818. /**
  7819. * TSL object that represents the object's world matrix.
  7820. *
  7821. * @tsl
  7822. * @type {ModelNode<mat4>}
  7823. */
  7824. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7825. /**
  7826. * TSL object that represents the object's position in world space.
  7827. *
  7828. * @tsl
  7829. * @type {ModelNode<vec3>}
  7830. */
  7831. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7832. /**
  7833. * TSL object that represents the object's scale in world space.
  7834. *
  7835. * @tsl
  7836. * @type {ModelNode<vec3>}
  7837. */
  7838. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7839. /**
  7840. * TSL object that represents the object's position in view/camera space.
  7841. *
  7842. * @tsl
  7843. * @type {ModelNode<vec3>}
  7844. */
  7845. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7846. /**
  7847. * TSL object that represents the object's normal matrix.
  7848. *
  7849. * @tsl
  7850. * @type {UniformNode<mat3>}
  7851. */
  7852. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7853. /**
  7854. * TSL object that represents the object's inverse world matrix.
  7855. *
  7856. * @tsl
  7857. * @type {UniformNode<mat4>}
  7858. */
  7859. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7860. /**
  7861. * TSL object that represents the object's model view matrix.
  7862. *
  7863. * @tsl
  7864. * @type {Node<mat4>}
  7865. */
  7866. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7867. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7868. } ).once() )().toVar( 'modelViewMatrix' );
  7869. // GPU Precision
  7870. /**
  7871. * TSL object that represents the object's model view in `mediump` precision.
  7872. *
  7873. * @tsl
  7874. * @type {Node<mat4>}
  7875. */
  7876. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7877. // CPU Precision
  7878. /**
  7879. * TSL object that represents the object's model view in `highp` precision
  7880. * which is achieved by computing the matrix in JS and not in the shader.
  7881. *
  7882. * @tsl
  7883. * @type {Node<mat4>}
  7884. */
  7885. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7886. builder.context.isHighPrecisionModelViewMatrix = true;
  7887. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7888. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7889. } );
  7890. } ).once() )().toVar( 'highpModelViewMatrix' );
  7891. /**
  7892. * TSL object that represents the object's model normal view in `highp` precision
  7893. * which is achieved by computing the matrix in JS and not in the shader.
  7894. *
  7895. * @tsl
  7896. * @type {Node<mat3>}
  7897. */
  7898. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7899. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7900. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7901. if ( isHighPrecisionModelViewMatrix !== true ) {
  7902. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7903. }
  7904. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7905. } );
  7906. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7907. /**
  7908. * TSL object that represents the position attribute of the current rendered object.
  7909. *
  7910. * @tsl
  7911. * @type {AttributeNode<vec3>}
  7912. */
  7913. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7914. /**
  7915. * TSL object that represents the vertex position in local space of the current rendered object.
  7916. *
  7917. * @tsl
  7918. * @type {AttributeNode<vec3>}
  7919. */
  7920. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7921. /**
  7922. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7923. * Used in context of {@link VelocityNode} for rendering motion vectors.
  7924. *
  7925. * @tsl
  7926. * @type {AttributeNode<vec3>}
  7927. */
  7928. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7929. /**
  7930. * TSL object that represents the vertex position in world space of the current rendered object.
  7931. *
  7932. * @tsl
  7933. * @type {VaryingNode<vec3>}
  7934. */
  7935. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7936. /**
  7937. * TSL object that represents the position world direction of the current rendered object.
  7938. *
  7939. * @tsl
  7940. * @type {Node<vec3>}
  7941. */
  7942. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7943. /**
  7944. * TSL object that represents the vertex position in view space of the current rendered object.
  7945. *
  7946. * @tsl
  7947. * @type {VaryingNode<vec3>}
  7948. */
  7949. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7950. return builder.context.setupPositionView();
  7951. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7952. /**
  7953. * TSL object that represents the position view direction of the current rendered object.
  7954. *
  7955. * @tsl
  7956. * @type {VaryingNode<vec3>}
  7957. */
  7958. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7959. /**
  7960. * This node can be used to evaluate whether a primitive is front or back facing.
  7961. *
  7962. * @augments Node
  7963. */
  7964. class FrontFacingNode extends Node {
  7965. static get type() {
  7966. return 'FrontFacingNode';
  7967. }
  7968. /**
  7969. * Constructs a new front facing node.
  7970. */
  7971. constructor() {
  7972. super( 'bool' );
  7973. /**
  7974. * This flag can be used for type testing.
  7975. *
  7976. * @type {boolean}
  7977. * @readonly
  7978. * @default true
  7979. */
  7980. this.isFrontFacingNode = true;
  7981. }
  7982. generate( builder ) {
  7983. const { renderer, material } = builder;
  7984. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7985. if ( material.side === BackSide ) {
  7986. return 'false';
  7987. }
  7988. }
  7989. return builder.getFrontFacing();
  7990. }
  7991. }
  7992. /**
  7993. * TSL object that represents whether a primitive is front or back facing
  7994. *
  7995. * @tsl
  7996. * @type {FrontFacingNode<bool>}
  7997. */
  7998. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7999. /**
  8000. * TSL object that represents the front facing status as a number instead of a bool.
  8001. * `1` means front facing, `-1` means back facing.
  8002. *
  8003. * @tsl
  8004. * @type {Node<float>}
  8005. */
  8006. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8007. /**
  8008. * TSL object that represents the normal attribute of the current rendered object.
  8009. *
  8010. * @tsl
  8011. * @type {Node<vec3>}
  8012. */
  8013. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8014. /**
  8015. * TSL object that represents the vertex normal in local space of the current rendered object.
  8016. *
  8017. * @tsl
  8018. * @type {Node<vec3>}
  8019. */
  8020. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8021. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8022. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  8023. return vec3( 0, 1, 0 );
  8024. }
  8025. return normalGeometry;
  8026. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8027. /**
  8028. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8029. *
  8030. * @tsl
  8031. * @type {Node<vec3>}
  8032. */
  8033. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8034. /**
  8035. * TSL object that represents the vertex normal in view space of the current rendered object.
  8036. *
  8037. * @tsl
  8038. * @type {Node<vec3>}
  8039. */
  8040. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8041. let node;
  8042. if ( builder.material.flatShading === true ) {
  8043. node = normalFlat;
  8044. } else {
  8045. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8046. }
  8047. return node;
  8048. }, 'vec3' ).once() )().toVar( 'normalView' );
  8049. /**
  8050. * TSL object that represents the vertex normal in world space of the current rendered object.
  8051. *
  8052. * @tsl
  8053. * @type {Node<vec3>}
  8054. */
  8055. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  8056. /**
  8057. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8058. *
  8059. * @tsl
  8060. * @type {Node<vec3>}
  8061. */
  8062. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8063. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8064. return builder.context.setupNormal().context( { getUV: null } );
  8065. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  8066. /**
  8067. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8068. *
  8069. * @tsl
  8070. * @type {Node<vec3>}
  8071. */
  8072. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8073. /**
  8074. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8075. *
  8076. * @tsl
  8077. * @type {Node<vec3>}
  8078. */
  8079. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8080. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8081. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  8082. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  8083. /**
  8084. * Transforms the normal with the given matrix.
  8085. *
  8086. * @tsl
  8087. * @function
  8088. * @param {Node<vec3>} normal - The normal.
  8089. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8090. * @return {Node<vec3>} The transformed normal.
  8091. */
  8092. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8093. const m = mat3( matrix );
  8094. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8095. return m.mul( transformedNormal ).xyz;
  8096. } );
  8097. /**
  8098. * Transforms the given normal from local to view space.
  8099. *
  8100. * @tsl
  8101. * @function
  8102. * @param {Node<vec3>} normal - The normal.
  8103. * @param {NodeBuilder} builder - The current node builder.
  8104. * @return {Node<vec3>} The transformed normal.
  8105. */
  8106. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8107. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  8108. if ( modelNormalViewMatrix !== null ) {
  8109. return modelNormalViewMatrix.transformDirection( normal );
  8110. }
  8111. //
  8112. const transformedNormal = modelNormalMatrix.mul( normal );
  8113. return cameraViewMatrix.transformDirection( transformedNormal );
  8114. } );
  8115. /**
  8116. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8117. *
  8118. * @tsl
  8119. * @type {UniformNode<float>}
  8120. */
  8121. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  8122. /**
  8123. * The reflect vector in view space.
  8124. *
  8125. * @tsl
  8126. * @type {Node<vec3>}
  8127. */
  8128. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8129. /**
  8130. * The refract vector in view space.
  8131. *
  8132. * @tsl
  8133. * @type {Node<vec3>}
  8134. */
  8135. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8136. /**
  8137. * Used for sampling cube maps when using cube reflection mapping.
  8138. *
  8139. * @tsl
  8140. * @type {Node<vec3>}
  8141. */
  8142. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8143. /**
  8144. * Used for sampling cube maps when using cube refraction mapping.
  8145. *
  8146. * @tsl
  8147. * @type {Node<vec3>}
  8148. */
  8149. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8150. /**
  8151. * This type of uniform node represents a cube texture.
  8152. *
  8153. * @augments TextureNode
  8154. */
  8155. class CubeTextureNode extends TextureNode {
  8156. static get type() {
  8157. return 'CubeTextureNode';
  8158. }
  8159. /**
  8160. * Constructs a new cube texture node.
  8161. *
  8162. * @param {CubeTexture} value - The cube texture.
  8163. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8164. * @param {?Node<int>} [levelNode=null] - The level node.
  8165. * @param {?Node<float>} [biasNode=null] - The bias node.
  8166. */
  8167. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8168. super( value, uvNode, levelNode, biasNode );
  8169. /**
  8170. * This flag can be used for type testing.
  8171. *
  8172. * @type {boolean}
  8173. * @readonly
  8174. * @default true
  8175. */
  8176. this.isCubeTextureNode = true;
  8177. }
  8178. /**
  8179. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8180. *
  8181. * @param {NodeBuilder} builder - The current node builder.
  8182. * @return {string} The input type.
  8183. */
  8184. getInputType( /*builder*/ ) {
  8185. return 'cubeTexture';
  8186. }
  8187. /**
  8188. * Returns a default uvs based on the mapping type of the cube texture.
  8189. *
  8190. * @return {Node<vec3>} The default uv attribute.
  8191. */
  8192. getDefaultUV() {
  8193. const texture = this.value;
  8194. if ( texture.mapping === CubeReflectionMapping ) {
  8195. return reflectVector;
  8196. } else if ( texture.mapping === CubeRefractionMapping ) {
  8197. return refractVector;
  8198. } else {
  8199. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8200. return vec3( 0, 0, 0 );
  8201. }
  8202. }
  8203. /**
  8204. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8205. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8206. *
  8207. * @param {boolean} value - The update toggle.
  8208. */
  8209. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8210. /**
  8211. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8212. * to modify the uv node for correct sampling.
  8213. *
  8214. * @param {NodeBuilder} builder - The current node builder.
  8215. * @param {Node} uvNode - The uv node to setup.
  8216. * @return {Node} The updated uv node.
  8217. */
  8218. setupUV( builder, uvNode ) {
  8219. const texture = this.value;
  8220. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8221. return vec3( uvNode.x.negate(), uvNode.yz );
  8222. } else {
  8223. return uvNode;
  8224. }
  8225. }
  8226. /**
  8227. * Generates the uv code snippet.
  8228. *
  8229. * @param {NodeBuilder} builder - The current node builder.
  8230. * @param {Node} cubeUV - The uv node to generate code for.
  8231. * @return {string} The generated code snippet.
  8232. */
  8233. generateUV( builder, cubeUV ) {
  8234. return cubeUV.build( builder, 'vec3' );
  8235. }
  8236. }
  8237. /**
  8238. * TSL function for creating a cube texture node.
  8239. *
  8240. * @tsl
  8241. * @function
  8242. * @param {CubeTexture} value - The cube texture.
  8243. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8244. * @param {?Node<int>} [levelNode=null] - The level node.
  8245. * @param {?Node<float>} [biasNode=null] - The bias node.
  8246. * @returns {CubeTextureNode}
  8247. */
  8248. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  8249. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8250. /**
  8251. * This class is only relevant if the referenced property is array-like.
  8252. * In this case, `ReferenceElementNode` allows to refer to a specific
  8253. * element inside the data structure via an index.
  8254. *
  8255. * @augments ArrayElementNode
  8256. */
  8257. class ReferenceElementNode extends ArrayElementNode {
  8258. static get type() {
  8259. return 'ReferenceElementNode';
  8260. }
  8261. /**
  8262. * Constructs a new reference element node.
  8263. *
  8264. * @param {?ReferenceNode} referenceNode - The reference node.
  8265. * @param {Node} indexNode - The index node that defines the element access.
  8266. */
  8267. constructor( referenceNode, indexNode ) {
  8268. super( referenceNode, indexNode );
  8269. /**
  8270. * Similar to {@link ReferenceNode#reference}, an additional
  8271. * property references to the current node.
  8272. *
  8273. * @type {?ReferenceNode}
  8274. * @default null
  8275. */
  8276. this.referenceNode = referenceNode;
  8277. /**
  8278. * This flag can be used for type testing.
  8279. *
  8280. * @type {boolean}
  8281. * @readonly
  8282. * @default true
  8283. */
  8284. this.isReferenceElementNode = true;
  8285. }
  8286. /**
  8287. * This method is overwritten since the node type is inferred from
  8288. * the uniform type of the reference node.
  8289. *
  8290. * @return {string} The node type.
  8291. */
  8292. getNodeType() {
  8293. return this.referenceNode.uniformType;
  8294. }
  8295. generate( builder ) {
  8296. const snippet = super.generate( builder );
  8297. const arrayType = this.referenceNode.getNodeType();
  8298. const elementType = this.getNodeType();
  8299. return builder.format( snippet, arrayType, elementType );
  8300. }
  8301. }
  8302. /**
  8303. * This type of node establishes a reference to a property of another object.
  8304. * In this way, the value of the node is automatically linked to the value of
  8305. * referenced object. Reference nodes internally represent the linked value
  8306. * as a uniform.
  8307. *
  8308. * @augments Node
  8309. */
  8310. class ReferenceNode extends Node {
  8311. static get type() {
  8312. return 'ReferenceNode';
  8313. }
  8314. /**
  8315. * Constructs a new reference node.
  8316. *
  8317. * @param {string} property - The name of the property the node refers to.
  8318. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  8319. * @param {?Object} [object=null] - The object the property belongs to.
  8320. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8321. */
  8322. constructor( property, uniformType, object = null, count = null ) {
  8323. super();
  8324. /**
  8325. * The name of the property the node refers to.
  8326. *
  8327. * @type {string}
  8328. */
  8329. this.property = property;
  8330. /**
  8331. * The uniform type that should be used to represent the property value.
  8332. *
  8333. * @type {string}
  8334. */
  8335. this.uniformType = uniformType;
  8336. /**
  8337. * The object the property belongs to.
  8338. *
  8339. * @type {?Object}
  8340. * @default null
  8341. */
  8342. this.object = object;
  8343. /**
  8344. * When the linked property is an array, this parameter defines its length.
  8345. *
  8346. * @type {?number}
  8347. * @default null
  8348. */
  8349. this.count = count;
  8350. /**
  8351. * The property name might have dots so nested properties can be referred.
  8352. * The hierarchy of the names is stored inside this array.
  8353. *
  8354. * @type {Array<string>}
  8355. */
  8356. this.properties = property.split( '.' );
  8357. /**
  8358. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  8359. * since the final reference might be updated from calling code.
  8360. *
  8361. * @type {?Object}
  8362. * @default null
  8363. */
  8364. this.reference = object;
  8365. /**
  8366. * The uniform node that holds the value of the reference node.
  8367. *
  8368. * @type {UniformNode}
  8369. * @default null
  8370. */
  8371. this.node = null;
  8372. /**
  8373. * The uniform group of the internal uniform.
  8374. *
  8375. * @type {UniformGroupNode}
  8376. * @default null
  8377. */
  8378. this.group = null;
  8379. /**
  8380. * An optional label of the internal uniform node.
  8381. *
  8382. * @type {?string}
  8383. * @default null
  8384. */
  8385. this.name = null;
  8386. /**
  8387. * Overwritten since reference nodes are updated per object.
  8388. *
  8389. * @type {string}
  8390. * @default 'object'
  8391. */
  8392. this.updateType = NodeUpdateType.OBJECT;
  8393. }
  8394. /**
  8395. * When the referred property is array-like, this method can be used
  8396. * to access elements via an index node.
  8397. *
  8398. * @param {IndexNode} indexNode - indexNode.
  8399. * @return {ReferenceElementNode} A reference to an element.
  8400. */
  8401. element( indexNode ) {
  8402. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8403. }
  8404. /**
  8405. * Sets the uniform group for this reference node.
  8406. *
  8407. * @param {UniformGroupNode} group - The uniform group to set.
  8408. * @return {ReferenceNode} A reference to this node.
  8409. */
  8410. setGroup( group ) {
  8411. this.group = group;
  8412. return this;
  8413. }
  8414. /**
  8415. * Sets the label for the internal uniform.
  8416. *
  8417. * @param {string} name - The label to set.
  8418. * @return {ReferenceNode} A reference to this node.
  8419. */
  8420. label( name ) {
  8421. this.name = name;
  8422. return this;
  8423. }
  8424. /**
  8425. * Sets the node type which automatically defines the internal
  8426. * uniform type.
  8427. *
  8428. * @param {string} uniformType - The type to set.
  8429. */
  8430. setNodeType( uniformType ) {
  8431. let node = null;
  8432. if ( this.count !== null ) {
  8433. node = buffer( null, uniformType, this.count );
  8434. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8435. node = uniformArray( null, uniformType );
  8436. } else if ( uniformType === 'texture' ) {
  8437. node = texture( null );
  8438. } else if ( uniformType === 'cubeTexture' ) {
  8439. node = cubeTexture( null );
  8440. } else {
  8441. node = uniform( null, uniformType );
  8442. }
  8443. if ( this.group !== null ) {
  8444. node.setGroup( this.group );
  8445. }
  8446. if ( this.name !== null ) node.label( this.name );
  8447. this.node = node.getSelf();
  8448. }
  8449. /**
  8450. * This method is overwritten since the node type is inferred from
  8451. * the type of the reference node.
  8452. *
  8453. * @param {NodeBuilder} builder - The current node builder.
  8454. * @return {string} The node type.
  8455. */
  8456. getNodeType( builder ) {
  8457. if ( this.node === null ) {
  8458. this.updateReference( builder );
  8459. this.updateValue();
  8460. }
  8461. return this.node.getNodeType( builder );
  8462. }
  8463. /**
  8464. * Returns the property value from the given referred object.
  8465. *
  8466. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8467. * @return {any} The value.
  8468. */
  8469. getValueFromReference( object = this.reference ) {
  8470. const { properties } = this;
  8471. let value = object[ properties[ 0 ] ];
  8472. for ( let i = 1; i < properties.length; i ++ ) {
  8473. value = value[ properties[ i ] ];
  8474. }
  8475. return value;
  8476. }
  8477. /**
  8478. * Allows to update the reference based on the given state. The state is only
  8479. * evaluated {@link ReferenceNode#object} is not set.
  8480. *
  8481. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8482. * @return {Object} The updated reference.
  8483. */
  8484. updateReference( state ) {
  8485. this.reference = this.object !== null ? this.object : state.object;
  8486. return this.reference;
  8487. }
  8488. /**
  8489. * The output of the reference node is the internal uniform node.
  8490. *
  8491. * @param {NodeBuilder} builder - The current node builder.
  8492. * @return {UniformNode} The output node.
  8493. */
  8494. setup( /* builder */ ) {
  8495. this.updateValue();
  8496. return this.node;
  8497. }
  8498. /**
  8499. * Overwritten to to update the internal uniform value.
  8500. *
  8501. * @param {NodeFrame} frame - A reference to the current node frame.
  8502. */
  8503. update( /*frame*/ ) {
  8504. this.updateValue();
  8505. }
  8506. /**
  8507. * Retrieves the value from the referred object property and uses it
  8508. * to updated the internal uniform.
  8509. */
  8510. updateValue() {
  8511. if ( this.node === null ) this.setNodeType( this.uniformType );
  8512. const value = this.getValueFromReference();
  8513. if ( Array.isArray( value ) ) {
  8514. this.node.array = value;
  8515. } else {
  8516. this.node.value = value;
  8517. }
  8518. }
  8519. }
  8520. /**
  8521. * TSL function for creating a reference node.
  8522. *
  8523. * @tsl
  8524. * @function
  8525. * @param {string} name - The name of the property the node refers to.
  8526. * @param {string} type - The uniform type that should be used to represent the property value.
  8527. * @param {Object} object - The object the property belongs to.
  8528. * @returns {ReferenceNode}
  8529. */
  8530. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8531. /**
  8532. * TSL function for creating a reference node. Use this function if you want need a reference
  8533. * to an array-like property that should be represented as a uniform buffer.
  8534. *
  8535. * @tsl
  8536. * @function
  8537. * @param {string} name - The name of the property the node refers to.
  8538. * @param {string} type - The uniform type that should be used to represent the property value.
  8539. * @param {number} count - The number of value inside the array-like object.
  8540. * @param {Object} object - An array-like object the property belongs to.
  8541. * @returns {ReferenceNode}
  8542. */
  8543. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8544. /**
  8545. * This node is a special type of reference node which is intended
  8546. * for linking material properties with node values.
  8547. * ```js
  8548. * const opacityNode = materialReference( 'opacity', 'float', material );
  8549. * ```
  8550. * When changing `material.opacity`, the node value of `opacityNode` will
  8551. * automatically be updated.
  8552. *
  8553. * @augments ReferenceNode
  8554. */
  8555. class MaterialReferenceNode extends ReferenceNode {
  8556. static get type() {
  8557. return 'MaterialReferenceNode';
  8558. }
  8559. /**
  8560. * Constructs a new material reference node.
  8561. *
  8562. * @param {string} property - The name of the property the node refers to.
  8563. * @param {string} inputType - The uniform type that should be used to represent the property value.
  8564. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  8565. * the node refers to the material of the current rendered object.
  8566. */
  8567. constructor( property, inputType, material = null ) {
  8568. super( property, inputType, material );
  8569. /**
  8570. * The material the property belongs to. When no material is set,
  8571. * the node refers to the material of the current rendered object.
  8572. *
  8573. * @type {?Material}
  8574. * @default null
  8575. */
  8576. this.material = material;
  8577. /**
  8578. * This flag can be used for type testing.
  8579. *
  8580. * @type {boolean}
  8581. * @readonly
  8582. * @default true
  8583. */
  8584. this.isMaterialReferenceNode = true;
  8585. }
  8586. /**
  8587. * Updates the reference based on the given state. The state is only evaluated
  8588. * {@link MaterialReferenceNode#material} is not set.
  8589. *
  8590. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8591. * @return {Object} The updated reference.
  8592. */
  8593. updateReference( state ) {
  8594. this.reference = this.material !== null ? this.material : state.material;
  8595. return this.reference;
  8596. }
  8597. }
  8598. /**
  8599. * TSL function for creating a material reference node.
  8600. *
  8601. * @tsl
  8602. * @function
  8603. * @param {string} name - The name of the property the node refers to.
  8604. * @param {string} type - The uniform type that should be used to represent the property value.
  8605. * @param {?Material} [material=null] - The material the property belongs to.
  8606. * When no material is set, the node refers to the material of the current rendered object.
  8607. * @returns {MaterialReferenceNode}
  8608. */
  8609. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8610. /**
  8611. * TSL object that represents the tangent attribute of the current rendered object.
  8612. *
  8613. * @tsl
  8614. * @type {Node<vec4>}
  8615. */
  8616. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8617. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8618. builder.geometry.computeTangents();
  8619. }
  8620. return attribute( 'tangent', 'vec4' );
  8621. } )();
  8622. /**
  8623. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8624. *
  8625. * @tsl
  8626. * @type {Node<vec3>}
  8627. */
  8628. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8629. /**
  8630. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8631. *
  8632. * @tsl
  8633. * @type {Node<vec3>}
  8634. */
  8635. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8636. /**
  8637. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8638. *
  8639. * @tsl
  8640. * @type {Node<vec3>}
  8641. */
  8642. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8643. /**
  8644. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8645. *
  8646. * @tsl
  8647. * @type {Node<vec3>}
  8648. */
  8649. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8650. /**
  8651. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8652. *
  8653. * @tsl
  8654. * @type {Node<vec3>}
  8655. */
  8656. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8657. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8658. /**
  8659. * TSL object that represents the bitangent attribute of the current rendered object.
  8660. *
  8661. * @tsl
  8662. * @type {Node<vec3>}
  8663. */
  8664. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8665. /**
  8666. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8667. *
  8668. * @tsl
  8669. * @type {Node<vec3>}
  8670. */
  8671. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8672. /**
  8673. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8674. *
  8675. * @tsl
  8676. * @type {Node<vec4>}
  8677. */
  8678. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8679. /**
  8680. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8681. *
  8682. * @tsl
  8683. * @type {Node<vec4>}
  8684. */
  8685. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8686. /**
  8687. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8688. *
  8689. * @tsl
  8690. * @type {Node<vec4>}
  8691. */
  8692. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8693. /**
  8694. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8695. *
  8696. * @tsl
  8697. * @type {Node<vec4>}
  8698. */
  8699. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8700. /**
  8701. * TSL object that represents the TBN matrix in view space.
  8702. *
  8703. * @tsl
  8704. * @type {Node<mat3>}
  8705. */
  8706. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8707. /**
  8708. * TSL object that represents the parallax direction.
  8709. *
  8710. * @tsl
  8711. * @type {Node<mat3>}
  8712. */
  8713. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8714. /**
  8715. * TSL function for computing parallax uv coordinates.
  8716. *
  8717. * @tsl
  8718. * @function
  8719. * @param {Node<vec2>} uv - A uv node.
  8720. * @param {Node<vec2>} scale - A scale node.
  8721. * @returns {Node<vec2>} Parallax uv coordinates.
  8722. */
  8723. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8724. /**
  8725. * TSL function for computing bent normals.
  8726. *
  8727. * @tsl
  8728. * @function
  8729. * @returns {Node<vec3>} Bent normals.
  8730. */
  8731. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8732. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8733. let bentNormal = anisotropyB.cross( positionViewDirection );
  8734. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8735. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8736. return bentNormal;
  8737. } )();
  8738. // Normal Mapping Without Precomputed Tangents
  8739. // http://www.thetenthplanet.de/archives/1180
  8740. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8741. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8742. const q0 = eye_pos.dFdx();
  8743. const q1 = eye_pos.dFdy();
  8744. const st0 = uv.dFdx();
  8745. const st1 = uv.dFdy();
  8746. const N = surf_norm; // normalized
  8747. const q1perp = q1.cross( N );
  8748. const q0perp = N.cross( q0 );
  8749. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8750. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8751. const det = T.dot( T ).max( B.dot( B ) );
  8752. const scale = faceDirection.mul( det.inverseSqrt() );
  8753. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8754. } );
  8755. /**
  8756. * This class can be used for applying normals maps to materials.
  8757. *
  8758. * ```js
  8759. * material.normalNode = normalMap( texture( normalTex ) );
  8760. * ```
  8761. *
  8762. * @augments TempNode
  8763. */
  8764. class NormalMapNode extends TempNode {
  8765. static get type() {
  8766. return 'NormalMapNode';
  8767. }
  8768. /**
  8769. * Constructs a new normal map node.
  8770. *
  8771. * @param {Node<vec3>} node - Represents the normal map data.
  8772. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8773. */
  8774. constructor( node, scaleNode = null ) {
  8775. super( 'vec3' );
  8776. /**
  8777. * Represents the normal map data.
  8778. *
  8779. * @type {Node<vec3>}
  8780. */
  8781. this.node = node;
  8782. /**
  8783. * Controls the intensity of the effect.
  8784. *
  8785. * @type {?Node<vec2>}
  8786. * @default null
  8787. */
  8788. this.scaleNode = scaleNode;
  8789. /**
  8790. * The normal map type.
  8791. *
  8792. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8793. * @default TangentSpaceNormalMap
  8794. */
  8795. this.normalMapType = TangentSpaceNormalMap;
  8796. }
  8797. setup( builder ) {
  8798. const { normalMapType, scaleNode } = this;
  8799. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8800. if ( scaleNode !== null ) {
  8801. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8802. }
  8803. let outputNode = null;
  8804. if ( normalMapType === ObjectSpaceNormalMap ) {
  8805. outputNode = transformNormalToView( normalMap );
  8806. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8807. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8808. if ( tangent === true ) {
  8809. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8810. } else {
  8811. outputNode = perturbNormal2Arb( {
  8812. eye_pos: positionView,
  8813. surf_norm: normalView,
  8814. mapN: normalMap,
  8815. uv: uv()
  8816. } );
  8817. }
  8818. }
  8819. return outputNode;
  8820. }
  8821. }
  8822. /**
  8823. * TSL function for creating a normal map node.
  8824. *
  8825. * @tsl
  8826. * @function
  8827. * @param {Node<vec3>} node - Represents the normal map data.
  8828. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8829. * @returns {NormalMapNode}
  8830. */
  8831. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8832. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8833. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8834. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8835. // It's used to preserve the same TextureNode instance
  8836. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8837. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8838. return vec2(
  8839. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8840. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8841. ).mul( bumpScale );
  8842. } );
  8843. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8844. const perturbNormalArb = Fn( ( inputs ) => {
  8845. const { surf_pos, surf_norm, dHdxy } = inputs;
  8846. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8847. const vSigmaX = surf_pos.dFdx().normalize();
  8848. const vSigmaY = surf_pos.dFdy().normalize();
  8849. const vN = surf_norm; // normalized
  8850. const R1 = vSigmaY.cross( vN );
  8851. const R2 = vN.cross( vSigmaX );
  8852. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8853. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8854. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8855. } );
  8856. /**
  8857. * This class can be used for applying bump maps to materials.
  8858. *
  8859. * ```js
  8860. * material.normalNode = bumpMap( texture( bumpTex ) );
  8861. * ```
  8862. *
  8863. * @augments TempNode
  8864. */
  8865. class BumpMapNode extends TempNode {
  8866. static get type() {
  8867. return 'BumpMapNode';
  8868. }
  8869. /**
  8870. * Constructs a new bump map node.
  8871. *
  8872. * @param {Node<float>} textureNode - Represents the bump map data.
  8873. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  8874. */
  8875. constructor( textureNode, scaleNode = null ) {
  8876. super( 'vec3' );
  8877. /**
  8878. * Represents the bump map data.
  8879. *
  8880. * @type {Node<float>}
  8881. */
  8882. this.textureNode = textureNode;
  8883. /**
  8884. * Controls the intensity of the bump effect.
  8885. *
  8886. * @type {?Node<float>}
  8887. * @default null
  8888. */
  8889. this.scaleNode = scaleNode;
  8890. }
  8891. setup() {
  8892. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8893. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8894. return perturbNormalArb( {
  8895. surf_pos: positionView,
  8896. surf_norm: normalView,
  8897. dHdxy
  8898. } );
  8899. }
  8900. }
  8901. /**
  8902. * TSL function for creating a bump map node.
  8903. *
  8904. * @tsl
  8905. * @function
  8906. * @param {Node<float>} textureNode - Represents the bump map data.
  8907. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  8908. * @returns {BumpMapNode}
  8909. */
  8910. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8911. const _propertyCache = new Map();
  8912. /**
  8913. * This class should simplify the node access to material properties.
  8914. * It internal uses reference nodes to make sure changes to material
  8915. * properties are automatically reflected to predefined TSL objects
  8916. * like e.g. `materialColor`.
  8917. *
  8918. * @augments Node
  8919. */
  8920. class MaterialNode extends Node {
  8921. static get type() {
  8922. return 'MaterialNode';
  8923. }
  8924. /**
  8925. * Constructs a new material node.
  8926. *
  8927. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  8928. */
  8929. constructor( scope ) {
  8930. super();
  8931. /**
  8932. * The scope defines what material property is referred by the node.
  8933. *
  8934. * @type {string}
  8935. */
  8936. this.scope = scope;
  8937. }
  8938. /**
  8939. * Returns a cached reference node for the given property and type.
  8940. *
  8941. * @param {string} property - The name of the material property.
  8942. * @param {string} type - The uniform type of the property.
  8943. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8944. */
  8945. getCache( property, type ) {
  8946. let node = _propertyCache.get( property );
  8947. if ( node === undefined ) {
  8948. node = materialReference( property, type );
  8949. _propertyCache.set( property, node );
  8950. }
  8951. return node;
  8952. }
  8953. /**
  8954. * Returns a float-typed material reference node for the given property name.
  8955. *
  8956. * @param {string} property - The name of the material property.
  8957. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8958. */
  8959. getFloat( property ) {
  8960. return this.getCache( property, 'float' );
  8961. }
  8962. /**
  8963. * Returns a color-typed material reference node for the given property name.
  8964. *
  8965. * @param {string} property - The name of the material property.
  8966. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8967. */
  8968. getColor( property ) {
  8969. return this.getCache( property, 'color' );
  8970. }
  8971. /**
  8972. * Returns a texture-typed material reference node for the given property name.
  8973. *
  8974. * @param {string} property - The name of the material property.
  8975. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8976. */
  8977. getTexture( property ) {
  8978. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8979. }
  8980. /**
  8981. * The node setup is done depending on the selected scope. Multiple material properties
  8982. * might be grouped into a single node composition if they logically belong together.
  8983. *
  8984. * @param {NodeBuilder} builder - The current node builder.
  8985. * @return {Node} The node representing the selected scope.
  8986. */
  8987. setup( builder ) {
  8988. const material = builder.context.material;
  8989. const scope = this.scope;
  8990. let node = null;
  8991. if ( scope === MaterialNode.COLOR ) {
  8992. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8993. if ( material.map && material.map.isTexture === true ) {
  8994. node = colorNode.mul( this.getTexture( 'map' ) );
  8995. } else {
  8996. node = colorNode;
  8997. }
  8998. } else if ( scope === MaterialNode.OPACITY ) {
  8999. const opacityNode = this.getFloat( scope );
  9000. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9001. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9002. } else {
  9003. node = opacityNode;
  9004. }
  9005. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9006. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9007. node = this.getTexture( 'specular' ).r;
  9008. } else {
  9009. node = float( 1 );
  9010. }
  9011. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9012. const specularIntensityNode = this.getFloat( scope );
  9013. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9014. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9015. } else {
  9016. node = specularIntensityNode;
  9017. }
  9018. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9019. const specularColorNode = this.getColor( scope );
  9020. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9021. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9022. } else {
  9023. node = specularColorNode;
  9024. }
  9025. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9026. const roughnessNode = this.getFloat( scope );
  9027. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9028. node = roughnessNode.mul( this.getTexture( scope ).g );
  9029. } else {
  9030. node = roughnessNode;
  9031. }
  9032. } else if ( scope === MaterialNode.METALNESS ) {
  9033. const metalnessNode = this.getFloat( scope );
  9034. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9035. node = metalnessNode.mul( this.getTexture( scope ).b );
  9036. } else {
  9037. node = metalnessNode;
  9038. }
  9039. } else if ( scope === MaterialNode.EMISSIVE ) {
  9040. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9041. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9042. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9043. node = emissiveNode.mul( this.getTexture( scope ) );
  9044. } else {
  9045. node = emissiveNode;
  9046. }
  9047. } else if ( scope === MaterialNode.NORMAL ) {
  9048. if ( material.normalMap ) {
  9049. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9050. node.normalMapType = material.normalMapType;
  9051. } else if ( material.bumpMap ) {
  9052. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9053. } else {
  9054. node = normalView;
  9055. }
  9056. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9057. const clearcoatNode = this.getFloat( scope );
  9058. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9059. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9060. } else {
  9061. node = clearcoatNode;
  9062. }
  9063. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9064. const clearcoatRoughnessNode = this.getFloat( scope );
  9065. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9066. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9067. } else {
  9068. node = clearcoatRoughnessNode;
  9069. }
  9070. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9071. if ( material.clearcoatNormalMap ) {
  9072. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9073. } else {
  9074. node = normalView;
  9075. }
  9076. } else if ( scope === MaterialNode.SHEEN ) {
  9077. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9078. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9079. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9080. } else {
  9081. node = sheenNode;
  9082. }
  9083. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9084. const sheenRoughnessNode = this.getFloat( scope );
  9085. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9086. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9087. } else {
  9088. node = sheenRoughnessNode;
  9089. }
  9090. node = node.clamp( 0.07, 1.0 );
  9091. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9092. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9093. const anisotropyPolar = this.getTexture( scope );
  9094. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9095. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9096. } else {
  9097. node = materialAnisotropyVector;
  9098. }
  9099. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9100. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9101. if ( material.iridescenceThicknessMap ) {
  9102. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9103. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9104. } else {
  9105. node = iridescenceThicknessMaximum;
  9106. }
  9107. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9108. const transmissionNode = this.getFloat( scope );
  9109. if ( material.transmissionMap ) {
  9110. node = transmissionNode.mul( this.getTexture( scope ).r );
  9111. } else {
  9112. node = transmissionNode;
  9113. }
  9114. } else if ( scope === MaterialNode.THICKNESS ) {
  9115. const thicknessNode = this.getFloat( scope );
  9116. if ( material.thicknessMap ) {
  9117. node = thicknessNode.mul( this.getTexture( scope ).g );
  9118. } else {
  9119. node = thicknessNode;
  9120. }
  9121. } else if ( scope === MaterialNode.IOR ) {
  9122. node = this.getFloat( scope );
  9123. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9124. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9125. } else if ( scope === MaterialNode.AO ) {
  9126. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9127. } else {
  9128. const outputType = this.getNodeType( builder );
  9129. node = this.getCache( scope, outputType );
  9130. }
  9131. return node;
  9132. }
  9133. }
  9134. MaterialNode.ALPHA_TEST = 'alphaTest';
  9135. MaterialNode.COLOR = 'color';
  9136. MaterialNode.OPACITY = 'opacity';
  9137. MaterialNode.SHININESS = 'shininess';
  9138. MaterialNode.SPECULAR = 'specular';
  9139. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9140. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9141. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9142. MaterialNode.REFLECTIVITY = 'reflectivity';
  9143. MaterialNode.ROUGHNESS = 'roughness';
  9144. MaterialNode.METALNESS = 'metalness';
  9145. MaterialNode.NORMAL = 'normal';
  9146. MaterialNode.CLEARCOAT = 'clearcoat';
  9147. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9148. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9149. MaterialNode.EMISSIVE = 'emissive';
  9150. MaterialNode.ROTATION = 'rotation';
  9151. MaterialNode.SHEEN = 'sheen';
  9152. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9153. MaterialNode.ANISOTROPY = 'anisotropy';
  9154. MaterialNode.IRIDESCENCE = 'iridescence';
  9155. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9156. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9157. MaterialNode.IOR = 'ior';
  9158. MaterialNode.TRANSMISSION = 'transmission';
  9159. MaterialNode.THICKNESS = 'thickness';
  9160. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9161. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9162. MaterialNode.LINE_SCALE = 'scale';
  9163. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9164. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9165. MaterialNode.LINE_WIDTH = 'linewidth';
  9166. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9167. MaterialNode.POINT_SIZE = 'size';
  9168. MaterialNode.DISPERSION = 'dispersion';
  9169. MaterialNode.LIGHT_MAP = 'light';
  9170. MaterialNode.AO = 'ao';
  9171. /**
  9172. * TSL object that represents alpha test of the current material.
  9173. *
  9174. * @tsl
  9175. * @type {Node<float>}
  9176. */
  9177. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9178. /**
  9179. * TSL object that represents the diffuse color of the current material.
  9180. * The value is composed via `color` * `map`.
  9181. *
  9182. * @tsl
  9183. * @type {Node<vec3>}
  9184. */
  9185. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9186. /**
  9187. * TSL object that represents the shininess of the current material.
  9188. *
  9189. * @tsl
  9190. * @type {Node<float>}
  9191. */
  9192. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9193. /**
  9194. * TSL object that represents the emissive color of the current material.
  9195. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9196. *
  9197. * @tsl
  9198. * @type {Node<vec3>}
  9199. */
  9200. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9201. /**
  9202. * TSL object that represents the opacity of the current material.
  9203. * The value is composed via `opacity` * `alphaMap`.
  9204. *
  9205. * @tsl
  9206. * @type {Node<float>}
  9207. */
  9208. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9209. /**
  9210. * TSL object that represents the specular of the current material.
  9211. *
  9212. * @tsl
  9213. * @type {Node<vec3>}
  9214. */
  9215. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9216. /**
  9217. * TSL object that represents the specular intensity of the current material.
  9218. * The value is composed via `specularIntensity` * `specularMap.a`.
  9219. *
  9220. * @tsl
  9221. * @type {Node<float>}
  9222. */
  9223. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9224. /**
  9225. * TSL object that represents the specular color of the current material.
  9226. * The value is composed via `specularColor` * `specularMap.rgb`.
  9227. *
  9228. * @tsl
  9229. * @type {Node<vec3>}
  9230. */
  9231. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9232. /**
  9233. * TSL object that represents the specular strength of the current material.
  9234. * The value is composed via `specularMap.r`.
  9235. *
  9236. * @tsl
  9237. * @type {Node<float>}
  9238. */
  9239. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9240. /**
  9241. * TSL object that represents the reflectivity of the current material.
  9242. *
  9243. * @tsl
  9244. * @type {Node<float>}
  9245. */
  9246. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9247. /**
  9248. * TSL object that represents the roughness of the current material.
  9249. * The value is composed via `roughness` * `roughnessMap.g`.
  9250. *
  9251. * @tsl
  9252. * @type {Node<float>}
  9253. */
  9254. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9255. /**
  9256. * TSL object that represents the metalness of the current material.
  9257. * The value is composed via `metalness` * `metalnessMap.b`.
  9258. *
  9259. * @tsl
  9260. * @type {Node<float>}
  9261. */
  9262. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9263. /**
  9264. * TSL object that represents the normal of the current material.
  9265. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9266. *
  9267. * @tsl
  9268. * @type {Node<vec3>}
  9269. */
  9270. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9271. /**
  9272. * TSL object that represents the clearcoat of the current material.
  9273. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9274. *
  9275. * @tsl
  9276. * @type {Node<float>}
  9277. */
  9278. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9279. /**
  9280. * TSL object that represents the clearcoat roughness of the current material.
  9281. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9282. *
  9283. * @tsl
  9284. * @type {Node<float>}
  9285. */
  9286. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9287. /**
  9288. * TSL object that represents the clearcoat normal of the current material.
  9289. * The value will be either `clearcoatNormalMap` or `normalView`.
  9290. *
  9291. * @tsl
  9292. * @type {Node<vec3>}
  9293. */
  9294. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9295. /**
  9296. * TSL object that represents the rotation of the current sprite material.
  9297. *
  9298. * @tsl
  9299. * @type {Node<float>}
  9300. */
  9301. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9302. /**
  9303. * TSL object that represents the sheen color of the current material.
  9304. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9305. *
  9306. * @tsl
  9307. * @type {Node<vec3>}
  9308. */
  9309. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9310. /**
  9311. * TSL object that represents the sheen roughness of the current material.
  9312. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9313. *
  9314. * @tsl
  9315. * @type {Node<float>}
  9316. */
  9317. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9318. /**
  9319. * TSL object that represents the anisotropy of the current material.
  9320. *
  9321. * @tsl
  9322. * @type {Node<vec2>}
  9323. */
  9324. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9325. /**
  9326. * TSL object that represents the iridescence of the current material.
  9327. *
  9328. * @tsl
  9329. * @type {Node<float>}
  9330. */
  9331. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9332. /**
  9333. * TSL object that represents the iridescence IOR of the current material.
  9334. *
  9335. * @tsl
  9336. * @type {Node<float>}
  9337. */
  9338. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9339. /**
  9340. * TSL object that represents the iridescence thickness of the current material.
  9341. *
  9342. * @tsl
  9343. * @type {Node<float>}
  9344. */
  9345. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9346. /**
  9347. * TSL object that represents the transmission of the current material.
  9348. * The value is composed via `transmission` * `transmissionMap.r`.
  9349. *
  9350. * @tsl
  9351. * @type {Node<float>}
  9352. */
  9353. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9354. /**
  9355. * TSL object that represents the thickness of the current material.
  9356. * The value is composed via `thickness` * `thicknessMap.g`.
  9357. *
  9358. * @tsl
  9359. * @type {Node<float>}
  9360. */
  9361. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9362. /**
  9363. * TSL object that represents the IOR of the current material.
  9364. *
  9365. * @tsl
  9366. * @type {Node<float>}
  9367. */
  9368. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9369. /**
  9370. * TSL object that represents the attenuation distance of the current material.
  9371. *
  9372. * @tsl
  9373. * @type {Node<float>}
  9374. */
  9375. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9376. /**
  9377. * TSL object that represents the attenuation color of the current material.
  9378. *
  9379. * @tsl
  9380. * @type {Node<vec3>}
  9381. */
  9382. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9383. /**
  9384. * TSL object that represents the scale of the current dashed line material.
  9385. *
  9386. * @tsl
  9387. * @type {Node<float>}
  9388. */
  9389. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9390. /**
  9391. * TSL object that represents the dash size of the current dashed line material.
  9392. *
  9393. * @tsl
  9394. * @type {Node<float>}
  9395. */
  9396. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9397. /**
  9398. * TSL object that represents the gap size of the current dashed line material.
  9399. *
  9400. * @tsl
  9401. * @type {Node<float>}
  9402. */
  9403. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9404. /**
  9405. * TSL object that represents the line width of the current line material.
  9406. *
  9407. * @tsl
  9408. * @type {Node<float>}
  9409. */
  9410. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9411. /**
  9412. * TSL object that represents the dash offset of the current line material.
  9413. *
  9414. * @tsl
  9415. * @type {Node<float>}
  9416. */
  9417. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9418. /**
  9419. * TSL object that represents the point size of the current points material.
  9420. *
  9421. * @tsl
  9422. * @type {Node<float>}
  9423. */
  9424. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9425. /**
  9426. * TSL object that represents the dispersion of the current material.
  9427. *
  9428. * @tsl
  9429. * @type {Node<float>}
  9430. */
  9431. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9432. /**
  9433. * TSL object that represents the light map of the current material.
  9434. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9435. *
  9436. * @tsl
  9437. * @type {Node<vec3>}
  9438. */
  9439. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9440. /**
  9441. * TSL object that represents the ambient occlusion map of the current material.
  9442. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9443. *
  9444. * @tsl
  9445. * @type {Node<float>}
  9446. */
  9447. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9448. /**
  9449. * TSL object that represents the anisotropy vector of the current material.
  9450. *
  9451. * @tsl
  9452. * @type {Node<vec2>}
  9453. */
  9454. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9455. return frame.material;
  9456. } ).onRenderUpdate( function ( { material } ) {
  9457. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9458. } );
  9459. /**
  9460. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9461. *
  9462. * @tsl
  9463. * @type {VaryingNode<vec4>}
  9464. */
  9465. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9466. return builder.context.setupModelViewProjection();
  9467. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9468. /**
  9469. * This class represents shader indices of different types. The following predefined node
  9470. * objects cover frequent use cases:
  9471. *
  9472. * - `vertexIndex`: The index of a vertex within a mesh.
  9473. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9474. * - `drawIndex`: The index of a draw call.
  9475. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9476. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9477. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9478. *
  9479. * @augments Node
  9480. */
  9481. class IndexNode extends Node {
  9482. static get type() {
  9483. return 'IndexNode';
  9484. }
  9485. /**
  9486. * Constructs a new index node.
  9487. *
  9488. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9489. */
  9490. constructor( scope ) {
  9491. super( 'uint' );
  9492. /**
  9493. * The scope of the index node.
  9494. *
  9495. * @type {string}
  9496. */
  9497. this.scope = scope;
  9498. /**
  9499. * This flag can be used for type testing.
  9500. *
  9501. * @type {boolean}
  9502. * @readonly
  9503. * @default true
  9504. */
  9505. this.isIndexNode = true;
  9506. }
  9507. generate( builder ) {
  9508. const nodeType = this.getNodeType( builder );
  9509. const scope = this.scope;
  9510. let propertyName;
  9511. if ( scope === IndexNode.VERTEX ) {
  9512. propertyName = builder.getVertexIndex();
  9513. } else if ( scope === IndexNode.INSTANCE ) {
  9514. propertyName = builder.getInstanceIndex();
  9515. } else if ( scope === IndexNode.DRAW ) {
  9516. propertyName = builder.getDrawIndex();
  9517. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9518. propertyName = builder.getInvocationLocalIndex();
  9519. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9520. propertyName = builder.getInvocationSubgroupIndex();
  9521. } else if ( scope === IndexNode.SUBGROUP ) {
  9522. propertyName = builder.getSubgroupIndex();
  9523. } else {
  9524. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9525. }
  9526. let output;
  9527. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9528. output = propertyName;
  9529. } else {
  9530. const nodeVarying = varying( this );
  9531. output = nodeVarying.build( builder, nodeType );
  9532. }
  9533. return output;
  9534. }
  9535. }
  9536. IndexNode.VERTEX = 'vertex';
  9537. IndexNode.INSTANCE = 'instance';
  9538. IndexNode.SUBGROUP = 'subgroup';
  9539. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9540. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9541. IndexNode.DRAW = 'draw';
  9542. /**
  9543. * TSL object that represents the index of a vertex within a mesh.
  9544. *
  9545. * @tsl
  9546. * @type {IndexNode}
  9547. */
  9548. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9549. /**
  9550. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9551. *
  9552. * @tsl
  9553. * @type {IndexNode}
  9554. */
  9555. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9556. /**
  9557. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9558. *
  9559. * @tsl
  9560. * @type {IndexNode}
  9561. */
  9562. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9563. /**
  9564. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9565. *
  9566. * @tsl
  9567. * @type {IndexNode}
  9568. */
  9569. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9570. /**
  9571. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9572. *
  9573. * @tsl
  9574. * @type {IndexNode}
  9575. */
  9576. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9577. /**
  9578. * TSL object that represents the index of a draw call.
  9579. *
  9580. * @tsl
  9581. * @type {IndexNode}
  9582. */
  9583. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9584. /**
  9585. * This node implements the vertex shader logic which is required
  9586. * when rendering 3D objects via instancing. The code makes sure
  9587. * vertex positions, normals and colors can be modified via instanced
  9588. * data.
  9589. *
  9590. * @augments Node
  9591. */
  9592. class InstanceNode extends Node {
  9593. static get type() {
  9594. return 'InstanceNode';
  9595. }
  9596. /**
  9597. * Constructs a new instance node.
  9598. *
  9599. * @param {number} count - The number of instances.
  9600. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9601. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9602. */
  9603. constructor( count, instanceMatrix, instanceColor ) {
  9604. super( 'void' );
  9605. /**
  9606. * The number of instances.
  9607. *
  9608. * @type {number}
  9609. */
  9610. this.count = count;
  9611. /**
  9612. * Instanced buffer attribute representing the transformation of instances.
  9613. *
  9614. * @type {InstancedBufferAttribute}
  9615. */
  9616. this.instanceMatrix = instanceMatrix;
  9617. /**
  9618. * Instanced buffer attribute representing the color of instances.
  9619. *
  9620. * @type {InstancedBufferAttribute}
  9621. */
  9622. this.instanceColor = instanceColor;
  9623. /**
  9624. * The node that represents the instance matrix data.
  9625. *
  9626. * @type {Node}
  9627. */
  9628. this.instanceMatrixNode = null;
  9629. /**
  9630. * The node that represents the instance color data.
  9631. *
  9632. * @type {Node}
  9633. */
  9634. this.instanceColorNode = null;
  9635. /**
  9636. * The update type is set to `frame` since an update
  9637. * of instanced buffer data must be checked per frame.
  9638. *
  9639. * @type {string}
  9640. * @default 'frame'
  9641. */
  9642. this.updateType = NodeUpdateType.FRAME;
  9643. /**
  9644. * A reference to a buffer that is used by `instanceMatrixNode`.
  9645. *
  9646. * @type {InstancedInterleavedBuffer}
  9647. */
  9648. this.buffer = null;
  9649. /**
  9650. * A reference to a buffer that is used by `instanceColorNode`.
  9651. *
  9652. * @type {InstancedBufferAttribute}
  9653. */
  9654. this.bufferColor = null;
  9655. }
  9656. /**
  9657. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9658. * to predefined node variables for accumulation. That follows the same patterns
  9659. * like with morph and skinning nodes.
  9660. *
  9661. * @param {NodeBuilder} builder - The current node builder.
  9662. */
  9663. setup( builder ) {
  9664. const { count, instanceMatrix, instanceColor } = this;
  9665. let { instanceMatrixNode, instanceColorNode } = this;
  9666. if ( instanceMatrixNode === null ) {
  9667. // 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.
  9668. if ( count <= 1000 ) {
  9669. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9670. } else {
  9671. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9672. this.buffer = buffer;
  9673. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9674. const instanceBuffers = [
  9675. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9676. bufferFn( buffer, 'vec4', 16, 0 ),
  9677. bufferFn( buffer, 'vec4', 16, 4 ),
  9678. bufferFn( buffer, 'vec4', 16, 8 ),
  9679. bufferFn( buffer, 'vec4', 16, 12 )
  9680. ];
  9681. instanceMatrixNode = mat4( ...instanceBuffers );
  9682. }
  9683. this.instanceMatrixNode = instanceMatrixNode;
  9684. }
  9685. if ( instanceColor && instanceColorNode === null ) {
  9686. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9687. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9688. this.bufferColor = buffer;
  9689. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9690. this.instanceColorNode = instanceColorNode;
  9691. }
  9692. // POSITION
  9693. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9694. positionLocal.assign( instancePosition );
  9695. // NORMAL
  9696. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9697. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9698. // ASSIGNS
  9699. normalLocal.assign( instanceNormal );
  9700. }
  9701. // COLOR
  9702. if ( this.instanceColorNode !== null ) {
  9703. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9704. }
  9705. }
  9706. /**
  9707. * Checks if the internal buffers required an update.
  9708. *
  9709. * @param {NodeFrame} frame - The current node frame.
  9710. */
  9711. update( /*frame*/ ) {
  9712. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9713. this.buffer.version = this.instanceMatrix.version;
  9714. }
  9715. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9716. this.bufferColor.version = this.instanceColor.version;
  9717. }
  9718. }
  9719. }
  9720. /**
  9721. * TSL function for creating an instance node.
  9722. *
  9723. * @tsl
  9724. * @function
  9725. * @param {number} count - The number of instances.
  9726. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9727. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9728. * @returns {InstanceNode}
  9729. */
  9730. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9731. /**
  9732. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9733. * It allows an easier setup of the instance node.
  9734. *
  9735. * @augments InstanceNode
  9736. */
  9737. class InstancedMeshNode extends InstanceNode {
  9738. static get type() {
  9739. return 'InstancedMeshNode';
  9740. }
  9741. /**
  9742. * Constructs a new instanced mesh node.
  9743. *
  9744. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9745. */
  9746. constructor( instancedMesh ) {
  9747. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9748. super( count, instanceMatrix, instanceColor );
  9749. /**
  9750. * A reference to the instanced mesh.
  9751. *
  9752. * @type {InstancedMesh}
  9753. */
  9754. this.instancedMesh = instancedMesh;
  9755. }
  9756. }
  9757. /**
  9758. * TSL function for creating an instanced mesh node.
  9759. *
  9760. * @tsl
  9761. * @function
  9762. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9763. * @returns {InstancedMeshNode}
  9764. */
  9765. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9766. /**
  9767. * This node implements the vertex shader logic which is required
  9768. * when rendering 3D objects via batching. `BatchNode` must be used
  9769. * with instances of {@link BatchedMesh}.
  9770. *
  9771. * @augments Node
  9772. */
  9773. class BatchNode extends Node {
  9774. static get type() {
  9775. return 'BatchNode';
  9776. }
  9777. /**
  9778. * Constructs a new batch node.
  9779. *
  9780. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9781. */
  9782. constructor( batchMesh ) {
  9783. super( 'void' );
  9784. /**
  9785. * A reference to batched mesh.
  9786. *
  9787. * @type {BatchedMesh}
  9788. */
  9789. this.batchMesh = batchMesh;
  9790. /**
  9791. * The batching index node.
  9792. *
  9793. * @type {?IndexNode}
  9794. * @default null
  9795. */
  9796. this.batchingIdNode = null;
  9797. }
  9798. /**
  9799. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9800. * to predefined node variables for accumulation. That follows the same patterns
  9801. * like with morph and skinning nodes.
  9802. *
  9803. * @param {NodeBuilder} builder - The current node builder.
  9804. */
  9805. setup( builder ) {
  9806. if ( this.batchingIdNode === null ) {
  9807. if ( builder.getDrawIndex() === null ) {
  9808. this.batchingIdNode = instanceIndex;
  9809. } else {
  9810. this.batchingIdNode = drawIndex;
  9811. }
  9812. }
  9813. const getIndirectIndex = Fn( ( [ id ] ) => {
  9814. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ) );
  9815. const x = int( id ).modInt( size );
  9816. const y = int( id ).div( size );
  9817. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9818. } ).setLayout( {
  9819. name: 'getIndirectIndex',
  9820. type: 'uint',
  9821. inputs: [
  9822. { name: 'id', type: 'int' }
  9823. ]
  9824. } );
  9825. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9826. const matricesTexture = this.batchMesh._matricesTexture;
  9827. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9828. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9829. const x = j.modInt( size );
  9830. const y = j.div( int( size ) );
  9831. const batchingMatrix = mat4(
  9832. textureLoad( matricesTexture, ivec2( x, y ) ),
  9833. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9834. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9835. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9836. );
  9837. const colorsTexture = this.batchMesh._colorsTexture;
  9838. if ( colorsTexture !== null ) {
  9839. const getBatchingColor = Fn( ( [ id ] ) => {
  9840. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9841. const j = id;
  9842. const x = j.modInt( size );
  9843. const y = j.div( size );
  9844. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9845. } ).setLayout( {
  9846. name: 'getBatchingColor',
  9847. type: 'vec3',
  9848. inputs: [
  9849. { name: 'id', type: 'int' }
  9850. ]
  9851. } );
  9852. const color = getBatchingColor( indirectId );
  9853. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9854. }
  9855. const bm = mat3( batchingMatrix );
  9856. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9857. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9858. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9859. normalLocal.assign( batchingNormal );
  9860. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9861. tangentLocal.mulAssign( bm );
  9862. }
  9863. }
  9864. }
  9865. /**
  9866. * TSL function for creating a batch node.
  9867. *
  9868. * @tsl
  9869. * @function
  9870. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9871. * @returns {BatchNode}
  9872. */
  9873. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9874. const _frameId = new WeakMap();
  9875. /**
  9876. * This node implements the vertex transformation shader logic which is required
  9877. * for skinning/skeletal animation.
  9878. *
  9879. * @augments Node
  9880. */
  9881. class SkinningNode extends Node {
  9882. static get type() {
  9883. return 'SkinningNode';
  9884. }
  9885. /**
  9886. * Constructs a new skinning node.
  9887. *
  9888. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9889. * @param {boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9890. */
  9891. constructor( skinnedMesh, useReference = false ) {
  9892. super( 'void' );
  9893. /**
  9894. * The skinned mesh.
  9895. *
  9896. * @type {SkinnedMesh}
  9897. */
  9898. this.skinnedMesh = skinnedMesh;
  9899. /**
  9900. * Whether to use reference nodes for internal skinned mesh related data or not.
  9901. * TODO: Explain the purpose of the property.
  9902. *
  9903. * @type {boolean}
  9904. */
  9905. this.useReference = useReference;
  9906. /**
  9907. * The update type overwritten since skinning nodes are updated per object.
  9908. *
  9909. * @type {string}
  9910. */
  9911. this.updateType = NodeUpdateType.OBJECT;
  9912. //
  9913. /**
  9914. * The skin index attribute.
  9915. *
  9916. * @type {AttributeNode}
  9917. */
  9918. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9919. /**
  9920. * The skin weight attribute.
  9921. *
  9922. * @type {AttributeNode}
  9923. */
  9924. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9925. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9926. if ( useReference ) {
  9927. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9928. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9929. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9930. } else {
  9931. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9932. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9933. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9934. }
  9935. /**
  9936. * The bind matrix node.
  9937. *
  9938. * @type {Node<mat4>}
  9939. */
  9940. this.bindMatrixNode = bindMatrixNode;
  9941. /**
  9942. * The bind matrix inverse node.
  9943. *
  9944. * @type {Node<mat4>}
  9945. */
  9946. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9947. /**
  9948. * The bind matrices as a uniform buffer node.
  9949. *
  9950. * @type {Node}
  9951. */
  9952. this.boneMatricesNode = boneMatricesNode;
  9953. /**
  9954. * The previous bind matrices as a uniform buffer node.
  9955. * Required for computing motion vectors.
  9956. *
  9957. * @type {?Node}
  9958. * @default null
  9959. */
  9960. this.previousBoneMatricesNode = null;
  9961. }
  9962. /**
  9963. * Transforms the given vertex position via skinning.
  9964. *
  9965. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9966. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9967. * @return {Node<vec3>} The transformed vertex position.
  9968. */
  9969. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9970. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9971. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9972. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9973. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9974. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9975. // POSITION
  9976. const skinVertex = bindMatrixNode.mul( position );
  9977. const skinned = add(
  9978. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9979. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9980. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9981. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9982. );
  9983. return bindMatrixInverseNode.mul( skinned ).xyz;
  9984. }
  9985. /**
  9986. * Transforms the given vertex normal via skinning.
  9987. *
  9988. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9989. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9990. * @return {Node<vec3>} The transformed vertex normal.
  9991. */
  9992. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9993. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9994. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9995. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9996. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9997. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9998. // NORMAL
  9999. let skinMatrix = add(
  10000. skinWeightNode.x.mul( boneMatX ),
  10001. skinWeightNode.y.mul( boneMatY ),
  10002. skinWeightNode.z.mul( boneMatZ ),
  10003. skinWeightNode.w.mul( boneMatW )
  10004. );
  10005. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  10006. return skinMatrix.transformDirection( normal ).xyz;
  10007. }
  10008. /**
  10009. * Transforms the given vertex normal via skinning.
  10010. *
  10011. * @param {NodeBuilder} builder - The current node builder.
  10012. * @return {Node<vec3>} The skinned position from the previous frame.
  10013. */
  10014. getPreviousSkinnedPosition( builder ) {
  10015. const skinnedMesh = builder.object;
  10016. if ( this.previousBoneMatricesNode === null ) {
  10017. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  10018. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10019. }
  10020. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  10021. }
  10022. /**
  10023. * Returns `true` if bone matrices from the previous frame are required.
  10024. *
  10025. * @param {NodeBuilder} builder - The current node builder.
  10026. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  10027. */
  10028. needsPreviousBoneMatrices( builder ) {
  10029. const mrt = builder.renderer.getMRT();
  10030. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  10031. }
  10032. /**
  10033. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  10034. *
  10035. * @param {NodeBuilder} builder - The current node builder.
  10036. */
  10037. setup( builder ) {
  10038. if ( this.needsPreviousBoneMatrices( builder ) ) {
  10039. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  10040. }
  10041. const skinPosition = this.getSkinnedPosition();
  10042. positionLocal.assign( skinPosition );
  10043. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10044. const skinNormal = this.getSkinnedNormal();
  10045. normalLocal.assign( skinNormal );
  10046. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10047. tangentLocal.assign( skinNormal );
  10048. }
  10049. }
  10050. }
  10051. /**
  10052. * Generates the code snippet of the skinning node.
  10053. *
  10054. * @param {NodeBuilder} builder - The current node builder.
  10055. * @param {string} output - The current output.
  10056. * @return {string} The generated code snippet.
  10057. */
  10058. generate( builder, output ) {
  10059. if ( output !== 'void' ) {
  10060. return positionLocal.build( builder, output );
  10061. }
  10062. }
  10063. /**
  10064. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  10065. *
  10066. * @param {NodeFrame} frame - The current node frame.
  10067. */
  10068. update( frame ) {
  10069. const object = this.useReference ? frame.object : this.skinnedMesh;
  10070. const skeleton = object.skeleton;
  10071. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  10072. _frameId.set( skeleton, frame.frameId );
  10073. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  10074. skeleton.update();
  10075. }
  10076. }
  10077. /**
  10078. * TSL function for creating a skinning node.
  10079. *
  10080. * @tsl
  10081. * @function
  10082. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10083. * @returns {SkinningNode}
  10084. */
  10085. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  10086. /**
  10087. * TSL function for creating a skinning node with reference usage.
  10088. *
  10089. * @tsl
  10090. * @function
  10091. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10092. * @returns {SkinningNode}
  10093. */
  10094. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  10095. /**
  10096. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  10097. * ```js
  10098. * Loop( count, ( { i } ) => {
  10099. *
  10100. * } );
  10101. * ```
  10102. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  10103. * ```js
  10104. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  10105. *
  10106. * } );
  10107. *```
  10108. * Nested loops can be defined in a compacted form:
  10109. * ```js
  10110. * Loop( 10, 5, ( { i, j } ) => {
  10111. *
  10112. * } );
  10113. * ```
  10114. * Loops that should run backwards can be defined like so:
  10115. * ```js
  10116. * Loop( { start: 10 }, () => {} );
  10117. * ```
  10118. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  10119. * @augments Node
  10120. */
  10121. class LoopNode extends Node {
  10122. static get type() {
  10123. return 'LoopNode';
  10124. }
  10125. /**
  10126. * Constructs a new loop node.
  10127. *
  10128. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  10129. */
  10130. constructor( params = [] ) {
  10131. super();
  10132. this.params = params;
  10133. }
  10134. /**
  10135. * Returns a loop variable name based on an index. The pattern is
  10136. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  10137. *
  10138. * @param {number} index - The index.
  10139. * @return {string} The loop variable name.
  10140. */
  10141. getVarName( index ) {
  10142. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  10143. }
  10144. /**
  10145. * Returns properties about this node.
  10146. *
  10147. * @param {NodeBuilder} builder - The current node builder.
  10148. * @return {Object} The node properties.
  10149. */
  10150. getProperties( builder ) {
  10151. const properties = builder.getNodeProperties( this );
  10152. if ( properties.stackNode !== undefined ) return properties;
  10153. //
  10154. const inputs = {};
  10155. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10156. const param = this.params[ i ];
  10157. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  10158. const type = ( param.isNode !== true && param.type ) || 'int';
  10159. inputs[ name ] = expression( name, type );
  10160. }
  10161. const stack = builder.addStack(); // TODO: cache() it
  10162. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  10163. properties.stackNode = stack;
  10164. builder.removeStack();
  10165. return properties;
  10166. }
  10167. /**
  10168. * This method is overwritten since the node type is inferred based on the loop configuration.
  10169. *
  10170. * @param {NodeBuilder} builder - The current node builder.
  10171. * @return {string} The node type.
  10172. */
  10173. getNodeType( builder ) {
  10174. const { returnsNode } = this.getProperties( builder );
  10175. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  10176. }
  10177. setup( builder ) {
  10178. // setup properties
  10179. this.getProperties( builder );
  10180. }
  10181. generate( builder ) {
  10182. const properties = this.getProperties( builder );
  10183. const params = this.params;
  10184. const stackNode = properties.stackNode;
  10185. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  10186. const param = params[ i ];
  10187. let start = null, end = null, name = null, type = null, condition = null, update = null;
  10188. if ( param.isNode ) {
  10189. type = 'int';
  10190. name = this.getVarName( i );
  10191. start = '0';
  10192. end = param.build( builder, type );
  10193. condition = '<';
  10194. } else {
  10195. type = param.type || 'int';
  10196. name = param.name || this.getVarName( i );
  10197. start = param.start;
  10198. end = param.end;
  10199. condition = param.condition;
  10200. update = param.update;
  10201. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  10202. else if ( start && start.isNode ) start = start.build( builder, type );
  10203. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  10204. else if ( end && end.isNode ) end = end.build( builder, type );
  10205. if ( start !== undefined && end === undefined ) {
  10206. start = start + ' - 1';
  10207. end = '0';
  10208. condition = '>=';
  10209. } else if ( end !== undefined && start === undefined ) {
  10210. start = '0';
  10211. condition = '<';
  10212. }
  10213. if ( condition === undefined ) {
  10214. if ( Number( start ) > Number( end ) ) {
  10215. condition = '>=';
  10216. } else {
  10217. condition = '<';
  10218. }
  10219. }
  10220. }
  10221. const internalParam = { start, end};
  10222. //
  10223. const startSnippet = internalParam.start;
  10224. const endSnippet = internalParam.end;
  10225. let declarationSnippet = '';
  10226. let conditionalSnippet = '';
  10227. let updateSnippet = '';
  10228. if ( ! update ) {
  10229. if ( type === 'int' || type === 'uint' ) {
  10230. if ( condition.includes( '<' ) ) update = '++';
  10231. else update = '--';
  10232. } else {
  10233. if ( condition.includes( '<' ) ) update = '+= 1.';
  10234. else update = '-= 1.';
  10235. }
  10236. }
  10237. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  10238. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  10239. updateSnippet += name + ' ' + update;
  10240. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  10241. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  10242. }
  10243. const stackSnippet = stackNode.build( builder, 'void' );
  10244. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  10245. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  10246. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10247. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  10248. }
  10249. builder.addFlowTab();
  10250. return returnsSnippet;
  10251. }
  10252. }
  10253. /**
  10254. * TSL function for creating a loop node.
  10255. *
  10256. * @tsl
  10257. * @function
  10258. * @param {...any} params - A list of parameters.
  10259. * @returns {LoopNode}
  10260. */
  10261. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  10262. /**
  10263. * TSL function for creating a `Continue()` expression.
  10264. *
  10265. * @tsl
  10266. * @function
  10267. * @returns {ExpressionNode}
  10268. */
  10269. const Continue = () => expression( 'continue' ).append();
  10270. /**
  10271. * TSL function for creating a `Break()` expression.
  10272. *
  10273. * @tsl
  10274. * @function
  10275. * @returns {ExpressionNode}
  10276. */
  10277. const Break = () => expression( 'break' ).append();
  10278. // Deprecated
  10279. /**
  10280. * @tsl
  10281. * @function
  10282. * @deprecated since r168. Use {@link Loop} instead.
  10283. *
  10284. * @param {...any} params
  10285. * @returns {LoopNode}
  10286. */
  10287. const loop = ( ...params ) => { // @deprecated, r168
  10288. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  10289. return Loop( ...params );
  10290. };
  10291. const _morphTextures = /*@__PURE__*/ new WeakMap();
  10292. const _morphVec4 = /*@__PURE__*/ new Vector4();
  10293. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  10294. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  10295. const y = texelIndex.div( width );
  10296. const x = texelIndex.sub( y.mul( width ) );
  10297. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  10298. return bufferAttrib.mul( influence );
  10299. } );
  10300. function getEntry( geometry ) {
  10301. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10302. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10303. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10304. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10305. // into an array of data textures. Each layer represents a single morph target.
  10306. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10307. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10308. let entry = _morphTextures.get( geometry );
  10309. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10310. if ( entry !== undefined ) entry.texture.dispose();
  10311. const morphTargets = geometry.morphAttributes.position || [];
  10312. const morphNormals = geometry.morphAttributes.normal || [];
  10313. const morphColors = geometry.morphAttributes.color || [];
  10314. let vertexDataCount = 0;
  10315. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10316. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10317. if ( hasMorphColors === true ) vertexDataCount = 3;
  10318. let width = geometry.attributes.position.count * vertexDataCount;
  10319. let height = 1;
  10320. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  10321. if ( width > maxTextureSize ) {
  10322. height = Math.ceil( width / maxTextureSize );
  10323. width = maxTextureSize;
  10324. }
  10325. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10326. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10327. bufferTexture.type = FloatType;
  10328. bufferTexture.needsUpdate = true;
  10329. // fill buffer
  10330. const vertexDataStride = vertexDataCount * 4;
  10331. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10332. const morphTarget = morphTargets[ i ];
  10333. const morphNormal = morphNormals[ i ];
  10334. const morphColor = morphColors[ i ];
  10335. const offset = width * height * 4 * i;
  10336. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10337. const stride = j * vertexDataStride;
  10338. if ( hasMorphPosition === true ) {
  10339. _morphVec4.fromBufferAttribute( morphTarget, j );
  10340. buffer[ offset + stride + 0 ] = _morphVec4.x;
  10341. buffer[ offset + stride + 1 ] = _morphVec4.y;
  10342. buffer[ offset + stride + 2 ] = _morphVec4.z;
  10343. buffer[ offset + stride + 3 ] = 0;
  10344. }
  10345. if ( hasMorphNormals === true ) {
  10346. _morphVec4.fromBufferAttribute( morphNormal, j );
  10347. buffer[ offset + stride + 4 ] = _morphVec4.x;
  10348. buffer[ offset + stride + 5 ] = _morphVec4.y;
  10349. buffer[ offset + stride + 6 ] = _morphVec4.z;
  10350. buffer[ offset + stride + 7 ] = 0;
  10351. }
  10352. if ( hasMorphColors === true ) {
  10353. _morphVec4.fromBufferAttribute( morphColor, j );
  10354. buffer[ offset + stride + 8 ] = _morphVec4.x;
  10355. buffer[ offset + stride + 9 ] = _morphVec4.y;
  10356. buffer[ offset + stride + 10 ] = _morphVec4.z;
  10357. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  10358. }
  10359. }
  10360. }
  10361. entry = {
  10362. count: morphTargetsCount,
  10363. texture: bufferTexture,
  10364. stride: vertexDataCount,
  10365. size: new Vector2( width, height )
  10366. };
  10367. _morphTextures.set( geometry, entry );
  10368. function disposeTexture() {
  10369. bufferTexture.dispose();
  10370. _morphTextures.delete( geometry );
  10371. geometry.removeEventListener( 'dispose', disposeTexture );
  10372. }
  10373. geometry.addEventListener( 'dispose', disposeTexture );
  10374. }
  10375. return entry;
  10376. }
  10377. /**
  10378. * This node implements the vertex transformation shader logic which is required
  10379. * for morph target animation.
  10380. *
  10381. * @augments Node
  10382. */
  10383. class MorphNode extends Node {
  10384. static get type() {
  10385. return 'MorphNode';
  10386. }
  10387. /**
  10388. * Constructs a new morph node.
  10389. *
  10390. * @param {Mesh} mesh - The mesh holding the morph targets.
  10391. */
  10392. constructor( mesh ) {
  10393. super( 'void' );
  10394. /**
  10395. * The mesh holding the morph targets.
  10396. *
  10397. * @type {Mesh}
  10398. */
  10399. this.mesh = mesh;
  10400. /**
  10401. * A uniform node which represents the morph base influence value.
  10402. *
  10403. * @type {UniformNode<float>}
  10404. */
  10405. this.morphBaseInfluence = uniform( 1 );
  10406. /**
  10407. * The update type overwritten since morph nodes are updated per object.
  10408. *
  10409. * @type {string}
  10410. */
  10411. this.updateType = NodeUpdateType.OBJECT;
  10412. }
  10413. /**
  10414. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  10415. *
  10416. * @param {NodeBuilder} builder - The current node builder.
  10417. */
  10418. setup( builder ) {
  10419. const { geometry } = builder;
  10420. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10421. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  10422. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10423. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10424. // nodes
  10425. const { texture: bufferMap, stride, size } = getEntry( geometry );
  10426. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  10427. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  10428. const width = int( size.width );
  10429. Loop( morphTargetsCount, ( { i } ) => {
  10430. const influence = float( 0 ).toVar();
  10431. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10432. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10433. } else {
  10434. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10435. }
  10436. if ( hasMorphPosition === true ) {
  10437. positionLocal.addAssign( getMorph( {
  10438. bufferMap,
  10439. influence,
  10440. stride,
  10441. width,
  10442. depth: i,
  10443. offset: int( 0 )
  10444. } ) );
  10445. }
  10446. if ( hasMorphNormals === true ) {
  10447. normalLocal.addAssign( getMorph( {
  10448. bufferMap,
  10449. influence,
  10450. stride,
  10451. width,
  10452. depth: i,
  10453. offset: int( 1 )
  10454. } ) );
  10455. }
  10456. } );
  10457. }
  10458. /**
  10459. * Updates the state of the morphed mesh by updating the base influence.
  10460. *
  10461. * @param {NodeFrame} frame - The current node frame.
  10462. */
  10463. update( /*frame*/ ) {
  10464. const morphBaseInfluence = this.morphBaseInfluence;
  10465. if ( this.mesh.geometry.morphTargetsRelative ) {
  10466. morphBaseInfluence.value = 1;
  10467. } else {
  10468. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10469. }
  10470. }
  10471. }
  10472. /**
  10473. * TSL function for creating a morph node.
  10474. *
  10475. * @tsl
  10476. * @function
  10477. * @param {Mesh} mesh - The mesh holding the morph targets.
  10478. * @returns {MorphNode}
  10479. */
  10480. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10481. /**
  10482. * Base class for lighting nodes.
  10483. *
  10484. * @augments Node
  10485. */
  10486. class LightingNode extends Node {
  10487. static get type() {
  10488. return 'LightingNode';
  10489. }
  10490. /**
  10491. * Constructs a new lighting node.
  10492. */
  10493. constructor() {
  10494. super( 'vec3' );
  10495. /**
  10496. * This flag can be used for type testing.
  10497. *
  10498. * @type {boolean}
  10499. * @readonly
  10500. * @default true
  10501. */
  10502. this.isLightingNode = true;
  10503. }
  10504. }
  10505. /**
  10506. * A generic class that can be used by nodes which contribute
  10507. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10508. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10509. *
  10510. * @augments LightingNode
  10511. */
  10512. class AONode extends LightingNode {
  10513. static get type() {
  10514. return 'AONode';
  10515. }
  10516. /**
  10517. * Constructs a new AO node.
  10518. *
  10519. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  10520. */
  10521. constructor( aoNode = null ) {
  10522. super();
  10523. /**
  10524. * The ambient occlusion node.
  10525. *
  10526. * @type {?Node<float>}
  10527. * @default null
  10528. */
  10529. this.aoNode = aoNode;
  10530. }
  10531. setup( builder ) {
  10532. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10533. }
  10534. }
  10535. /**
  10536. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  10537. * by adding lighting specific context data. It represents the runtime context of
  10538. * {@link LightsNode}.
  10539. *
  10540. * @augments ContextNode
  10541. */
  10542. class LightingContextNode extends ContextNode {
  10543. static get type() {
  10544. return 'LightingContextNode';
  10545. }
  10546. /**
  10547. * Constructs a new lighting context node.
  10548. *
  10549. * @param {LightsNode} node - The lights node.
  10550. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  10551. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  10552. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  10553. */
  10554. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10555. super( node );
  10556. /**
  10557. * The current lighting model.
  10558. *
  10559. * @type {?LightingModel}
  10560. * @default null
  10561. */
  10562. this.lightingModel = lightingModel;
  10563. /**
  10564. * A backdrop node.
  10565. *
  10566. * @type {?Node<vec3>}
  10567. * @default null
  10568. */
  10569. this.backdropNode = backdropNode;
  10570. /**
  10571. * A backdrop alpha node.
  10572. *
  10573. * @type {?Node<float>}
  10574. * @default null
  10575. */
  10576. this.backdropAlphaNode = backdropAlphaNode;
  10577. this._value = null;
  10578. }
  10579. /**
  10580. * Returns a lighting context object.
  10581. *
  10582. * @return {{
  10583. * radiance: Node<vec3>,
  10584. * irradiance: Node<vec3>,
  10585. * iblIrradiance: Node<vec3>,
  10586. * ambientOcclusion: Node<float>,
  10587. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10588. * backdrop: Node<vec3>,
  10589. * backdropAlpha: Node<float>
  10590. * }} The lighting context object.
  10591. */
  10592. getContext() {
  10593. const { backdropNode, backdropAlphaNode } = this;
  10594. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10595. directSpecular = vec3().toVar( 'directSpecular' ),
  10596. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10597. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10598. const reflectedLight = {
  10599. directDiffuse,
  10600. directSpecular,
  10601. indirectDiffuse,
  10602. indirectSpecular
  10603. };
  10604. const context = {
  10605. radiance: vec3().toVar( 'radiance' ),
  10606. irradiance: vec3().toVar( 'irradiance' ),
  10607. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10608. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10609. reflectedLight,
  10610. backdrop: backdropNode,
  10611. backdropAlpha: backdropAlphaNode
  10612. };
  10613. return context;
  10614. }
  10615. setup( builder ) {
  10616. this.value = this._value || ( this._value = this.getContext() );
  10617. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10618. return super.setup( builder );
  10619. }
  10620. }
  10621. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10622. /**
  10623. * A generic class that can be used by nodes which contribute
  10624. * irradiance to the scene. E.g. a light map node can be used
  10625. * as input for this module. Used in {@link NodeMaterial}.
  10626. *
  10627. * @augments LightingNode
  10628. */
  10629. class IrradianceNode extends LightingNode {
  10630. static get type() {
  10631. return 'IrradianceNode';
  10632. }
  10633. /**
  10634. * Constructs a new irradiance node.
  10635. *
  10636. * @param {Node<vec3>} node - A node contributing irradiance.
  10637. */
  10638. constructor( node ) {
  10639. super();
  10640. /**
  10641. * A node contributing irradiance.
  10642. *
  10643. * @type {Node<vec3>}
  10644. */
  10645. this.node = node;
  10646. }
  10647. setup( builder ) {
  10648. builder.context.irradiance.addAssign( this.node );
  10649. }
  10650. }
  10651. let screenSizeVec, viewportVec;
  10652. /**
  10653. * This node provides a collection of screen related metrics.
  10654. * Depending on {@link ScreenNode#scope}, the nodes can represent
  10655. * resolution or viewport data as well as fragment or uv coordinates.
  10656. *
  10657. * @augments Node
  10658. */
  10659. class ScreenNode extends Node {
  10660. static get type() {
  10661. return 'ScreenNode';
  10662. }
  10663. /**
  10664. * Constructs a new screen node.
  10665. *
  10666. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10667. */
  10668. constructor( scope ) {
  10669. super();
  10670. /**
  10671. * The node represents different metric depending on which scope is selected.
  10672. *
  10673. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10674. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10675. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10676. * - `ScreenNode.UV`: Normalized coordinates.
  10677. *
  10678. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10679. */
  10680. this.scope = scope;
  10681. /**
  10682. * This flag can be used for type testing.
  10683. *
  10684. * @type {boolean}
  10685. * @readonly
  10686. * @default true
  10687. */
  10688. this.isViewportNode = true;
  10689. }
  10690. /**
  10691. * This method is overwritten since the node type depends on the selected scope.
  10692. *
  10693. * @return {('vec2'|'vec4')} The node type.
  10694. */
  10695. getNodeType() {
  10696. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10697. else return 'vec2';
  10698. }
  10699. /**
  10700. * This method is overwritten since the node's update type depends on the selected scope.
  10701. *
  10702. * @return {NodeUpdateType} The update type.
  10703. */
  10704. getUpdateType() {
  10705. let updateType = NodeUpdateType.NONE;
  10706. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10707. updateType = NodeUpdateType.RENDER;
  10708. }
  10709. this.updateType = updateType;
  10710. return updateType;
  10711. }
  10712. /**
  10713. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10714. * from the current renderer.
  10715. *
  10716. * @param {NodeFrame} frame - A reference to the current node frame.
  10717. */
  10718. update( { renderer } ) {
  10719. const renderTarget = renderer.getRenderTarget();
  10720. if ( this.scope === ScreenNode.VIEWPORT ) {
  10721. if ( renderTarget !== null ) {
  10722. viewportVec.copy( renderTarget.viewport );
  10723. } else {
  10724. renderer.getViewport( viewportVec );
  10725. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10726. }
  10727. } else {
  10728. if ( renderTarget !== null ) {
  10729. screenSizeVec.width = renderTarget.width;
  10730. screenSizeVec.height = renderTarget.height;
  10731. } else {
  10732. renderer.getDrawingBufferSize( screenSizeVec );
  10733. }
  10734. }
  10735. }
  10736. setup( /*builder*/ ) {
  10737. const scope = this.scope;
  10738. let output = null;
  10739. if ( scope === ScreenNode.SIZE ) {
  10740. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10741. } else if ( scope === ScreenNode.VIEWPORT ) {
  10742. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10743. } else {
  10744. output = vec2( screenCoordinate.div( screenSize ) );
  10745. }
  10746. return output;
  10747. }
  10748. generate( builder ) {
  10749. if ( this.scope === ScreenNode.COORDINATE ) {
  10750. let coord = builder.getFragCoord();
  10751. if ( builder.isFlipY() ) {
  10752. // follow webgpu standards
  10753. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10754. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10755. }
  10756. return coord;
  10757. }
  10758. return super.generate( builder );
  10759. }
  10760. }
  10761. ScreenNode.COORDINATE = 'coordinate';
  10762. ScreenNode.VIEWPORT = 'viewport';
  10763. ScreenNode.SIZE = 'size';
  10764. ScreenNode.UV = 'uv';
  10765. // Screen
  10766. /**
  10767. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10768. *
  10769. * @tsl
  10770. * @type {ScreenNode<vec2>}
  10771. */
  10772. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10773. /**
  10774. * TSL object that represents the screen resolution in physical pixel units.
  10775. *
  10776. * @tsl
  10777. * @type {ScreenNode<vec2>}
  10778. */
  10779. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10780. /**
  10781. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10782. *
  10783. * @tsl
  10784. * @type {ScreenNode<vec2>}
  10785. */
  10786. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10787. // Viewport
  10788. /**
  10789. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10790. *
  10791. * @tsl
  10792. * @type {ScreenNode<vec4>}
  10793. */
  10794. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10795. /**
  10796. * TSL object that represents the viewport resolution in physical pixel units.
  10797. *
  10798. * @tsl
  10799. * @type {ScreenNode<vec2>}
  10800. */
  10801. const viewportSize = viewport.zw;
  10802. /**
  10803. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10804. *
  10805. * @tsl
  10806. * @type {ScreenNode<vec2>}
  10807. */
  10808. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10809. /**
  10810. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10811. *
  10812. * @tsl
  10813. * @type {ScreenNode<vec2>}
  10814. */
  10815. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10816. // Deprecated
  10817. /**
  10818. * @deprecated since r169. Use {@link screenSize} instead.
  10819. */
  10820. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10821. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10822. return screenSize;
  10823. }, 'vec2' ).once() )();
  10824. /**
  10825. * @tsl
  10826. * @deprecated since r168. Use {@link screenUV} instead.
  10827. * @type {Node<vec2>}
  10828. */
  10829. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10830. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10831. return screenUV;
  10832. }, 'vec2' ).once() )();
  10833. /**
  10834. * @tsl
  10835. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10836. * @type {Node<vec2>}
  10837. */
  10838. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10839. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10840. return screenUV.flipY();
  10841. }, 'vec2' ).once() )();
  10842. const _size$4 = /*@__PURE__*/ new Vector2();
  10843. /**
  10844. * A special type of texture node which represents the data of the current viewport
  10845. * as a texture. The module extracts data from the current bound framebuffer with
  10846. * a copy operation so no extra render pass is required to produce the texture data
  10847. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10848. * variety of effects like refractive or transmissive materials.
  10849. *
  10850. * @augments TextureNode
  10851. */
  10852. class ViewportTextureNode extends TextureNode {
  10853. static get type() {
  10854. return 'ViewportTextureNode';
  10855. }
  10856. /**
  10857. * Constructs a new viewport texture node.
  10858. *
  10859. * @param {Node} [uvNode=screenUV] - The uv node.
  10860. * @param {?Node} [levelNode=null] - The level node.
  10861. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10862. */
  10863. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10864. if ( framebufferTexture === null ) {
  10865. framebufferTexture = new FramebufferTexture();
  10866. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10867. }
  10868. super( framebufferTexture, uvNode, levelNode );
  10869. /**
  10870. * Whether to generate mipmaps or not.
  10871. *
  10872. * @type {boolean}
  10873. * @default false
  10874. */
  10875. this.generateMipmaps = false;
  10876. /**
  10877. * This flag can be used for type testing.
  10878. *
  10879. * @type {boolean}
  10880. * @readonly
  10881. * @default true
  10882. */
  10883. this.isOutputTextureNode = true;
  10884. /**
  10885. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10886. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10887. *
  10888. * @type {string}
  10889. * @default 'frame'
  10890. */
  10891. this.updateBeforeType = NodeUpdateType.FRAME;
  10892. }
  10893. updateBefore( frame ) {
  10894. const renderer = frame.renderer;
  10895. renderer.getDrawingBufferSize( _size$4 );
  10896. //
  10897. const framebufferTexture = this.value;
  10898. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10899. framebufferTexture.image.width = _size$4.width;
  10900. framebufferTexture.image.height = _size$4.height;
  10901. framebufferTexture.needsUpdate = true;
  10902. }
  10903. //
  10904. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10905. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10906. renderer.copyFramebufferToTexture( framebufferTexture );
  10907. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10908. }
  10909. clone() {
  10910. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10911. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10912. return viewportTextureNode;
  10913. }
  10914. }
  10915. /**
  10916. * TSL function for creating a viewport texture node.
  10917. *
  10918. * @tsl
  10919. * @function
  10920. * @param {Node} [uvNode=screenUV] - The uv node.
  10921. * @param {?Node} [levelNode=null] - The level node.
  10922. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10923. * @returns {ViewportTextureNode}
  10924. */
  10925. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10926. /**
  10927. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10928. *
  10929. * @tsl
  10930. * @function
  10931. * @param {Node} [uvNode=screenUV] - The uv node.
  10932. * @param {?Node} [levelNode=null] - The level node.
  10933. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10934. * @returns {ViewportTextureNode}
  10935. */
  10936. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10937. let sharedDepthbuffer = null;
  10938. /**
  10939. * Represents the depth of the current viewport as a texture. This module
  10940. * can be used in combination with viewport texture to achieve effects
  10941. * that require depth evaluation.
  10942. *
  10943. * @augments ViewportTextureNode
  10944. */
  10945. class ViewportDepthTextureNode extends ViewportTextureNode {
  10946. static get type() {
  10947. return 'ViewportDepthTextureNode';
  10948. }
  10949. /**
  10950. * Constructs a new viewport depth texture node.
  10951. *
  10952. * @param {Node} [uvNode=screenUV] - The uv node.
  10953. * @param {?Node} [levelNode=null] - The level node.
  10954. */
  10955. constructor( uvNode = screenUV, levelNode = null ) {
  10956. if ( sharedDepthbuffer === null ) {
  10957. sharedDepthbuffer = new DepthTexture();
  10958. }
  10959. super( uvNode, levelNode, sharedDepthbuffer );
  10960. }
  10961. }
  10962. /**
  10963. * TSL function for a viewport depth texture node.
  10964. *
  10965. * @tsl
  10966. * @function
  10967. * @param {Node} [uvNode=screenUV] - The uv node.
  10968. * @param {?Node} [levelNode=null] - The level node.
  10969. * @returns {ViewportDepthTextureNode}
  10970. */
  10971. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10972. /**
  10973. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10974. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10975. * fragment or for depth evaluation purposes.
  10976. *
  10977. * @augments Node
  10978. */
  10979. class ViewportDepthNode extends Node {
  10980. static get type() {
  10981. return 'ViewportDepthNode';
  10982. }
  10983. /**
  10984. * Constructs a new viewport depth node.
  10985. *
  10986. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10987. * @param {?Node} [valueNode=null] - The value node.
  10988. */
  10989. constructor( scope, valueNode = null ) {
  10990. super( 'float' );
  10991. /**
  10992. * The node behaves differently depending on which scope is selected.
  10993. *
  10994. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10995. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10996. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10997. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10998. *
  10999. * @type {('depth'|'depthBase'|'linearDepth')}
  11000. */
  11001. this.scope = scope;
  11002. /**
  11003. * Can be used to define a custom depth value.
  11004. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  11005. *
  11006. * @type {?Node}
  11007. * @default null
  11008. */
  11009. this.valueNode = valueNode;
  11010. /**
  11011. * This flag can be used for type testing.
  11012. *
  11013. * @type {boolean}
  11014. * @readonly
  11015. * @default true
  11016. */
  11017. this.isViewportDepthNode = true;
  11018. }
  11019. generate( builder ) {
  11020. const { scope } = this;
  11021. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11022. return builder.getFragDepth();
  11023. }
  11024. return super.generate( builder );
  11025. }
  11026. setup( { camera } ) {
  11027. const { scope } = this;
  11028. const value = this.valueNode;
  11029. let node = null;
  11030. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11031. if ( value !== null ) {
  11032. node = depthBase().assign( value );
  11033. }
  11034. } else if ( scope === ViewportDepthNode.DEPTH ) {
  11035. if ( camera.isPerspectiveCamera ) {
  11036. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  11037. } else {
  11038. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11039. }
  11040. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  11041. if ( value !== null ) {
  11042. if ( camera.isPerspectiveCamera ) {
  11043. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  11044. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  11045. } else {
  11046. node = value;
  11047. }
  11048. } else {
  11049. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11050. }
  11051. }
  11052. return node;
  11053. }
  11054. }
  11055. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  11056. ViewportDepthNode.DEPTH = 'depth';
  11057. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  11058. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  11059. /**
  11060. * TSL function for converting a viewZ value to an orthographic depth value.
  11061. *
  11062. * @tsl
  11063. * @function
  11064. * @param {Node<float>} viewZ - The viewZ node.
  11065. * @param {Node<float>} near - The camera's near value.
  11066. * @param {Node<float>} far - The camera's far value.
  11067. * @returns {Node<float>}
  11068. */
  11069. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  11070. /**
  11071. * TSL function for converting an orthographic depth value to a viewZ value.
  11072. *
  11073. * @tsl
  11074. * @function
  11075. * @param {Node<float>} depth - The orthographic depth.
  11076. * @param {Node<float>} near - The camera's near value.
  11077. * @param {Node<float>} far - The camera's far value.
  11078. * @returns {Node<float>}
  11079. */
  11080. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  11081. /**
  11082. * TSL function for converting a viewZ value to a perspective depth value.
  11083. *
  11084. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  11085. *
  11086. * @tsl
  11087. * @function
  11088. * @param {Node<float>} viewZ - The viewZ node.
  11089. * @param {Node<float>} near - The camera's near value.
  11090. * @param {Node<float>} far - The camera's far value.
  11091. * @returns {Node<float>}
  11092. */
  11093. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  11094. /**
  11095. * TSL function for converting a perspective depth value to a viewZ value.
  11096. *
  11097. * @tsl
  11098. * @function
  11099. * @param {Node<float>} depth - The perspective depth.
  11100. * @param {Node<float>} near - The camera's near value.
  11101. * @param {Node<float>} far - The camera's far value.
  11102. * @returns {Node<float>}
  11103. */
  11104. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  11105. /**
  11106. * TSL function for converting a viewZ value to a logarithmic depth value.
  11107. *
  11108. * @tsl
  11109. * @function
  11110. * @param {Node<float>} viewZ - The viewZ node.
  11111. * @param {Node<float>} near - The camera's near value.
  11112. * @param {Node<float>} far - The camera's far value.
  11113. * @returns {Node<float>}
  11114. */
  11115. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  11116. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  11117. // The final logarithmic depth formula used here is adapted from one described in an
  11118. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  11119. // which was an improvement upon an earlier formula one described in an
  11120. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  11121. // Ulrich's formula is the following:
  11122. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  11123. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  11124. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  11125. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  11126. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  11127. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  11128. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  11129. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  11130. // be used, and ultimately Ulrich's "near plane" version was chosen.
  11131. // Outerra eventually made another improvement to their original "C-constant" variant,
  11132. // but it still does not incorporate the camera near plane (for this version,
  11133. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  11134. // Here we make 4 changes to Ulrich's formula:
  11135. // 1. Clamp the camera near plane so we don't divide by 0.
  11136. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  11137. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  11138. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  11139. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  11140. // so we do the same here, hence the 'viewZ.negate()' call.
  11141. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  11142. near = near.max( 1e-6 ).toVar();
  11143. const numerator = log2( viewZ.negate().div( near ) );
  11144. const denominator = log2( far.div( near ) );
  11145. return numerator.div( denominator );
  11146. };
  11147. /**
  11148. * TSL function for converting a logarithmic depth value to a viewZ value.
  11149. *
  11150. * @tsl
  11151. * @function
  11152. * @param {Node<float>} depth - The logarithmic depth.
  11153. * @param {Node<float>} near - The camera's near value.
  11154. * @param {Node<float>} far - The camera's far value.
  11155. * @returns {Node<float>}
  11156. */
  11157. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  11158. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  11159. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  11160. // a negative viewZ).
  11161. const exponent = depth.mul( log( far.div( near ) ) );
  11162. return float( Math.E ).pow( exponent ).mul( near ).negate();
  11163. };
  11164. /**
  11165. * TSL function for defining a value for the current fragment's depth.
  11166. *
  11167. * @tsl
  11168. * @function
  11169. * @param {Node<float>} value - The depth value to set.
  11170. * @returns {ViewportDepthNode<float>}
  11171. */
  11172. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  11173. /**
  11174. * TSL object that represents the depth value for the current fragment.
  11175. *
  11176. * @tsl
  11177. * @type {ViewportDepthNode}
  11178. */
  11179. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  11180. /**
  11181. * TSL function for converting a perspective depth value to linear depth.
  11182. *
  11183. * @tsl
  11184. * @function
  11185. * @param {Node<float>} value - The perspective depth.
  11186. * @returns {ViewportDepthNode<float>}
  11187. */
  11188. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  11189. /**
  11190. * TSL object that represents the linear (orthographic) depth value of the current fragment
  11191. *
  11192. * @tsl
  11193. * @type {ViewportDepthNode}
  11194. */
  11195. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  11196. depth.assign = ( value ) => depthBase( value );
  11197. /**
  11198. * The node allows to set values for built-in shader variables. That is
  11199. * required for features like hardware-accelerated vertex clipping.
  11200. *
  11201. * @augments Node
  11202. */
  11203. class BuiltinNode extends Node {
  11204. /**
  11205. * Constructs a new builtin node.
  11206. *
  11207. * @param {string} name - The name of the built-in shader variable.
  11208. */
  11209. constructor( name ) {
  11210. super( 'float' );
  11211. /**
  11212. * The name of the built-in shader variable.
  11213. *
  11214. * @type {string}
  11215. */
  11216. this.name = name;
  11217. /**
  11218. * This flag can be used for type testing.
  11219. *
  11220. * @type {boolean}
  11221. * @readonly
  11222. * @default true
  11223. */
  11224. this.isBuiltinNode = true;
  11225. }
  11226. /**
  11227. * Generates the code snippet of the builtin node.
  11228. *
  11229. * @param {NodeBuilder} builder - The current node builder.
  11230. * @return {string} The generated code snippet.
  11231. */
  11232. generate( /* builder */ ) {
  11233. return this.name;
  11234. }
  11235. }
  11236. /**
  11237. * TSL function for creating a builtin node.
  11238. *
  11239. * @tsl
  11240. * @function
  11241. * @param {string} name - The name of the built-in shader variable.
  11242. * @returns {BuiltinNode}
  11243. */
  11244. const builtin = nodeProxy( BuiltinNode );
  11245. /**
  11246. * This node is used in {@link NodeMaterial} to setup the clipping
  11247. * which can happen hardware-accelerated (if supported) and optionally
  11248. * use alpha-to-coverage for anti-aliasing clipped edges.
  11249. *
  11250. * @augments Node
  11251. */
  11252. class ClippingNode extends Node {
  11253. static get type() {
  11254. return 'ClippingNode';
  11255. }
  11256. /**
  11257. * Constructs a new clipping node.
  11258. *
  11259. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  11260. * the selected scope influences the behavior of the node and what type of code is generated.
  11261. */
  11262. constructor( scope = ClippingNode.DEFAULT ) {
  11263. super();
  11264. /**
  11265. * The node's scope. Similar to other nodes, the selected scope influences
  11266. * the behavior of the node and what type of code is generated.
  11267. *
  11268. * @type {('default'|'hardware'|'alphaToCoverage')}
  11269. */
  11270. this.scope = scope;
  11271. }
  11272. /**
  11273. * Setups the node depending on the selected scope.
  11274. *
  11275. * @param {NodeBuilder} builder - The current node builder.
  11276. * @return {Node} The result node.
  11277. */
  11278. setup( builder ) {
  11279. super.setup( builder );
  11280. const clippingContext = builder.clippingContext;
  11281. const { intersectionPlanes, unionPlanes } = clippingContext;
  11282. this.hardwareClipping = builder.material.hardwareClipping;
  11283. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  11284. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  11285. } else if ( this.scope === ClippingNode.HARDWARE ) {
  11286. return this.setupHardwareClipping( unionPlanes, builder );
  11287. } else {
  11288. return this.setupDefault( intersectionPlanes, unionPlanes );
  11289. }
  11290. }
  11291. /**
  11292. * Setups alpha to coverage.
  11293. *
  11294. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11295. * @param {Array<Vector4>} unionPlanes - The union planes.
  11296. * @return {Node} The result node.
  11297. */
  11298. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  11299. return Fn( () => {
  11300. const distanceToPlane = float().toVar( 'distanceToPlane' );
  11301. const distanceGradient = float().toVar( 'distanceToGradient' );
  11302. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  11303. const numUnionPlanes = unionPlanes.length;
  11304. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11305. const clippingPlanes = uniformArray( unionPlanes );
  11306. Loop( numUnionPlanes, ( { i } ) => {
  11307. const plane = clippingPlanes.element( i );
  11308. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11309. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11310. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  11311. } );
  11312. }
  11313. const numIntersectionPlanes = intersectionPlanes.length;
  11314. if ( numIntersectionPlanes > 0 ) {
  11315. const clippingPlanes = uniformArray( intersectionPlanes );
  11316. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  11317. Loop( numIntersectionPlanes, ( { i } ) => {
  11318. const plane = clippingPlanes.element( i );
  11319. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11320. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11321. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  11322. } );
  11323. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  11324. }
  11325. diffuseColor.a.mulAssign( clipOpacity );
  11326. diffuseColor.a.equal( 0.0 ).discard();
  11327. } )();
  11328. }
  11329. /**
  11330. * Setups the default clipping.
  11331. *
  11332. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11333. * @param {Array<Vector4>} unionPlanes - The union planes.
  11334. * @return {Node} The result node.
  11335. */
  11336. setupDefault( intersectionPlanes, unionPlanes ) {
  11337. return Fn( () => {
  11338. const numUnionPlanes = unionPlanes.length;
  11339. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11340. const clippingPlanes = uniformArray( unionPlanes );
  11341. Loop( numUnionPlanes, ( { i } ) => {
  11342. const plane = clippingPlanes.element( i );
  11343. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  11344. } );
  11345. }
  11346. const numIntersectionPlanes = intersectionPlanes.length;
  11347. if ( numIntersectionPlanes > 0 ) {
  11348. const clippingPlanes = uniformArray( intersectionPlanes );
  11349. const clipped = bool( true ).toVar( 'clipped' );
  11350. Loop( numIntersectionPlanes, ( { i } ) => {
  11351. const plane = clippingPlanes.element( i );
  11352. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  11353. } );
  11354. clipped.discard();
  11355. }
  11356. } )();
  11357. }
  11358. /**
  11359. * Setups hardware clipping.
  11360. *
  11361. * @param {Array<Vector4>} unionPlanes - The union planes.
  11362. * @param {NodeBuilder} builder - The current node builder.
  11363. * @return {Node} The result node.
  11364. */
  11365. setupHardwareClipping( unionPlanes, builder ) {
  11366. const numUnionPlanes = unionPlanes.length;
  11367. builder.enableHardwareClipping( numUnionPlanes );
  11368. return Fn( () => {
  11369. const clippingPlanes = uniformArray( unionPlanes );
  11370. const hw_clip_distances = builtin( builder.getClipDistance() );
  11371. Loop( numUnionPlanes, ( { i } ) => {
  11372. const plane = clippingPlanes.element( i );
  11373. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  11374. hw_clip_distances.element( i ).assign( distance );
  11375. } );
  11376. } )();
  11377. }
  11378. }
  11379. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  11380. ClippingNode.DEFAULT = 'default';
  11381. ClippingNode.HARDWARE = 'hardware';
  11382. /**
  11383. * TSL function for setting up the default clipping logic.
  11384. *
  11385. * @tsl
  11386. * @function
  11387. * @returns {ClippingNode}
  11388. */
  11389. const clipping = () => nodeObject( new ClippingNode() );
  11390. /**
  11391. * TSL function for setting up alpha to coverage.
  11392. *
  11393. * @tsl
  11394. * @function
  11395. * @returns {ClippingNode}
  11396. */
  11397. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  11398. /**
  11399. * TSL function for setting up hardware-based clipping.
  11400. *
  11401. * @tsl
  11402. * @function
  11403. * @returns {ClippingNode}
  11404. */
  11405. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  11406. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  11407. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  11408. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11409. 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 ) ) ) ) ) );
  11410. } );
  11411. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11412. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  11413. } );
  11414. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  11415. // Find the discretized derivatives of our coordinates
  11416. const maxDeriv = max$1(
  11417. length( dFdx( position.xyz ) ),
  11418. length( dFdy( position.xyz ) )
  11419. );
  11420. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  11421. // Find two nearest log-discretized noise scales
  11422. const pixScales = vec2(
  11423. exp2( floor( log2( pixScale ) ) ),
  11424. exp2( ceil( log2( pixScale ) ) )
  11425. );
  11426. // Compute alpha thresholds at our two noise scales
  11427. const alpha = vec2(
  11428. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  11429. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  11430. );
  11431. // Factor to interpolate lerp with
  11432. const lerpFactor = fract( log2( pixScale ) );
  11433. // Interpolate alpha threshold from noise at two scales
  11434. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  11435. // Pass into CDF to compute uniformly distrib threshold
  11436. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  11437. const cases = vec3(
  11438. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  11439. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  11440. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  11441. // Find our final, uniformly distributed alpha threshold (ατ)
  11442. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  11443. // Avoids ατ == 0. Could also do ατ =1-ατ
  11444. return clamp( threshold, 1.0e-6, 1.0 );
  11445. } ).setLayout( {
  11446. name: 'getAlphaHashThreshold',
  11447. type: 'float',
  11448. inputs: [
  11449. { name: 'position', type: 'vec3' }
  11450. ]
  11451. } );
  11452. /**
  11453. * Base class for all node materials.
  11454. *
  11455. * @augments Material
  11456. */
  11457. class NodeMaterial extends Material {
  11458. static get type() {
  11459. return 'NodeMaterial';
  11460. }
  11461. /**
  11462. * Represents the type of the node material.
  11463. *
  11464. * @type {string}
  11465. */
  11466. get type() {
  11467. return this.constructor.type;
  11468. }
  11469. set type( _value ) { /* */ }
  11470. /**
  11471. * Constructs a new node material.
  11472. */
  11473. constructor() {
  11474. super();
  11475. /**
  11476. * This flag can be used for type testing.
  11477. *
  11478. * @type {boolean}
  11479. * @readonly
  11480. * @default true
  11481. */
  11482. this.isNodeMaterial = true;
  11483. /**
  11484. * Whether this material is affected by fog or not.
  11485. *
  11486. * @type {boolean}
  11487. * @default true
  11488. */
  11489. this.fog = true;
  11490. /**
  11491. * Whether this material is affected by lights or not.
  11492. *
  11493. * @type {boolean}
  11494. * @default false
  11495. */
  11496. this.lights = false;
  11497. /**
  11498. * Whether this material uses hardware clipping or not.
  11499. * This property is managed by the engine and should not be
  11500. * modified by apps.
  11501. *
  11502. * @type {boolean}
  11503. * @default false
  11504. */
  11505. this.hardwareClipping = false;
  11506. /**
  11507. * Node materials which set their `lights` property to `true`
  11508. * are affected by all lights of the scene. Sometimes selective
  11509. * lighting is wanted which means only _some_ lights in the scene
  11510. * affect a material. This can be achieved by creating an instance
  11511. * of {@link LightsNode} with a list of selective
  11512. * lights and assign the node to this property.
  11513. *
  11514. * ```js
  11515. * const customLightsNode = lights( [ light1, light2 ] );
  11516. * material.lightsNode = customLightsNode;
  11517. * ```
  11518. *
  11519. * @type {?LightsNode}
  11520. * @default null
  11521. */
  11522. this.lightsNode = null;
  11523. /**
  11524. * The environment of node materials can be defined by an environment
  11525. * map assigned to the `envMap` property or by `Scene.environment`
  11526. * if the node material is a PBR material. This node property allows to overwrite
  11527. * the default behavior and define the environment with a custom node.
  11528. *
  11529. * ```js
  11530. * material.envNode = pmremTexture( renderTarget.texture );
  11531. * ```
  11532. *
  11533. * @type {?Node<vec3>}
  11534. * @default null
  11535. */
  11536. this.envNode = null;
  11537. /**
  11538. * The lighting of node materials might be influenced by ambient occlusion.
  11539. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11540. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11541. * the default and define the ambient occlusion with a custom node instead.
  11542. *
  11543. * If you don't want to overwrite the diffuse color but modify the existing
  11544. * values instead, use {@link materialAO}.
  11545. *
  11546. * @type {?Node<float>}
  11547. * @default null
  11548. */
  11549. this.aoNode = null;
  11550. /**
  11551. * The diffuse color of node materials is by default inferred from the
  11552. * `color` and `map` properties. This node property allows to overwrite the default
  11553. * and define the diffuse color with a node instead.
  11554. *
  11555. * ```js
  11556. * material.colorNode = color( 0xff0000 ); // define red color
  11557. * ```
  11558. *
  11559. * If you don't want to overwrite the diffuse color but modify the existing
  11560. * values instead, use {@link materialColor}.
  11561. *
  11562. * ```js
  11563. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11564. * ```
  11565. *
  11566. * @type {?Node<vec3>}
  11567. * @default null
  11568. */
  11569. this.colorNode = null;
  11570. /**
  11571. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11572. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11573. * and define the normals with a node instead.
  11574. *
  11575. * If you don't want to overwrite the normals but modify the existing values instead,
  11576. * use {@link materialNormal}.
  11577. *
  11578. * @type {?Node<vec3>}
  11579. * @default null
  11580. */
  11581. this.normalNode = null;
  11582. /**
  11583. * The opacity of node materials is by default inferred from the `opacity`
  11584. * and `alphaMap` properties. This node property allows to overwrite the default
  11585. * and define the opacity with a node instead.
  11586. *
  11587. * If you don't want to overwrite the normals but modify the existing
  11588. * value instead, use {@link materialOpacity}.
  11589. *
  11590. * @type {?Node<float>}
  11591. * @default null
  11592. */
  11593. this.opacityNode = null;
  11594. /**
  11595. * This node can be used to to implement a variety of filter-like effects. The idea is
  11596. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11597. * to create an arbitrary effect and then assign the node composition to this property.
  11598. * Everything behind the object using this material will now be affected by a filter.
  11599. *
  11600. * ```js
  11601. * const material = new NodeMaterial()
  11602. * material.transparent = true;
  11603. *
  11604. * // everything behind the object will be monochromatic
  11605. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  11606. * ```
  11607. *
  11608. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11609. *
  11610. * @type {?Node<vec3>}
  11611. * @default null
  11612. */
  11613. this.backdropNode = null;
  11614. /**
  11615. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11616. *
  11617. * @type {?Node<float>}
  11618. * @default null
  11619. */
  11620. this.backdropAlphaNode = null;
  11621. /**
  11622. * The alpha test of node materials is by default inferred from the `alphaTest`
  11623. * property. This node property allows to overwrite the default and define the
  11624. * alpha test with a node instead.
  11625. *
  11626. * If you don't want to overwrite the alpha test but modify the existing
  11627. * value instead, use {@link materialAlphaTest}.
  11628. *
  11629. * @type {?Node<float>}
  11630. * @default null
  11631. */
  11632. this.alphaTestNode = null;
  11633. /**
  11634. * The local vertex positions are computed based on multiple factors like the
  11635. * attribute data, morphing or skinning. This node property allows to overwrite
  11636. * the default and define local vertex positions with nodes instead.
  11637. *
  11638. * If you don't want to overwrite the vertex positions but modify the existing
  11639. * values instead, use {@link positionLocal}.
  11640. *
  11641. *```js
  11642. * material.positionNode = positionLocal.add( displace );
  11643. * ```
  11644. *
  11645. * @type {?Node<vec3>}
  11646. * @default null
  11647. */
  11648. this.positionNode = null;
  11649. /**
  11650. * This node property is intended for logic which modifies geometry data once or per animation step.
  11651. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11652. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11653. * can be implemented.
  11654. *
  11655. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11656. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11657. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11658. * eventually assigned to `geometryNode`.
  11659. *
  11660. * @type {Function}
  11661. * @default null
  11662. */
  11663. this.geometryNode = null;
  11664. /**
  11665. * Allows to overwrite depth values in the fragment shader.
  11666. *
  11667. * @type {?Node<float>}
  11668. * @default null
  11669. */
  11670. this.depthNode = null;
  11671. /**
  11672. * Allows to overwrite the position used for shadow map rendering which
  11673. * is by default {@link positionWorld}, the vertex position
  11674. * in world space.
  11675. *
  11676. * @type {?Node<float>}
  11677. * @default null
  11678. */
  11679. this.shadowPositionNode = null;
  11680. /**
  11681. * This node can be used to influence how an object using this node material
  11682. * receive shadows.
  11683. *
  11684. * ```js
  11685. * const totalShadows = float( 1 ).toVar();
  11686. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11687. * totalShadows.mulAssign( shadow );
  11688. * //return float( 1 ); // bypass received shadows
  11689. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11690. * } );
  11691. *
  11692. * @type {?Node<vec4>}
  11693. * @default null
  11694. */
  11695. this.receivedShadowNode = null;
  11696. /**
  11697. * This node can be used to influence how an object using this node material
  11698. * casts shadows. To apply a color to shadows, you can simply do:
  11699. *
  11700. * ```js
  11701. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11702. * ```
  11703. *
  11704. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11705. * is also common to use the property with `Fn` function so checks are performed
  11706. * per fragment.
  11707. *
  11708. * ```js
  11709. * materialCustomShadow.castShadowNode = Fn( () => {
  11710. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11711. * return materialColor;
  11712. * } )();
  11713. * ```
  11714. *
  11715. * @type {?Node<vec4>}
  11716. * @default null
  11717. */
  11718. this.castShadowNode = null;
  11719. /**
  11720. * This node can be used to define the final output of the material.
  11721. *
  11722. * TODO: Explain the differences to `fragmentNode`.
  11723. *
  11724. * @type {?Node<vec4>}
  11725. * @default null
  11726. */
  11727. this.outputNode = null;
  11728. /**
  11729. * MRT configuration is done on renderer or pass level. This node allows to
  11730. * overwrite what values are written into MRT targets on material level. This
  11731. * can be useful for implementing selective FX features that should only affect
  11732. * specific objects.
  11733. *
  11734. * @type {?MRTNode}
  11735. * @default null
  11736. */
  11737. this.mrtNode = null;
  11738. /**
  11739. * This node property can be used if you need complete freedom in implementing
  11740. * the fragment shader. Assigning a node will replace the built-in material
  11741. * logic used in the fragment stage.
  11742. *
  11743. * @type {?Node<vec4>}
  11744. * @default null
  11745. */
  11746. this.fragmentNode = null;
  11747. /**
  11748. * This node property can be used if you need complete freedom in implementing
  11749. * the vertex shader. Assigning a node will replace the built-in material logic
  11750. * used in the vertex stage.
  11751. *
  11752. * @type {?Node<vec4>}
  11753. * @default null
  11754. */
  11755. this.vertexNode = null;
  11756. }
  11757. /**
  11758. * Allows to define a custom cache key that influence the material key computation
  11759. * for render objects.
  11760. *
  11761. * @return {string} The custom cache key.
  11762. */
  11763. customProgramCacheKey() {
  11764. return this.type + getCacheKey$1( this );
  11765. }
  11766. /**
  11767. * Builds this material with the given node builder.
  11768. *
  11769. * @param {NodeBuilder} builder - The current node builder.
  11770. */
  11771. build( builder ) {
  11772. this.setup( builder );
  11773. }
  11774. /**
  11775. * Setups a node material observer with the given builder.
  11776. *
  11777. * @param {NodeBuilder} builder - The current node builder.
  11778. * @return {NodeMaterialObserver} The node material observer.
  11779. */
  11780. setupObserver( builder ) {
  11781. return new NodeMaterialObserver( builder );
  11782. }
  11783. /**
  11784. * Setups the vertex and fragment stage of this node material.
  11785. *
  11786. * @param {NodeBuilder} builder - The current node builder.
  11787. */
  11788. setup( builder ) {
  11789. builder.context.setupNormal = () => this.setupNormal( builder );
  11790. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11791. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11792. const renderer = builder.renderer;
  11793. const renderTarget = renderer.getRenderTarget();
  11794. // < VERTEX STAGE >
  11795. builder.addStack();
  11796. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11797. builder.stack.outputNode = vertexNode;
  11798. this.setupHardwareClipping( builder );
  11799. if ( this.geometryNode !== null ) {
  11800. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11801. }
  11802. builder.addFlow( 'vertex', builder.removeStack() );
  11803. // < FRAGMENT STAGE >
  11804. builder.addStack();
  11805. let resultNode;
  11806. const clippingNode = this.setupClipping( builder );
  11807. if ( this.depthWrite === true || this.depthTest === true ) {
  11808. // only write depth if depth buffer is configured
  11809. if ( renderTarget !== null ) {
  11810. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11811. } else {
  11812. if ( renderer.depth === true ) this.setupDepth( builder );
  11813. }
  11814. }
  11815. if ( this.fragmentNode === null ) {
  11816. this.setupDiffuseColor( builder );
  11817. this.setupVariants( builder );
  11818. const outgoingLightNode = this.setupLighting( builder );
  11819. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11820. // force unsigned floats - useful for RenderTargets
  11821. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11822. resultNode = this.setupOutput( builder, basicOutput );
  11823. // OUTPUT NODE
  11824. output.assign( resultNode );
  11825. //
  11826. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11827. // MRT
  11828. if ( renderTarget !== null ) {
  11829. const mrt = renderer.getMRT();
  11830. const materialMRT = this.mrtNode;
  11831. if ( mrt !== null ) {
  11832. resultNode = mrt;
  11833. if ( materialMRT !== null ) {
  11834. resultNode = mrt.merge( materialMRT );
  11835. }
  11836. } else if ( materialMRT !== null ) {
  11837. resultNode = materialMRT;
  11838. }
  11839. }
  11840. } else {
  11841. let fragmentNode = this.fragmentNode;
  11842. if ( fragmentNode.isOutputStructNode !== true ) {
  11843. fragmentNode = vec4( fragmentNode );
  11844. }
  11845. resultNode = this.setupOutput( builder, fragmentNode );
  11846. }
  11847. builder.stack.outputNode = resultNode;
  11848. builder.addFlow( 'fragment', builder.removeStack() );
  11849. // < OBSERVER >
  11850. builder.observer = this.setupObserver( builder );
  11851. }
  11852. /**
  11853. * Setups the clipping node.
  11854. *
  11855. * @param {NodeBuilder} builder - The current node builder.
  11856. * @return {ClippingNode} The clipping node.
  11857. */
  11858. setupClipping( builder ) {
  11859. if ( builder.clippingContext === null ) return null;
  11860. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11861. let result = null;
  11862. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11863. const samples = builder.renderer.samples;
  11864. if ( this.alphaToCoverage && samples > 1 ) {
  11865. // to be added to flow when the color/alpha value has been determined
  11866. result = clippingAlpha();
  11867. } else {
  11868. builder.stack.add( clipping() );
  11869. }
  11870. }
  11871. return result;
  11872. }
  11873. /**
  11874. * Setups the hardware clipping if available on the current device.
  11875. *
  11876. * @param {NodeBuilder} builder - The current node builder.
  11877. */
  11878. setupHardwareClipping( builder ) {
  11879. this.hardwareClipping = false;
  11880. if ( builder.clippingContext === null ) return;
  11881. const candidateCount = builder.clippingContext.unionPlanes.length;
  11882. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11883. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11884. builder.stack.add( hardwareClipping() );
  11885. this.hardwareClipping = true;
  11886. }
  11887. return;
  11888. }
  11889. /**
  11890. * Setups the depth of this material.
  11891. *
  11892. * @param {NodeBuilder} builder - The current node builder.
  11893. */
  11894. setupDepth( builder ) {
  11895. const { renderer, camera } = builder;
  11896. // Depth
  11897. let depthNode = this.depthNode;
  11898. if ( depthNode === null ) {
  11899. const mrt = renderer.getMRT();
  11900. if ( mrt && mrt.has( 'depth' ) ) {
  11901. depthNode = mrt.get( 'depth' );
  11902. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11903. if ( camera.isPerspectiveCamera ) {
  11904. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11905. } else {
  11906. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11907. }
  11908. }
  11909. }
  11910. if ( depthNode !== null ) {
  11911. depth.assign( depthNode ).append();
  11912. }
  11913. }
  11914. /**
  11915. * Setups the position node in view space. This method exists
  11916. * so derived node materials can modify the implementation e.g. sprite materials.
  11917. *
  11918. * @param {NodeBuilder} builder - The current node builder.
  11919. * @return {Node<vec3>} The position in view space.
  11920. */
  11921. setupPositionView( /*builder*/ ) {
  11922. return modelViewMatrix.mul( positionLocal ).xyz;
  11923. }
  11924. /**
  11925. * Setups the position in clip space.
  11926. *
  11927. * @param {NodeBuilder} builder - The current node builder.
  11928. * @return {Node<vec4>} The position in view space.
  11929. */
  11930. setupModelViewProjection( /*builder*/ ) {
  11931. return cameraProjectionMatrix.mul( positionView );
  11932. }
  11933. /**
  11934. * Setups the logic for the vertex stage.
  11935. *
  11936. * @param {NodeBuilder} builder - The current node builder.
  11937. * @return {Node<vec4>} The position in clip space.
  11938. */
  11939. setupVertex( builder ) {
  11940. builder.addStack();
  11941. this.setupPosition( builder );
  11942. builder.context.vertex = builder.removeStack();
  11943. return modelViewProjection;
  11944. }
  11945. /**
  11946. * Setups the computation of the position in local space.
  11947. *
  11948. * @param {NodeBuilder} builder - The current node builder.
  11949. * @return {Node<vec3>} The position in local space.
  11950. */
  11951. setupPosition( builder ) {
  11952. const { object, geometry } = builder;
  11953. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11954. morphReference( object ).append();
  11955. }
  11956. if ( object.isSkinnedMesh === true ) {
  11957. skinningReference( object ).append();
  11958. }
  11959. if ( this.displacementMap ) {
  11960. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11961. const displacementScale = materialReference( 'displacementScale', 'float' );
  11962. const displacementBias = materialReference( 'displacementBias', 'float' );
  11963. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11964. }
  11965. if ( object.isBatchedMesh ) {
  11966. batch( object ).append();
  11967. }
  11968. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11969. instancedMesh( object ).append();
  11970. }
  11971. if ( this.positionNode !== null ) {
  11972. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11973. }
  11974. return positionLocal;
  11975. }
  11976. /**
  11977. * Setups the computation of the material's diffuse color.
  11978. *
  11979. * @param {NodeBuilder} builder - The current node builder.
  11980. * @param {BufferGeometry} geometry - The geometry.
  11981. */
  11982. setupDiffuseColor( { object, geometry } ) {
  11983. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11984. // VERTEX COLORS
  11985. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11986. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11987. }
  11988. // Instanced colors
  11989. if ( object.instanceColor ) {
  11990. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11991. colorNode = instanceColor.mul( colorNode );
  11992. }
  11993. if ( object.isBatchedMesh && object._colorsTexture ) {
  11994. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11995. colorNode = batchColor.mul( colorNode );
  11996. }
  11997. // COLOR
  11998. diffuseColor.assign( colorNode );
  11999. // OPACITY
  12000. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12001. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  12002. // ALPHA TEST
  12003. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  12004. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  12005. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  12006. }
  12007. // ALPHA HASH
  12008. if ( this.alphaHash === true ) {
  12009. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  12010. }
  12011. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  12012. diffuseColor.a.assign( 1.0 );
  12013. }
  12014. }
  12015. /**
  12016. * Abstract interface method that can be implemented by derived materials
  12017. * to setup material-specific node variables.
  12018. *
  12019. * @abstract
  12020. * @param {NodeBuilder} builder - The current node builder.
  12021. */
  12022. setupVariants( /*builder*/ ) {
  12023. // Interface function.
  12024. }
  12025. /**
  12026. * Setups the outgoing light node variable
  12027. *
  12028. * @return {Node<vec3>} The outgoing light node.
  12029. */
  12030. setupOutgoingLight() {
  12031. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  12032. }
  12033. /**
  12034. * Setups the normal node from the material.
  12035. *
  12036. * @return {Node<vec3>} The normal node.
  12037. */
  12038. setupNormal() {
  12039. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  12040. }
  12041. /**
  12042. * Setups the environment node from the material.
  12043. *
  12044. * @param {NodeBuilder} builder - The current node builder.
  12045. * @return {Node<vec4>} The environment node.
  12046. */
  12047. setupEnvironment( /*builder*/ ) {
  12048. let node = null;
  12049. if ( this.envNode ) {
  12050. node = this.envNode;
  12051. } else if ( this.envMap ) {
  12052. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  12053. }
  12054. return node;
  12055. }
  12056. /**
  12057. * Setups the light map node from the material.
  12058. *
  12059. * @param {NodeBuilder} builder - The current node builder.
  12060. * @return {Node<vec3>} The light map node.
  12061. */
  12062. setupLightMap( builder ) {
  12063. let node = null;
  12064. if ( builder.material.lightMap ) {
  12065. node = new IrradianceNode( materialLightMap );
  12066. }
  12067. return node;
  12068. }
  12069. /**
  12070. * Setups the lights node based on the scene, environment and material.
  12071. *
  12072. * @param {NodeBuilder} builder - The current node builder.
  12073. * @return {LightsNode} The lights node.
  12074. */
  12075. setupLights( builder ) {
  12076. const materialLightsNode = [];
  12077. //
  12078. const envNode = this.setupEnvironment( builder );
  12079. if ( envNode && envNode.isLightingNode ) {
  12080. materialLightsNode.push( envNode );
  12081. }
  12082. const lightMapNode = this.setupLightMap( builder );
  12083. if ( lightMapNode && lightMapNode.isLightingNode ) {
  12084. materialLightsNode.push( lightMapNode );
  12085. }
  12086. if ( this.aoNode !== null || builder.material.aoMap ) {
  12087. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  12088. materialLightsNode.push( new AONode( aoNode ) );
  12089. }
  12090. let lightsN = this.lightsNode || builder.lightsNode;
  12091. if ( materialLightsNode.length > 0 ) {
  12092. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  12093. }
  12094. return lightsN;
  12095. }
  12096. /**
  12097. * This method should be implemented by most derived materials
  12098. * since it defines the material's lighting model.
  12099. *
  12100. * @abstract
  12101. * @param {NodeBuilder} builder - The current node builder.
  12102. * @return {LightingModel} The lighting model.
  12103. */
  12104. setupLightingModel( /*builder*/ ) {
  12105. // Interface function.
  12106. }
  12107. /**
  12108. * Setups the outgoing light node.
  12109. *
  12110. * @param {NodeBuilder} builder - The current node builder.
  12111. * @return {Node<vec3>} The outgoing light node.
  12112. */
  12113. setupLighting( builder ) {
  12114. const { material } = builder;
  12115. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  12116. // OUTGOING LIGHT
  12117. const lights = this.lights === true || this.lightsNode !== null;
  12118. const lightsNode = lights ? this.setupLights( builder ) : null;
  12119. let outgoingLightNode = this.setupOutgoingLight( builder );
  12120. if ( lightsNode && lightsNode.getScope().hasLights ) {
  12121. const lightingModel = this.setupLightingModel( builder );
  12122. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  12123. } else if ( backdropNode !== null ) {
  12124. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  12125. }
  12126. // EMISSIVE
  12127. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  12128. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  12129. outgoingLightNode = outgoingLightNode.add( emissive );
  12130. }
  12131. return outgoingLightNode;
  12132. }
  12133. /**
  12134. * Setups the output node.
  12135. *
  12136. * @param {NodeBuilder} builder - The current node builder.
  12137. * @param {Node<vec4>} outputNode - The existing output node.
  12138. * @return {Node<vec4>} The output node.
  12139. */
  12140. setupOutput( builder, outputNode ) {
  12141. // FOG
  12142. if ( this.fog === true ) {
  12143. const fogNode = builder.fogNode;
  12144. if ( fogNode ) {
  12145. output.assign( outputNode );
  12146. outputNode = vec4( fogNode );
  12147. }
  12148. }
  12149. return outputNode;
  12150. }
  12151. /**
  12152. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  12153. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  12154. * defining all material properties of the classic type in the node type.
  12155. *
  12156. * @param {Material} material - The material to copy properties with their values to this node material.
  12157. */
  12158. setDefaultValues( material ) {
  12159. // This approach is to reuse the native refreshUniforms*
  12160. // and turn available the use of features like transmission and environment in core
  12161. for ( const property in material ) {
  12162. const value = material[ property ];
  12163. if ( this[ property ] === undefined ) {
  12164. this[ property ] = value;
  12165. if ( value && value.clone ) this[ property ] = value.clone();
  12166. }
  12167. }
  12168. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  12169. for ( const key in descriptors ) {
  12170. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  12171. descriptors[ key ].get !== undefined ) {
  12172. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  12173. }
  12174. }
  12175. }
  12176. /**
  12177. * Serializes this material to JSON.
  12178. *
  12179. * @param {?(Object|string)} meta - The meta information for serialization.
  12180. * @return {Object} The serialized node.
  12181. */
  12182. toJSON( meta ) {
  12183. const isRoot = ( meta === undefined || typeof meta === 'string' );
  12184. if ( isRoot ) {
  12185. meta = {
  12186. textures: {},
  12187. images: {},
  12188. nodes: {}
  12189. };
  12190. }
  12191. const data = Material.prototype.toJSON.call( this, meta );
  12192. const nodeChildren = getNodeChildren( this );
  12193. data.inputNodes = {};
  12194. for ( const { property, childNode } of nodeChildren ) {
  12195. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  12196. }
  12197. // TODO: Copied from Object3D.toJSON
  12198. function extractFromCache( cache ) {
  12199. const values = [];
  12200. for ( const key in cache ) {
  12201. const data = cache[ key ];
  12202. delete data.metadata;
  12203. values.push( data );
  12204. }
  12205. return values;
  12206. }
  12207. if ( isRoot ) {
  12208. const textures = extractFromCache( meta.textures );
  12209. const images = extractFromCache( meta.images );
  12210. const nodes = extractFromCache( meta.nodes );
  12211. if ( textures.length > 0 ) data.textures = textures;
  12212. if ( images.length > 0 ) data.images = images;
  12213. if ( nodes.length > 0 ) data.nodes = nodes;
  12214. }
  12215. return data;
  12216. }
  12217. /**
  12218. * Copies the properties of the given node material to this instance.
  12219. *
  12220. * @param {NodeMaterial} source - The material to copy.
  12221. * @return {NodeMaterial} A reference to this node material.
  12222. */
  12223. copy( source ) {
  12224. this.lightsNode = source.lightsNode;
  12225. this.envNode = source.envNode;
  12226. this.colorNode = source.colorNode;
  12227. this.normalNode = source.normalNode;
  12228. this.opacityNode = source.opacityNode;
  12229. this.backdropNode = source.backdropNode;
  12230. this.backdropAlphaNode = source.backdropAlphaNode;
  12231. this.alphaTestNode = source.alphaTestNode;
  12232. this.positionNode = source.positionNode;
  12233. this.geometryNode = source.geometryNode;
  12234. this.depthNode = source.depthNode;
  12235. this.shadowPositionNode = source.shadowPositionNode;
  12236. this.receivedShadowNode = source.receivedShadowNode;
  12237. this.castShadowNode = source.castShadowNode;
  12238. this.outputNode = source.outputNode;
  12239. this.mrtNode = source.mrtNode;
  12240. this.fragmentNode = source.fragmentNode;
  12241. this.vertexNode = source.vertexNode;
  12242. return super.copy( source );
  12243. }
  12244. }
  12245. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  12246. /**
  12247. * Node material version of `LineBasicMaterial`.
  12248. *
  12249. * @augments NodeMaterial
  12250. */
  12251. class LineBasicNodeMaterial extends NodeMaterial {
  12252. static get type() {
  12253. return 'LineBasicNodeMaterial';
  12254. }
  12255. /**
  12256. * Constructs a new line basic node material.
  12257. *
  12258. * @param {?Object} parameters - The configuration parameter.
  12259. */
  12260. constructor( parameters ) {
  12261. super();
  12262. /**
  12263. * This flag can be used for type testing.
  12264. *
  12265. * @type {boolean}
  12266. * @readonly
  12267. * @default true
  12268. */
  12269. this.isLineBasicNodeMaterial = true;
  12270. this.setDefaultValues( _defaultValues$d );
  12271. this.setValues( parameters );
  12272. }
  12273. }
  12274. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  12275. /**
  12276. * Node material version of `LineDashedMaterial`.
  12277. *
  12278. * @augments NodeMaterial
  12279. */
  12280. class LineDashedNodeMaterial extends NodeMaterial {
  12281. static get type() {
  12282. return 'LineDashedNodeMaterial';
  12283. }
  12284. /**
  12285. * Constructs a new line dashed node material.
  12286. *
  12287. * @param {?Object} parameters - The configuration parameter.
  12288. */
  12289. constructor( parameters ) {
  12290. super();
  12291. /**
  12292. * This flag can be used for type testing.
  12293. *
  12294. * @type {boolean}
  12295. * @readonly
  12296. * @default true
  12297. */
  12298. this.isLineDashedNodeMaterial = true;
  12299. this.setDefaultValues( _defaultValues$c );
  12300. /**
  12301. * The dash offset.
  12302. *
  12303. * @type {number}
  12304. * @default 0
  12305. */
  12306. this.dashOffset = 0;
  12307. /**
  12308. * The offset of dash materials is by default inferred from the `dashOffset`
  12309. * property. This node property allows to overwrite the default
  12310. * and define the offset with a node instead.
  12311. *
  12312. * If you don't want to overwrite the offset but modify the existing
  12313. * value instead, use {@link materialLineDashOffset}.
  12314. *
  12315. * @type {?Node<float>}
  12316. * @default null
  12317. */
  12318. this.offsetNode = null;
  12319. /**
  12320. * The scale of dash materials is by default inferred from the `scale`
  12321. * property. This node property allows to overwrite the default
  12322. * and define the scale with a node instead.
  12323. *
  12324. * If you don't want to overwrite the scale but modify the existing
  12325. * value instead, use {@link materialLineScale}.
  12326. *
  12327. * @type {?Node<float>}
  12328. * @default null
  12329. */
  12330. this.dashScaleNode = null;
  12331. /**
  12332. * The dash size of dash materials is by default inferred from the `dashSize`
  12333. * property. This node property allows to overwrite the default
  12334. * and define the dash size with a node instead.
  12335. *
  12336. * If you don't want to overwrite the dash size but modify the existing
  12337. * value instead, use {@link materialLineDashSize}.
  12338. *
  12339. * @type {?Node<float>}
  12340. * @default null
  12341. */
  12342. this.dashSizeNode = null;
  12343. /**
  12344. * The gap size of dash materials is by default inferred from the `gapSize`
  12345. * property. This node property allows to overwrite the default
  12346. * and define the gap size with a node instead.
  12347. *
  12348. * If you don't want to overwrite the gap size but modify the existing
  12349. * value instead, use {@link materialLineGapSize}.
  12350. *
  12351. * @type {?Node<float>}
  12352. * @default null
  12353. */
  12354. this.gapSizeNode = null;
  12355. this.setValues( parameters );
  12356. }
  12357. /**
  12358. * Setups the dash specific node variables.
  12359. *
  12360. * @param {NodeBuilder} builder - The current node builder.
  12361. */
  12362. setupVariants( /* builder */ ) {
  12363. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12364. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12365. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12366. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12367. dashSize.assign( dashSizeNode );
  12368. gapSize.assign( gapSizeNode );
  12369. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  12370. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  12371. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  12372. }
  12373. }
  12374. let _sharedFramebuffer = null;
  12375. /**
  12376. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  12377. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  12378. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  12379. *
  12380. * @augments ViewportTextureNode
  12381. */
  12382. class ViewportSharedTextureNode extends ViewportTextureNode {
  12383. static get type() {
  12384. return 'ViewportSharedTextureNode';
  12385. }
  12386. /**
  12387. * Constructs a new viewport shared texture node.
  12388. *
  12389. * @param {Node} [uvNode=screenUV] - The uv node.
  12390. * @param {?Node} [levelNode=null] - The level node.
  12391. */
  12392. constructor( uvNode = screenUV, levelNode = null ) {
  12393. if ( _sharedFramebuffer === null ) {
  12394. _sharedFramebuffer = new FramebufferTexture();
  12395. }
  12396. super( uvNode, levelNode, _sharedFramebuffer );
  12397. }
  12398. updateReference() {
  12399. return this;
  12400. }
  12401. }
  12402. /**
  12403. * TSL function for creating a shared viewport texture node.
  12404. *
  12405. * @tsl
  12406. * @function
  12407. * @param {Node} [uvNode=screenUV] - The uv node.
  12408. * @param {?Node} [levelNode=null] - The level node.
  12409. * @returns {ViewportSharedTextureNode}
  12410. */
  12411. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  12412. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  12413. /**
  12414. * This node material can be used to render lines with a size larger than one
  12415. * by representing them as instanced meshes.
  12416. *
  12417. * @augments NodeMaterial
  12418. */
  12419. class Line2NodeMaterial extends NodeMaterial {
  12420. static get type() {
  12421. return 'Line2NodeMaterial';
  12422. }
  12423. /**
  12424. * Constructs a new node material for wide line rendering.
  12425. *
  12426. * @param {?Object} parameters - The configuration parameter.
  12427. */
  12428. constructor( parameters = {} ) {
  12429. super();
  12430. /**
  12431. * This flag can be used for type testing.
  12432. *
  12433. * @type {boolean}
  12434. * @readonly
  12435. * @default true
  12436. */
  12437. this.isLine2NodeMaterial = true;
  12438. this.setDefaultValues( _defaultValues$b );
  12439. /**
  12440. * Whether vertex colors should be used or not.
  12441. *
  12442. * @type {boolean}
  12443. * @default false
  12444. */
  12445. this.useColor = parameters.vertexColors;
  12446. /**
  12447. * The dash offset.
  12448. *
  12449. * @type {number}
  12450. * @default 0
  12451. */
  12452. this.dashOffset = 0;
  12453. /**
  12454. * The line width.
  12455. *
  12456. * @type {number}
  12457. * @default 0
  12458. */
  12459. this.lineWidth = 1;
  12460. /**
  12461. * Defines the lines color.
  12462. *
  12463. * @type {?Node<vec3>}
  12464. * @default null
  12465. */
  12466. this.lineColorNode = null;
  12467. /**
  12468. * Defines the offset.
  12469. *
  12470. * @type {?Node<float>}
  12471. * @default null
  12472. */
  12473. this.offsetNode = null;
  12474. /**
  12475. * Defines the dash scale.
  12476. *
  12477. * @type {?Node<float>}
  12478. * @default null
  12479. */
  12480. this.dashScaleNode = null;
  12481. /**
  12482. * Defines the dash size.
  12483. *
  12484. * @type {?Node<float>}
  12485. * @default null
  12486. */
  12487. this.dashSizeNode = null;
  12488. /**
  12489. * Defines the gap size.
  12490. *
  12491. * @type {?Node<float>}
  12492. * @default null
  12493. */
  12494. this.gapSizeNode = null;
  12495. /**
  12496. * Blending is set to `NoBlending` since transparency
  12497. * is not supported, yet.
  12498. *
  12499. * @type {number}
  12500. * @default 0
  12501. */
  12502. this.blending = NoBlending;
  12503. this._useDash = parameters.dashed;
  12504. this._useAlphaToCoverage = true;
  12505. this._useWorldUnits = false;
  12506. this.setValues( parameters );
  12507. }
  12508. /**
  12509. * Setups the vertex and fragment stage of this node material.
  12510. *
  12511. * @param {NodeBuilder} builder - The current node builder.
  12512. */
  12513. setup( builder ) {
  12514. const { renderer } = builder;
  12515. const useAlphaToCoverage = this._useAlphaToCoverage;
  12516. const useColor = this.useColor;
  12517. const useDash = this._useDash;
  12518. const useWorldUnits = this._useWorldUnits;
  12519. const trimSegment = Fn( ( { start, end } ) => {
  12520. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12521. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12522. const nearEstimate = b.mul( -0.5 ).div( a );
  12523. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12524. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12525. } ).setLayout( {
  12526. name: 'trimSegment',
  12527. type: 'vec4',
  12528. inputs: [
  12529. { name: 'start', type: 'vec4' },
  12530. { name: 'end', type: 'vec4' }
  12531. ]
  12532. } );
  12533. this.vertexNode = Fn( () => {
  12534. const instanceStart = attribute( 'instanceStart' );
  12535. const instanceEnd = attribute( 'instanceEnd' );
  12536. // camera space
  12537. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12538. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12539. if ( useDash ) {
  12540. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12541. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12542. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12543. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12544. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12545. lineDistance = lineDistance.add( offsetNode );
  12546. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12547. }
  12548. if ( useWorldUnits ) {
  12549. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12550. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12551. }
  12552. const aspect = viewport.z.div( viewport.w );
  12553. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12554. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12555. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12556. // perhaps there is a more elegant solution -- WestLangley
  12557. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  12558. If( perspective, () => {
  12559. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12560. end.assign( trimSegment( { start: start, end: end } ) );
  12561. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12562. start.assign( trimSegment( { start: end, end: start } ) );
  12563. } );
  12564. } );
  12565. // clip space
  12566. const clipStart = cameraProjectionMatrix.mul( start );
  12567. const clipEnd = cameraProjectionMatrix.mul( end );
  12568. // ndc space
  12569. const ndcStart = clipStart.xyz.div( clipStart.w );
  12570. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12571. // direction
  12572. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12573. // account for clip-space aspect ratio
  12574. dir.x.assign( dir.x.mul( aspect ) );
  12575. dir.assign( dir.normalize() );
  12576. const clip = vec4().toVar();
  12577. if ( useWorldUnits ) {
  12578. // get the offset direction as perpendicular to the view vector
  12579. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12580. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12581. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12582. const worldFwd = worldDir.cross( worldUp );
  12583. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12584. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12585. // height offset
  12586. const hw = materialLineWidth.mul( 0.5 );
  12587. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12588. // don't extend the line if we're rendering dashes because we
  12589. // won't be rendering the endcaps
  12590. if ( ! useDash ) {
  12591. // cap extension
  12592. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12593. // add width to the box
  12594. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12595. // endcaps
  12596. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12597. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12598. } );
  12599. }
  12600. // project the worldpos
  12601. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12602. // shift the depth of the projected points so the line
  12603. // segments overlap neatly
  12604. const clipPose = vec3().toVar();
  12605. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12606. clip.z.assign( clipPose.z.mul( clip.w ) );
  12607. } else {
  12608. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12609. // undo aspect ratio adjustment
  12610. dir.x.assign( dir.x.div( aspect ) );
  12611. offset.x.assign( offset.x.div( aspect ) );
  12612. // sign flip
  12613. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12614. // endcaps
  12615. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12616. offset.assign( offset.sub( dir ) );
  12617. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12618. offset.assign( offset.add( dir ) );
  12619. } );
  12620. // adjust for linewidth
  12621. offset.assign( offset.mul( materialLineWidth ) );
  12622. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12623. offset.assign( offset.div( viewport.w ) );
  12624. // select end
  12625. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12626. // back to clip space
  12627. offset.assign( offset.mul( clip.w ) );
  12628. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12629. }
  12630. return clip;
  12631. } )();
  12632. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12633. const p13 = p1.sub( p3 );
  12634. const p43 = p4.sub( p3 );
  12635. const p21 = p2.sub( p1 );
  12636. const d1343 = p13.dot( p43 );
  12637. const d4321 = p43.dot( p21 );
  12638. const d1321 = p13.dot( p21 );
  12639. const d4343 = p43.dot( p43 );
  12640. const d2121 = p21.dot( p21 );
  12641. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12642. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12643. const mua = numer.div( denom ).clamp();
  12644. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12645. return vec2( mua, mub );
  12646. } );
  12647. this.colorNode = Fn( () => {
  12648. const vUv = uv();
  12649. if ( useDash ) {
  12650. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12651. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12652. dashSize.assign( dashSizeNode );
  12653. gapSize.assign( gapSizeNode );
  12654. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12655. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12656. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12657. }
  12658. const alpha = float( 1 ).toVar( 'alpha' );
  12659. if ( useWorldUnits ) {
  12660. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12661. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12662. // Find the closest points on the view ray and the line segment
  12663. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12664. const lineDir = worldEnd.sub( worldStart );
  12665. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12666. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12667. const p2 = rayEnd.mul( params.y );
  12668. const delta = p1.sub( p2 );
  12669. const len = delta.length();
  12670. const norm = len.div( materialLineWidth );
  12671. if ( ! useDash ) {
  12672. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12673. const dnorm = norm.fwidth();
  12674. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12675. } else {
  12676. norm.greaterThan( 0.5 ).discard();
  12677. }
  12678. }
  12679. } else {
  12680. // round endcaps
  12681. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12682. const a = vUv.x;
  12683. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12684. const len2 = a.mul( a ).add( b.mul( b ) );
  12685. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12686. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12687. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12688. } );
  12689. } else {
  12690. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12691. const a = vUv.x;
  12692. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12693. const len2 = a.mul( a ).add( b.mul( b ) );
  12694. len2.greaterThan( 1.0 ).discard();
  12695. } );
  12696. }
  12697. }
  12698. let lineColorNode;
  12699. if ( this.lineColorNode ) {
  12700. lineColorNode = this.lineColorNode;
  12701. } else {
  12702. if ( useColor ) {
  12703. const instanceColorStart = attribute( 'instanceColorStart' );
  12704. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12705. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12706. lineColorNode = instanceColor.mul( materialColor );
  12707. } else {
  12708. lineColorNode = materialColor;
  12709. }
  12710. }
  12711. return vec4( lineColorNode, alpha );
  12712. } )();
  12713. if ( this.transparent ) {
  12714. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12715. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12716. }
  12717. super.setup( builder );
  12718. }
  12719. /**
  12720. * Whether the lines should sized in world units or not.
  12721. * When set to `false` the unit is pixel.
  12722. *
  12723. * @type {boolean}
  12724. * @default false
  12725. */
  12726. get worldUnits() {
  12727. return this._useWorldUnits;
  12728. }
  12729. set worldUnits( value ) {
  12730. if ( this._useWorldUnits !== value ) {
  12731. this._useWorldUnits = value;
  12732. this.needsUpdate = true;
  12733. }
  12734. }
  12735. /**
  12736. * Whether the lines should be dashed or not.
  12737. *
  12738. * @type {boolean}
  12739. * @default false
  12740. */
  12741. get dashed() {
  12742. return this._useDash;
  12743. }
  12744. set dashed( value ) {
  12745. if ( this._useDash !== value ) {
  12746. this._useDash = value;
  12747. this.needsUpdate = true;
  12748. }
  12749. }
  12750. /**
  12751. * Whether alpha to coverage should be used or not.
  12752. *
  12753. * @type {boolean}
  12754. * @default true
  12755. */
  12756. get alphaToCoverage() {
  12757. return this._useAlphaToCoverage;
  12758. }
  12759. set alphaToCoverage( value ) {
  12760. if ( this._useAlphaToCoverage !== value ) {
  12761. this._useAlphaToCoverage = value;
  12762. this.needsUpdate = true;
  12763. }
  12764. }
  12765. }
  12766. /**
  12767. * Packs a direction vector into a color value.
  12768. *
  12769. * @tsl
  12770. * @function
  12771. * @param {Node<vec3>} node - The direction to pack.
  12772. * @return {Node<vec3>} The color.
  12773. */
  12774. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12775. /**
  12776. * Unpacks a color value into a direction vector.
  12777. *
  12778. * @tsl
  12779. * @function
  12780. * @param {Node<vec3>} node - The color to unpack.
  12781. * @return {Node<vec3>} The direction.
  12782. */
  12783. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12784. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12785. /**
  12786. * Node material version of `MeshNormalMaterial`.
  12787. *
  12788. * @augments NodeMaterial
  12789. */
  12790. class MeshNormalNodeMaterial extends NodeMaterial {
  12791. static get type() {
  12792. return 'MeshNormalNodeMaterial';
  12793. }
  12794. /**
  12795. * Constructs a new mesh normal node material.
  12796. *
  12797. * @param {?Object} parameters - The configuration parameter.
  12798. */
  12799. constructor( parameters ) {
  12800. super();
  12801. /**
  12802. * This flag can be used for type testing.
  12803. *
  12804. * @type {boolean}
  12805. * @readonly
  12806. * @default true
  12807. */
  12808. this.isMeshNormalNodeMaterial = true;
  12809. this.setDefaultValues( _defaultValues$a );
  12810. this.setValues( parameters );
  12811. }
  12812. /**
  12813. * Overwrites the default implementation by computing the diffuse color
  12814. * based on the normal data.
  12815. */
  12816. setupDiffuseColor() {
  12817. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12818. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12819. }
  12820. }
  12821. /**
  12822. * Can be used to compute texture coordinates for projecting an
  12823. * equirectangular texture onto a mesh for using it as the scene's
  12824. * background.
  12825. *
  12826. * ```js
  12827. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12828. * ```
  12829. *
  12830. * @augments TempNode
  12831. */
  12832. class EquirectUVNode extends TempNode {
  12833. static get type() {
  12834. return 'EquirectUVNode';
  12835. }
  12836. /**
  12837. * Constructs a new equirect uv node.
  12838. *
  12839. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12840. */
  12841. constructor( dirNode = positionWorldDirection ) {
  12842. super( 'vec2' );
  12843. /**
  12844. * A direction vector for sampling why is by default `positionWorldDirection`.
  12845. *
  12846. * @type {Node<vec3>}
  12847. */
  12848. this.dirNode = dirNode;
  12849. }
  12850. setup() {
  12851. const dir = this.dirNode;
  12852. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12853. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12854. return vec2( u, v );
  12855. }
  12856. }
  12857. /**
  12858. * TSL function for creating an equirect uv node.
  12859. *
  12860. * @tsl
  12861. * @function
  12862. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12863. * @returns {EquirectUVNode}
  12864. */
  12865. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12866. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12867. /**
  12868. * This class represents a cube render target. It is a special version
  12869. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12870. *
  12871. * @augments WebGLCubeRenderTarget
  12872. */
  12873. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12874. constructor( size = 1, options = {} ) {
  12875. super( size, options );
  12876. this.isCubeRenderTarget = true;
  12877. }
  12878. /**
  12879. * Converts the given equirectangular texture to a cube map.
  12880. *
  12881. * @param {Renderer} renderer - The renderer.
  12882. * @param {Texture} texture - The equirectangular texture.
  12883. * @return {CubeRenderTarget} A reference to this cube render target.
  12884. */
  12885. fromEquirectangularTexture( renderer, texture$1 ) {
  12886. const currentMinFilter = texture$1.minFilter;
  12887. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12888. texture$1.generateMipmaps = true;
  12889. this.texture.type = texture$1.type;
  12890. this.texture.colorSpace = texture$1.colorSpace;
  12891. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12892. this.texture.minFilter = texture$1.minFilter;
  12893. this.texture.magFilter = texture$1.magFilter;
  12894. const geometry = new BoxGeometry( 5, 5, 5 );
  12895. const uvNode = equirectUV( positionWorldDirection );
  12896. const material = new NodeMaterial();
  12897. material.colorNode = texture( texture$1, uvNode, 0 );
  12898. material.side = BackSide;
  12899. material.blending = NoBlending;
  12900. const mesh = new Mesh( geometry, material );
  12901. const scene = new Scene();
  12902. scene.add( mesh );
  12903. // Avoid blurred poles
  12904. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12905. const camera = new CubeCamera( 1, 10, this );
  12906. const currentMRT = renderer.getMRT();
  12907. renderer.setMRT( null );
  12908. camera.update( renderer, scene );
  12909. renderer.setMRT( currentMRT );
  12910. texture$1.minFilter = currentMinFilter;
  12911. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12912. mesh.geometry.dispose();
  12913. mesh.material.dispose();
  12914. return this;
  12915. }
  12916. }
  12917. const _cache$1 = new WeakMap();
  12918. /**
  12919. * This node can be used to automatically convert environment maps in the
  12920. * equirectangular format into the cube map format.
  12921. *
  12922. * @augments TempNode
  12923. */
  12924. class CubeMapNode extends TempNode {
  12925. static get type() {
  12926. return 'CubeMapNode';
  12927. }
  12928. /**
  12929. * Constructs a new cube map node.
  12930. *
  12931. * @param {Node} envNode - The node representing the environment map.
  12932. */
  12933. constructor( envNode ) {
  12934. super( 'vec3' );
  12935. /**
  12936. * The node representing the environment map.
  12937. *
  12938. * @type {Node}
  12939. */
  12940. this.envNode = envNode;
  12941. /**
  12942. * A reference to the internal cube texture.
  12943. *
  12944. * @private
  12945. * @type {CubeTexture}
  12946. * @default null
  12947. */
  12948. this._cubeTexture = null;
  12949. /**
  12950. * A reference to the internal cube texture node.
  12951. *
  12952. * @private
  12953. * @type {CubeTextureNode}
  12954. */
  12955. this._cubeTextureNode = cubeTexture();
  12956. const defaultTexture = new CubeTexture();
  12957. defaultTexture.isRenderTargetTexture = true;
  12958. /**
  12959. * A default cube texture that acts as a placeholder.
  12960. * It is used when the conversion from equirectangular to cube
  12961. * map has not finished yet for a given texture.
  12962. *
  12963. * @private
  12964. * @type {CubeTexture}
  12965. */
  12966. this._defaultTexture = defaultTexture;
  12967. /**
  12968. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12969. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12970. *
  12971. * @type {string}
  12972. * @default 'render'
  12973. */
  12974. this.updateBeforeType = NodeUpdateType.RENDER;
  12975. }
  12976. updateBefore( frame ) {
  12977. const { renderer, material } = frame;
  12978. const envNode = this.envNode;
  12979. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12980. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12981. if ( texture && texture.isTexture ) {
  12982. const mapping = texture.mapping;
  12983. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12984. // check for converted cubemap map
  12985. if ( _cache$1.has( texture ) ) {
  12986. const cubeMap = _cache$1.get( texture );
  12987. mapTextureMapping( cubeMap, texture.mapping );
  12988. this._cubeTexture = cubeMap;
  12989. } else {
  12990. // create cube map from equirectangular map
  12991. const image = texture.image;
  12992. if ( isEquirectangularMapReady$1( image ) ) {
  12993. const renderTarget = new CubeRenderTarget( image.height );
  12994. renderTarget.fromEquirectangularTexture( renderer, texture );
  12995. mapTextureMapping( renderTarget.texture, texture.mapping );
  12996. this._cubeTexture = renderTarget.texture;
  12997. _cache$1.set( texture, renderTarget.texture );
  12998. texture.addEventListener( 'dispose', onTextureDispose );
  12999. } else {
  13000. // default cube texture as fallback when equirectangular texture is not yet loaded
  13001. this._cubeTexture = this._defaultTexture;
  13002. }
  13003. }
  13004. //
  13005. this._cubeTextureNode.value = this._cubeTexture;
  13006. } else {
  13007. // envNode already refers to a cube map
  13008. this._cubeTextureNode = this.envNode;
  13009. }
  13010. }
  13011. }
  13012. }
  13013. setup( builder ) {
  13014. this.updateBefore( builder );
  13015. return this._cubeTextureNode;
  13016. }
  13017. }
  13018. /**
  13019. * Returns true if the given equirectangular image has been fully loaded
  13020. * and is ready for further processing.
  13021. *
  13022. * @private
  13023. * @param {Image} image - The equirectangular image to check.
  13024. * @return {boolean} Whether the image is ready or not.
  13025. */
  13026. function isEquirectangularMapReady$1( image ) {
  13027. if ( image === null || image === undefined ) return false;
  13028. return image.height > 0;
  13029. }
  13030. /**
  13031. * This function is executed when `dispose()` is called on the equirectangular
  13032. * texture. In this case, the generated cube map with its render target
  13033. * is deleted as well.
  13034. *
  13035. * @private
  13036. * @param {Object} event - The event object.
  13037. */
  13038. function onTextureDispose( event ) {
  13039. const texture = event.target;
  13040. texture.removeEventListener( 'dispose', onTextureDispose );
  13041. const renderTarget = _cache$1.get( texture );
  13042. if ( renderTarget !== undefined ) {
  13043. _cache$1.delete( texture );
  13044. renderTarget.dispose();
  13045. }
  13046. }
  13047. /**
  13048. * This function makes sure the generated cube map uses the correct
  13049. * texture mapping that corresponds to the equirectangular original.
  13050. *
  13051. * @private
  13052. * @param {Texture} texture - The cube texture.
  13053. * @param {number} mapping - The original texture mapping.
  13054. */
  13055. function mapTextureMapping( texture, mapping ) {
  13056. if ( mapping === EquirectangularReflectionMapping ) {
  13057. texture.mapping = CubeReflectionMapping;
  13058. } else if ( mapping === EquirectangularRefractionMapping ) {
  13059. texture.mapping = CubeRefractionMapping;
  13060. }
  13061. }
  13062. /**
  13063. * TSL function for creating a cube map node.
  13064. *
  13065. * @tsl
  13066. * @function
  13067. * @param {Node} envNode - The node representing the environment map.
  13068. * @returns {CubeMapNode}
  13069. */
  13070. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  13071. /**
  13072. * Represents a basic model for Image-based lighting (IBL). The environment
  13073. * is defined via environment maps in the equirectangular or cube map format.
  13074. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  13075. * or {@link MeshPhongNodeMaterial}.
  13076. *
  13077. * @augments LightingNode
  13078. */
  13079. class BasicEnvironmentNode extends LightingNode {
  13080. static get type() {
  13081. return 'BasicEnvironmentNode';
  13082. }
  13083. /**
  13084. * Constructs a new basic environment node.
  13085. *
  13086. * @param {Node} [envNode=null] - A node representing the environment.
  13087. */
  13088. constructor( envNode = null ) {
  13089. super();
  13090. /**
  13091. * A node representing the environment.
  13092. *
  13093. * @type {Node}
  13094. * @default null
  13095. */
  13096. this.envNode = envNode;
  13097. }
  13098. setup( builder ) {
  13099. // environment property is used in the finish() method of BasicLightingModel
  13100. builder.context.environment = cubeMapNode( this.envNode );
  13101. }
  13102. }
  13103. /**
  13104. * A specific version of {@link IrradianceNode} that is only relevant
  13105. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  13106. * requires a special scaling factor for the light map.
  13107. *
  13108. * @augments LightingNode
  13109. */
  13110. class BasicLightMapNode extends LightingNode {
  13111. static get type() {
  13112. return 'BasicLightMapNode';
  13113. }
  13114. /**
  13115. * Constructs a new basic light map node.
  13116. *
  13117. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  13118. */
  13119. constructor( lightMapNode = null ) {
  13120. super();
  13121. /**
  13122. * The light map node.
  13123. *
  13124. * @type {?Node<vec3>}
  13125. */
  13126. this.lightMapNode = lightMapNode;
  13127. }
  13128. setup( builder ) {
  13129. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  13130. const RECIPROCAL_PI = float( 1 / Math.PI );
  13131. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  13132. }
  13133. }
  13134. /**
  13135. * Abstract class for implementing lighting models. The module defines
  13136. * multiple methods that concrete lighting models can implement. These
  13137. * methods are executed at different points during the light evaluation
  13138. * process.
  13139. */
  13140. class LightingModel {
  13141. /**
  13142. * This method is intended for setting up lighting model and context data
  13143. * which are later used in the evaluation process.
  13144. *
  13145. * @abstract
  13146. * @param {ContextNode} input - The current node context.
  13147. * @param {StackNode} stack - The current stack.
  13148. * @param {NodeBuilder} builder - The current node builder.
  13149. */
  13150. start( /*input, stack, builder*/ ) { }
  13151. /**
  13152. * This method is intended for executing final tasks like final updates
  13153. * to the outgoing light.
  13154. *
  13155. * @abstract
  13156. * @param {ContextNode} input - The current node context.
  13157. * @param {StackNode} stack - The current stack.
  13158. * @param {NodeBuilder} builder - The current node builder.
  13159. */
  13160. finish( /*input, stack, builder*/ ) { }
  13161. /**
  13162. * This method is intended for implementing the direct light term and
  13163. * executed during the build process of directional, point and spot light nodes.
  13164. *
  13165. * @abstract
  13166. * @param {Object} input - The input data.
  13167. * @param {StackNode} stack - The current stack.
  13168. * @param {NodeBuilder} builder - The current node builder.
  13169. */
  13170. direct( /*input, stack, builder*/ ) { }
  13171. /**
  13172. * This method is intended for implementing the direct light term for
  13173. * rect area light nodes.
  13174. *
  13175. * @abstract
  13176. * @param {Object} input - The input data.
  13177. * @param {StackNode} stack - The current stack.
  13178. * @param {NodeBuilder} builder - The current node builder.
  13179. */
  13180. directRectArea( /*input, stack, builder*/ ) {}
  13181. /**
  13182. * This method is intended for implementing the indirect light term.
  13183. *
  13184. * @abstract
  13185. * @param {ContextNode} input - The current node context.
  13186. * @param {StackNode} stack - The current stack.
  13187. * @param {NodeBuilder} builder - The current node builder.
  13188. */
  13189. indirect( /*input, stack, builder*/ ) { }
  13190. /**
  13191. * This method is intended for implementing the ambient occlusion term.
  13192. * Unlike other methods, this method must be called manually by the lighting
  13193. * model in its indirect term.
  13194. *
  13195. * @abstract
  13196. * @param {ContextNode} input - The current node context.
  13197. * @param {StackNode} stack - The current stack.
  13198. * @param {NodeBuilder} builder - The current node builder.
  13199. */
  13200. ambientOcclusion( /*input, stack, builder*/ ) { }
  13201. }
  13202. /**
  13203. * Represents the lighting model for unlit materials. The only light contribution
  13204. * is baked indirect lighting modulated with ambient occlusion and the material's
  13205. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  13206. *
  13207. * @augments LightingModel
  13208. */
  13209. class BasicLightingModel extends LightingModel {
  13210. /**
  13211. * Constructs a new basic lighting model.
  13212. */
  13213. constructor() {
  13214. super();
  13215. }
  13216. /**
  13217. * Implements the baked indirect lighting with its modulation.
  13218. *
  13219. * @param {ContextNode} context - The current node context.
  13220. * @param {StackNode} stack - The current stack.
  13221. * @param {NodeBuilder} builder - The current node builder.
  13222. */
  13223. indirect( context, stack, builder ) {
  13224. const ambientOcclusion = context.ambientOcclusion;
  13225. const reflectedLight = context.reflectedLight;
  13226. const irradianceLightMap = builder.context.irradianceLightMap;
  13227. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  13228. // accumulation (baked indirect lighting only)
  13229. if ( irradianceLightMap ) {
  13230. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  13231. } else {
  13232. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  13233. }
  13234. // modulation
  13235. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13236. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  13237. }
  13238. /**
  13239. * Implements the environment mapping.
  13240. *
  13241. * @param {ContextNode} context - The current node context.
  13242. * @param {StackNode} stack - The current stack.
  13243. * @param {NodeBuilder} builder - The current node builder.
  13244. */
  13245. finish( context, stack, builder ) {
  13246. const material = builder.material;
  13247. const outgoingLight = context.outgoingLight;
  13248. const envNode = builder.context.environment;
  13249. if ( envNode ) {
  13250. switch ( material.combine ) {
  13251. case MultiplyOperation:
  13252. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  13253. break;
  13254. case MixOperation:
  13255. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  13256. break;
  13257. case AddOperation:
  13258. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  13259. break;
  13260. default:
  13261. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  13262. break;
  13263. }
  13264. }
  13265. }
  13266. }
  13267. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  13268. /**
  13269. * Node material version of `MeshBasicMaterial`.
  13270. *
  13271. * @augments NodeMaterial
  13272. */
  13273. class MeshBasicNodeMaterial extends NodeMaterial {
  13274. static get type() {
  13275. return 'MeshBasicNodeMaterial';
  13276. }
  13277. /**
  13278. * Constructs a new mesh basic node material.
  13279. *
  13280. * @param {?Object} parameters - The configuration parameter.
  13281. */
  13282. constructor( parameters ) {
  13283. super();
  13284. /**
  13285. * This flag can be used for type testing.
  13286. *
  13287. * @type {boolean}
  13288. * @readonly
  13289. * @default true
  13290. */
  13291. this.isMeshBasicNodeMaterial = true;
  13292. /**
  13293. * Although the basic material is by definition unlit, we set
  13294. * this property to `true` since we use a lighting model to compute
  13295. * the outgoing light of the fragment shader.
  13296. *
  13297. * @type {boolean}
  13298. * @default true
  13299. */
  13300. this.lights = true;
  13301. this.setDefaultValues( _defaultValues$9 );
  13302. this.setValues( parameters );
  13303. }
  13304. /**
  13305. * Basic materials are not affected by normal and bump maps so we
  13306. * return by default {@link normalView}.
  13307. *
  13308. * @return {Node<vec3>} The normal node.
  13309. */
  13310. setupNormal() {
  13311. return normalView; // see #28839
  13312. }
  13313. /**
  13314. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13315. * to implement the default environment mapping.
  13316. *
  13317. * @param {NodeBuilder} builder - The current node builder.
  13318. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13319. */
  13320. setupEnvironment( builder ) {
  13321. const envNode = super.setupEnvironment( builder );
  13322. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13323. }
  13324. /**
  13325. * This method must be overwritten since light maps are evaluated
  13326. * with a special scaling factor for basic materials.
  13327. *
  13328. * @param {NodeBuilder} builder - The current node builder.
  13329. * @return {?BasicLightMapNode<vec3>} The light map node.
  13330. */
  13331. setupLightMap( builder ) {
  13332. let node = null;
  13333. if ( builder.material.lightMap ) {
  13334. node = new BasicLightMapNode( materialLightMap );
  13335. }
  13336. return node;
  13337. }
  13338. /**
  13339. * The material overwrites this method because `lights` is set to `true` but
  13340. * we still want to return the diffuse color as the outgoing light.
  13341. *
  13342. * @return {Node<vec3>} The outgoing light node.
  13343. */
  13344. setupOutgoingLight() {
  13345. return diffuseColor.rgb;
  13346. }
  13347. /**
  13348. * Setups the lighting model.
  13349. *
  13350. * @return {BasicLightingModel} The lighting model.
  13351. */
  13352. setupLightingModel() {
  13353. return new BasicLightingModel();
  13354. }
  13355. }
  13356. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  13357. // Original approximation by Christophe Schlick '94
  13358. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  13359. // Optimized variant (presented by Epic at SIGGRAPH '13)
  13360. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  13361. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  13362. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  13363. } ); // validated
  13364. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  13365. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  13366. } ); // validated
  13367. const G_BlinnPhong_Implicit = () => float( 0.25 );
  13368. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  13369. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  13370. } );
  13371. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13372. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13373. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13374. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13375. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  13376. const G = G_BlinnPhong_Implicit();
  13377. const D = D_BlinnPhong( { dotNH } );
  13378. return F.mul( G ).mul( D );
  13379. } );
  13380. /**
  13381. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  13382. *
  13383. * @augments BasicLightingModel
  13384. */
  13385. class PhongLightingModel extends BasicLightingModel {
  13386. /**
  13387. * Constructs a new phong lighting model.
  13388. *
  13389. * @param {boolean} [specular=true] - Whether specular is supported or not.
  13390. */
  13391. constructor( specular = true ) {
  13392. super();
  13393. /**
  13394. * Whether specular is supported or not. Set this to `false` if you are
  13395. * looking for a Lambert-like material meaning a material for non-shiny
  13396. * surfaces, without specular highlights.
  13397. *
  13398. * @type {boolean}
  13399. * @default true
  13400. */
  13401. this.specular = specular;
  13402. }
  13403. /**
  13404. * Implements the direct lighting. The specular portion is optional an can be controlled
  13405. * with the {@link PhongLightingModel#specular} flag.
  13406. *
  13407. * @param {Object} input - The input data.
  13408. * @param {StackNode} stack - The current stack.
  13409. * @param {NodeBuilder} builder - The current node builder.
  13410. */
  13411. direct( { lightDirection, lightColor, reflectedLight } ) {
  13412. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13413. const irradiance = dotNL.mul( lightColor );
  13414. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13415. if ( this.specular === true ) {
  13416. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  13417. }
  13418. }
  13419. /**
  13420. * Implements the indirect lighting.
  13421. *
  13422. * @param {ContextNode} input - The current node context.
  13423. * @param {StackNode} stack - The current stack.
  13424. * @param {NodeBuilder} builder - The current node builder.
  13425. */
  13426. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  13427. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13428. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13429. }
  13430. }
  13431. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  13432. /**
  13433. * Node material version of `MeshLambertMaterial`.
  13434. *
  13435. * @augments NodeMaterial
  13436. */
  13437. class MeshLambertNodeMaterial extends NodeMaterial {
  13438. static get type() {
  13439. return 'MeshLambertNodeMaterial';
  13440. }
  13441. /**
  13442. * Constructs a new mesh lambert node material.
  13443. *
  13444. * @param {?Object} parameters - The configuration parameter.
  13445. */
  13446. constructor( parameters ) {
  13447. super();
  13448. /**
  13449. * This flag can be used for type testing.
  13450. *
  13451. * @type {boolean}
  13452. * @readonly
  13453. * @default true
  13454. */
  13455. this.isMeshLambertNodeMaterial = true;
  13456. /**
  13457. * Set to `true` because lambert materials react on lights.
  13458. *
  13459. * @type {boolean}
  13460. * @default true
  13461. */
  13462. this.lights = true;
  13463. this.setDefaultValues( _defaultValues$8 );
  13464. this.setValues( parameters );
  13465. }
  13466. /**
  13467. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13468. * to implement the default environment mapping.
  13469. *
  13470. * @param {NodeBuilder} builder - The current node builder.
  13471. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13472. */
  13473. setupEnvironment( builder ) {
  13474. const envNode = super.setupEnvironment( builder );
  13475. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13476. }
  13477. /**
  13478. * Setups the lighting model.
  13479. *
  13480. * @return {PhongLightingModel} The lighting model.
  13481. */
  13482. setupLightingModel( /*builder*/ ) {
  13483. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13484. }
  13485. }
  13486. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13487. /**
  13488. * Node material version of `MeshPhongMaterial`.
  13489. *
  13490. * @augments NodeMaterial
  13491. */
  13492. class MeshPhongNodeMaterial extends NodeMaterial {
  13493. static get type() {
  13494. return 'MeshPhongNodeMaterial';
  13495. }
  13496. /**
  13497. * Constructs a new mesh lambert node material.
  13498. *
  13499. * @param {?Object} parameters - The configuration parameter.
  13500. */
  13501. constructor( parameters ) {
  13502. super();
  13503. /**
  13504. * This flag can be used for type testing.
  13505. *
  13506. * @type {boolean}
  13507. * @readonly
  13508. * @default true
  13509. */
  13510. this.isMeshPhongNodeMaterial = true;
  13511. /**
  13512. * Set to `true` because phong materials react on lights.
  13513. *
  13514. * @type {boolean}
  13515. * @default true
  13516. */
  13517. this.lights = true;
  13518. /**
  13519. * The shininess of phong materials is by default inferred from the `shininess`
  13520. * property. This node property allows to overwrite the default
  13521. * and define the shininess with a node instead.
  13522. *
  13523. * If you don't want to overwrite the shininess but modify the existing
  13524. * value instead, use {@link materialShininess}.
  13525. *
  13526. * @type {?Node<float>}
  13527. * @default null
  13528. */
  13529. this.shininessNode = null;
  13530. /**
  13531. * The specular color of phong materials is by default inferred from the
  13532. * `specular` property. This node property allows to overwrite the default
  13533. * and define the specular color with a node instead.
  13534. *
  13535. * If you don't want to overwrite the specular color but modify the existing
  13536. * value instead, use {@link materialSpecular}.
  13537. *
  13538. * @type {?Node<vec3>}
  13539. * @default null
  13540. */
  13541. this.specularNode = null;
  13542. this.setDefaultValues( _defaultValues$7 );
  13543. this.setValues( parameters );
  13544. }
  13545. /**
  13546. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13547. * to implement the default environment mapping.
  13548. *
  13549. * @param {NodeBuilder} builder - The current node builder.
  13550. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13551. */
  13552. setupEnvironment( builder ) {
  13553. const envNode = super.setupEnvironment( builder );
  13554. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13555. }
  13556. /**
  13557. * Setups the lighting model.
  13558. *
  13559. * @return {PhongLightingModel} The lighting model.
  13560. */
  13561. setupLightingModel( /*builder*/ ) {
  13562. return new PhongLightingModel();
  13563. }
  13564. /**
  13565. * Setups the phong specific node variables.
  13566. *
  13567. * @param {NodeBuilder} builder - The current node builder.
  13568. */
  13569. setupVariants( /*builder*/ ) {
  13570. // SHININESS
  13571. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13572. shininess.assign( shininessNode );
  13573. // SPECULAR COLOR
  13574. const specularNode = this.specularNode || materialSpecular;
  13575. specularColor.assign( specularNode );
  13576. }
  13577. copy( source ) {
  13578. this.shininessNode = source.shininessNode;
  13579. this.specularNode = source.specularNode;
  13580. return super.copy( source );
  13581. }
  13582. }
  13583. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13584. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13585. return float( 0 );
  13586. }
  13587. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13588. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13589. return geometryRoughness;
  13590. } );
  13591. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13592. const { roughness } = inputs;
  13593. const geometryRoughness = getGeometryRoughness();
  13594. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13595. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13596. roughnessFactor = roughnessFactor.min( 1.0 );
  13597. return roughnessFactor;
  13598. } );
  13599. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13600. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13601. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13602. const a2 = alpha.pow2();
  13603. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13604. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13605. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13606. } ).setLayout( {
  13607. name: 'V_GGX_SmithCorrelated',
  13608. type: 'float',
  13609. inputs: [
  13610. { name: 'alpha', type: 'float' },
  13611. { name: 'dotNL', type: 'float' },
  13612. { name: 'dotNV', type: 'float' }
  13613. ]
  13614. } ); // validated
  13615. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13616. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13617. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13618. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13619. const v = div( 0.5, gv.add( gl ) );
  13620. return v.saturate();
  13621. } ).setLayout( {
  13622. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13623. type: 'float',
  13624. inputs: [
  13625. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13626. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13627. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13628. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13629. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13630. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13631. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13632. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13633. ]
  13634. } );
  13635. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13636. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13637. // alpha is "roughness squared" in Disney’s reparameterization
  13638. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13639. const a2 = alpha.pow2();
  13640. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13641. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13642. } ).setLayout( {
  13643. name: 'D_GGX',
  13644. type: 'float',
  13645. inputs: [
  13646. { name: 'alpha', type: 'float' },
  13647. { name: 'dotNH', type: 'float' }
  13648. ]
  13649. } ); // validated
  13650. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13651. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13652. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13653. const a2 = alphaT.mul( alphaB );
  13654. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13655. const v2 = v.dot( v );
  13656. const w2 = a2.div( v2 );
  13657. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13658. } ).setLayout( {
  13659. name: 'D_GGX_Anisotropic',
  13660. type: 'float',
  13661. inputs: [
  13662. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13663. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13664. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13665. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13666. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13667. ]
  13668. } );
  13669. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13670. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13671. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13672. const normalView = inputs.normalView || transformedNormalView;
  13673. const alpha = roughness.pow2(); // UE4's roughness
  13674. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13675. const dotNL = normalView.dot( lightDirection ).clamp();
  13676. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13677. const dotNH = normalView.dot( halfDir ).clamp();
  13678. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13679. let F = F_Schlick( { f0, f90, dotVH } );
  13680. let V, D;
  13681. if ( defined( USE_IRIDESCENCE ) ) {
  13682. F = iridescence.mix( F, f );
  13683. }
  13684. if ( defined( USE_ANISOTROPY ) ) {
  13685. const dotTL = anisotropyT.dot( lightDirection );
  13686. const dotTV = anisotropyT.dot( positionViewDirection );
  13687. const dotTH = anisotropyT.dot( halfDir );
  13688. const dotBL = anisotropyB.dot( lightDirection );
  13689. const dotBV = anisotropyB.dot( positionViewDirection );
  13690. const dotBH = anisotropyB.dot( halfDir );
  13691. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13692. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13693. } else {
  13694. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13695. D = D_GGX( { alpha, dotNH } );
  13696. }
  13697. return F.mul( V ).mul( D );
  13698. } ); // validated
  13699. // Analytical approximation of the DFG LUT, one half of the
  13700. // split-sum approximation used in indirect specular lighting.
  13701. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13702. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13703. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13704. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  13705. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  13706. const r = roughness.mul( c0 ).add( c1 );
  13707. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  13708. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  13709. return fab;
  13710. } ).setLayout( {
  13711. name: 'DFGApprox',
  13712. type: 'vec2',
  13713. inputs: [
  13714. { name: 'roughness', type: 'float' },
  13715. { name: 'dotNV', type: 'vec3' }
  13716. ]
  13717. } );
  13718. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13719. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13720. const fab = DFGApprox( { dotNV, roughness } );
  13721. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13722. } );
  13723. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13724. const x = dotVH.oneMinus().saturate();
  13725. const x2 = x.mul( x );
  13726. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13727. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13728. } ).setLayout( {
  13729. name: 'Schlick_to_F0',
  13730. type: 'vec3',
  13731. inputs: [
  13732. { name: 'f', type: 'vec3' },
  13733. { name: 'f90', type: 'float' },
  13734. { name: 'dotVH', type: 'float' }
  13735. ]
  13736. } );
  13737. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13738. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13739. const alpha = roughness.pow2();
  13740. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13741. const invAlpha = float( 1.0 ).div( alpha );
  13742. const cos2h = dotNH.pow2();
  13743. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13744. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13745. } ).setLayout( {
  13746. name: 'D_Charlie',
  13747. type: 'float',
  13748. inputs: [
  13749. { name: 'roughness', type: 'float' },
  13750. { name: 'dotNH', type: 'float' }
  13751. ]
  13752. } );
  13753. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13754. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13755. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13756. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13757. } ).setLayout( {
  13758. name: 'V_Neubelt',
  13759. type: 'float',
  13760. inputs: [
  13761. { name: 'dotNV', type: 'float' },
  13762. { name: 'dotNL', type: 'float' }
  13763. ]
  13764. } );
  13765. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13766. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13767. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13768. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13769. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13770. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13771. const V = V_Neubelt( { dotNV, dotNL } );
  13772. return sheen.mul( D ).mul( V );
  13773. } );
  13774. // Rect Area Light
  13775. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13776. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13777. // code: https://github.com/selfshadow/ltc_code/
  13778. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13779. const LUT_SIZE = 64.0;
  13780. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13781. const LUT_BIAS = 0.5 / LUT_SIZE;
  13782. const dotNV = N.dot( V ).saturate();
  13783. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13784. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13785. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13786. return uv;
  13787. } ).setLayout( {
  13788. name: 'LTC_Uv',
  13789. type: 'vec2',
  13790. inputs: [
  13791. { name: 'N', type: 'vec3' },
  13792. { name: 'V', type: 'vec3' },
  13793. { name: 'roughness', type: 'float' }
  13794. ]
  13795. } );
  13796. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13797. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13798. // An approximation of the form factor of a horizon-clipped rectangle.
  13799. const l = f.length();
  13800. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13801. } ).setLayout( {
  13802. name: 'LTC_ClippedSphereFormFactor',
  13803. type: 'float',
  13804. inputs: [
  13805. { name: 'f', type: 'vec3' }
  13806. ]
  13807. } );
  13808. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13809. const x = v1.dot( v2 );
  13810. const y = x.abs().toVar();
  13811. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13812. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13813. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13814. const v = a.div( b );
  13815. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13816. return v1.cross( v2 ).mul( theta_sintheta );
  13817. } ).setLayout( {
  13818. name: 'LTC_EdgeVectorFormFactor',
  13819. type: 'vec3',
  13820. inputs: [
  13821. { name: 'v1', type: 'vec3' },
  13822. { name: 'v2', type: 'vec3' }
  13823. ]
  13824. } );
  13825. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13826. // bail if point is on back side of plane of light
  13827. // assumes ccw winding order of light vertices
  13828. const v1 = p1.sub( p0 ).toVar();
  13829. const v2 = p3.sub( p0 ).toVar();
  13830. const lightNormal = v1.cross( v2 );
  13831. const result = vec3().toVar();
  13832. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13833. // construct orthonormal basis around N
  13834. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13835. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13836. // compute transform
  13837. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13838. // transform rect
  13839. // & project rect onto sphere
  13840. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13841. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13842. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13843. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13844. // calculate vector form factor
  13845. const vectorFormFactor = vec3( 0 ).toVar();
  13846. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13847. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13848. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13849. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13850. // adjust for horizon clipping
  13851. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13852. } );
  13853. return result;
  13854. } ).setLayout( {
  13855. name: 'LTC_Evaluate',
  13856. type: 'vec3',
  13857. inputs: [
  13858. { name: 'N', type: 'vec3' },
  13859. { name: 'V', type: 'vec3' },
  13860. { name: 'P', type: 'vec3' },
  13861. { name: 'mInv', type: 'mat3' },
  13862. { name: 'p0', type: 'vec3' },
  13863. { name: 'p1', type: 'vec3' },
  13864. { name: 'p2', type: 'vec3' },
  13865. { name: 'p3', type: 'vec3' }
  13866. ]
  13867. } );
  13868. // Mipped Bicubic Texture Filtering by N8
  13869. // https://www.shadertoy.com/view/Dl2SDW
  13870. const bC = 1.0 / 6.0;
  13871. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13872. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13873. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13874. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13875. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13876. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13877. // h0 and h1 are the two offset functions
  13878. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13879. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13880. const bicubic = ( textureNode, texelSize, lod ) => {
  13881. const uv = textureNode.uvNode;
  13882. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13883. const iuv = floor( uvScaled );
  13884. const fuv = fract( uvScaled );
  13885. const g0x = g0( fuv.x );
  13886. const g1x = g1( fuv.x );
  13887. const h0x = h0( fuv.x );
  13888. const h1x = h1( fuv.x );
  13889. const h0y = h0( fuv.y );
  13890. const h1y = h1( fuv.y );
  13891. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13892. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13893. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13894. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13895. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13896. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13897. return a.add( b );
  13898. };
  13899. /**
  13900. * Applies mipped bicubic texture filtering to the given texture node.
  13901. *
  13902. * @tsl
  13903. * @function
  13904. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13905. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13906. * @return {Node} The filtered texture sample.
  13907. */
  13908. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13909. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13910. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13911. const fLodSizeInv = div( 1.0, fLodSize );
  13912. const cLodSizeInv = div( 1.0, cLodSize );
  13913. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13914. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13915. return fract( lodNode ).mix( fSample, cSample );
  13916. } );
  13917. //
  13918. // Transmission
  13919. //
  13920. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13921. // Direction of refracted light.
  13922. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13923. // Compute rotation-independent scaling of the model matrix.
  13924. const modelScale = vec3(
  13925. length( modelMatrix[ 0 ].xyz ),
  13926. length( modelMatrix[ 1 ].xyz ),
  13927. length( modelMatrix[ 2 ].xyz )
  13928. );
  13929. // The thickness is specified in local space.
  13930. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13931. } ).setLayout( {
  13932. name: 'getVolumeTransmissionRay',
  13933. type: 'vec3',
  13934. inputs: [
  13935. { name: 'n', type: 'vec3' },
  13936. { name: 'v', type: 'vec3' },
  13937. { name: 'thickness', type: 'float' },
  13938. { name: 'ior', type: 'float' },
  13939. { name: 'modelMatrix', type: 'mat4' }
  13940. ]
  13941. } );
  13942. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13943. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13944. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13945. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13946. } ).setLayout( {
  13947. name: 'applyIorToRoughness',
  13948. type: 'float',
  13949. inputs: [
  13950. { name: 'roughness', type: 'float' },
  13951. { name: 'ior', type: 'float' }
  13952. ]
  13953. } );
  13954. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13955. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13956. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13957. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13958. const transmissionSample = vTexture.sample( fragCoord );
  13959. //const transmissionSample = viewportMipTexture( fragCoord );
  13960. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13961. return textureBicubic( transmissionSample, lod );
  13962. } );
  13963. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13964. If( attenuationDistance.notEqual( 0 ), () => {
  13965. // Compute light attenuation using Beer's law.
  13966. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13967. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13968. return transmittance;
  13969. } );
  13970. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13971. return vec3( 1.0 );
  13972. } ).setLayout( {
  13973. name: 'volumeAttenuation',
  13974. type: 'vec3',
  13975. inputs: [
  13976. { name: 'transmissionDistance', type: 'float' },
  13977. { name: 'attenuationColor', type: 'vec3' },
  13978. { name: 'attenuationDistance', type: 'float' }
  13979. ]
  13980. } );
  13981. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13982. let transmittedLight, transmittance;
  13983. if ( dispersion ) {
  13984. transmittedLight = vec4().toVar();
  13985. transmittance = vec3().toVar();
  13986. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13987. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13988. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13989. const ior = iors.element( i );
  13990. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13991. const refractedRayExit = position.add( transmissionRay );
  13992. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13993. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13994. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13995. refractionCoords.addAssign( 1.0 );
  13996. refractionCoords.divAssign( 2.0 );
  13997. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13998. // Sample framebuffer to get pixel the refracted ray hits.
  13999. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  14000. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  14001. transmittedLight.a.addAssign( transmissionSample.a );
  14002. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  14003. } );
  14004. transmittedLight.a.divAssign( 3.0 );
  14005. } else {
  14006. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  14007. const refractedRayExit = position.add( transmissionRay );
  14008. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  14009. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  14010. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  14011. refractionCoords.addAssign( 1.0 );
  14012. refractionCoords.divAssign( 2.0 );
  14013. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  14014. // Sample framebuffer to get pixel the refracted ray hits.
  14015. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  14016. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  14017. }
  14018. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  14019. const dotNV = n.dot( v ).clamp();
  14020. // Get the specular component.
  14021. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  14022. dotNV,
  14023. specularColor,
  14024. specularF90,
  14025. roughness
  14026. } ) );
  14027. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  14028. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  14029. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  14030. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  14031. } );
  14032. //
  14033. // Iridescence
  14034. //
  14035. // XYZ to linear-sRGB color space
  14036. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  14037. 3.2404542, -0.969266, 0.0556434,
  14038. -1.5371385, 1.8760108, -0.2040259,
  14039. -0.4985314, 0.0415560, 1.0572252
  14040. );
  14041. // Assume air interface for top
  14042. // Note: We don't handle the case fresnel0 == 1
  14043. const Fresnel0ToIor = ( fresnel0 ) => {
  14044. const sqrtF0 = fresnel0.sqrt();
  14045. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  14046. };
  14047. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  14048. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  14049. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  14050. };
  14051. // Fresnel equations for dielectric/dielectric interfaces.
  14052. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  14053. // Evaluation XYZ sensitivity curves in Fourier space
  14054. const evalSensitivity = ( OPD, shift ) => {
  14055. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  14056. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  14057. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  14058. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  14059. 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() );
  14060. 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() );
  14061. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  14062. const rgb = XYZ_TO_REC709.mul( xyz );
  14063. return rgb;
  14064. };
  14065. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  14066. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  14067. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  14068. // Evaluate the cosTheta on the base layer (Snell law)
  14069. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  14070. // Handle TIR:
  14071. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  14072. If( cosTheta2Sq.lessThan( 0 ), () => {
  14073. return vec3( 1.0 );
  14074. } );
  14075. const cosTheta2 = cosTheta2Sq.sqrt();
  14076. // First interface
  14077. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  14078. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  14079. //const R21 = R12;
  14080. const T121 = R12.oneMinus();
  14081. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  14082. const phi21 = float( Math.PI ).sub( phi12 );
  14083. // Second interface
  14084. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  14085. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  14086. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  14087. const phi23 = vec3(
  14088. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14089. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14090. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  14091. );
  14092. // Phase shift
  14093. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  14094. const phi = vec3( phi21 ).add( phi23 );
  14095. // Compound terms
  14096. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  14097. const r123 = R123.sqrt();
  14098. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  14099. // Reflectance term for m = 0 (DC term amplitude)
  14100. const C0 = R12.add( Rs );
  14101. const I = C0.toVar();
  14102. // Reflectance term for m > 0 (pairs of diracs)
  14103. const Cm = Rs.sub( T121 ).toVar();
  14104. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  14105. Cm.mulAssign( r123 );
  14106. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  14107. I.addAssign( Cm.mul( Sm ) );
  14108. } );
  14109. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  14110. return I.max( vec3( 0.0 ) );
  14111. } ).setLayout( {
  14112. name: 'evalIridescence',
  14113. type: 'vec3',
  14114. inputs: [
  14115. { name: 'outsideIOR', type: 'float' },
  14116. { name: 'eta2', type: 'float' },
  14117. { name: 'cosTheta1', type: 'float' },
  14118. { name: 'thinFilmThickness', type: 'float' },
  14119. { name: 'baseF0', type: 'vec3' }
  14120. ]
  14121. } );
  14122. //
  14123. // Sheen
  14124. //
  14125. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  14126. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  14127. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  14128. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  14129. const dotNV = normal.dot( viewDir ).saturate();
  14130. const r2 = roughness.pow2();
  14131. const a = select(
  14132. roughness.lessThan( 0.25 ),
  14133. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  14134. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  14135. );
  14136. const b = select(
  14137. roughness.lessThan( 0.25 ),
  14138. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  14139. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  14140. );
  14141. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  14142. return DG.mul( 1.0 / Math.PI ).saturate();
  14143. } );
  14144. const clearcoatF0 = vec3( 0.04 );
  14145. const clearcoatF90 = float( 1 );
  14146. /**
  14147. * Represents the lighting model for a PBR material.
  14148. *
  14149. * @augments LightingModel
  14150. */
  14151. class PhysicalLightingModel extends LightingModel {
  14152. /**
  14153. * Constructs a new physical lighting model.
  14154. *
  14155. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  14156. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  14157. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  14158. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  14159. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  14160. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  14161. */
  14162. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  14163. super();
  14164. /**
  14165. * Whether clearcoat is supported or not.
  14166. *
  14167. * @type {boolean}
  14168. * @default false
  14169. */
  14170. this.clearcoat = clearcoat;
  14171. /**
  14172. * Whether sheen is supported or not.
  14173. *
  14174. * @type {boolean}
  14175. * @default false
  14176. */
  14177. this.sheen = sheen;
  14178. /**
  14179. * Whether iridescence is supported or not.
  14180. *
  14181. * @type {boolean}
  14182. * @default false
  14183. */
  14184. this.iridescence = iridescence;
  14185. /**
  14186. * Whether anisotropy is supported or not.
  14187. *
  14188. * @type {boolean}
  14189. * @default false
  14190. */
  14191. this.anisotropy = anisotropy;
  14192. /**
  14193. * Whether transmission is supported or not.
  14194. *
  14195. * @type {boolean}
  14196. * @default false
  14197. */
  14198. this.transmission = transmission;
  14199. /**
  14200. * Whether dispersion is supported or not.
  14201. *
  14202. * @type {boolean}
  14203. * @default false
  14204. */
  14205. this.dispersion = dispersion;
  14206. /**
  14207. * The clear coat radiance.
  14208. *
  14209. * @type {?Node}
  14210. * @default null
  14211. */
  14212. this.clearcoatRadiance = null;
  14213. /**
  14214. * The clear coat specular direct.
  14215. *
  14216. * @type {?Node}
  14217. * @default null
  14218. */
  14219. this.clearcoatSpecularDirect = null;
  14220. /**
  14221. * The clear coat specular indirect.
  14222. *
  14223. * @type {?Node}
  14224. * @default null
  14225. */
  14226. this.clearcoatSpecularIndirect = null;
  14227. /**
  14228. * The sheen specular direct.
  14229. *
  14230. * @type {?Node}
  14231. * @default null
  14232. */
  14233. this.sheenSpecularDirect = null;
  14234. /**
  14235. * The sheen specular indirect.
  14236. *
  14237. * @type {?Node}
  14238. * @default null
  14239. */
  14240. this.sheenSpecularIndirect = null;
  14241. /**
  14242. * The iridescence Fresnel.
  14243. *
  14244. * @type {?Node}
  14245. * @default null
  14246. */
  14247. this.iridescenceFresnel = null;
  14248. /**
  14249. * The iridescence F0.
  14250. *
  14251. * @type {?Node}
  14252. * @default null
  14253. */
  14254. this.iridescenceF0 = null;
  14255. }
  14256. /**
  14257. * Depending on what features are requested, the method prepares certain node variables
  14258. * which are later used for lighting computations.
  14259. *
  14260. * @param {ContextNode} context - The current node context.
  14261. */
  14262. start( context ) {
  14263. if ( this.clearcoat === true ) {
  14264. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  14265. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  14266. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  14267. }
  14268. if ( this.sheen === true ) {
  14269. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  14270. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  14271. }
  14272. if ( this.iridescence === true ) {
  14273. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  14274. this.iridescenceFresnel = evalIridescence( {
  14275. outsideIOR: float( 1.0 ),
  14276. eta2: iridescenceIOR,
  14277. cosTheta1: dotNVi,
  14278. thinFilmThickness: iridescenceThickness,
  14279. baseF0: specularColor
  14280. } );
  14281. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  14282. }
  14283. if ( this.transmission === true ) {
  14284. const position = positionWorld;
  14285. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  14286. const n = transformedNormalWorld;
  14287. context.backdrop = getIBLVolumeRefraction(
  14288. n,
  14289. v,
  14290. roughness,
  14291. diffuseColor,
  14292. specularColor,
  14293. specularF90, // specularF90
  14294. position, // positionWorld
  14295. modelWorldMatrix, // modelMatrix
  14296. cameraViewMatrix, // viewMatrix
  14297. cameraProjectionMatrix, // projMatrix
  14298. ior,
  14299. thickness,
  14300. attenuationColor,
  14301. attenuationDistance,
  14302. this.dispersion ? dispersion : null
  14303. );
  14304. context.backdropAlpha = transmission;
  14305. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  14306. }
  14307. }
  14308. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  14309. // Approximates multi-scattering in order to preserve energy.
  14310. // http://www.jcgt.org/published/0008/01/03/
  14311. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  14312. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14313. const fab = DFGApprox( { roughness, dotNV } );
  14314. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  14315. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14316. const Ess = fab.x.add( fab.y );
  14317. const Ems = Ess.oneMinus();
  14318. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  14319. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  14320. singleScatter.addAssign( FssEss );
  14321. multiScatter.addAssign( Fms.mul( Ems ) );
  14322. }
  14323. /**
  14324. * Implements the direct light.
  14325. *
  14326. * @param {Object} input - The input data.
  14327. * @param {StackNode} stack - The current stack.
  14328. * @param {NodeBuilder} builder - The current node builder.
  14329. */
  14330. direct( { lightDirection, lightColor, reflectedLight } ) {
  14331. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14332. const irradiance = dotNL.mul( lightColor );
  14333. if ( this.sheen === true ) {
  14334. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  14335. }
  14336. if ( this.clearcoat === true ) {
  14337. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  14338. const ccIrradiance = dotNLcc.mul( lightColor );
  14339. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  14340. }
  14341. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14342. 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 } ) ) );
  14343. }
  14344. /**
  14345. * This method is intended for implementing the direct light term for
  14346. * rect area light nodes.
  14347. *
  14348. * @param {Object} input - The input data.
  14349. * @param {StackNode} stack - The current stack.
  14350. * @param {NodeBuilder} builder - The current node builder.
  14351. */
  14352. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  14353. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  14354. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  14355. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  14356. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  14357. const N = transformedNormalView;
  14358. const V = positionViewDirection;
  14359. const P = positionView.toVar();
  14360. const uv = LTC_Uv( { N, V, roughness } );
  14361. const t1 = ltc_1.sample( uv ).toVar();
  14362. const t2 = ltc_2.sample( uv ).toVar();
  14363. const mInv = mat3(
  14364. vec3( t1.x, 0, t1.y ),
  14365. vec3( 0, 1, 0 ),
  14366. vec3( t1.z, 0, t1.w )
  14367. ).toVar();
  14368. // LTC Fresnel Approximation by Stephen Hill
  14369. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  14370. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  14371. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  14372. 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 } ) ) );
  14373. }
  14374. /**
  14375. * Implements the indirect lighting.
  14376. *
  14377. * @param {ContextNode} context - The current node context.
  14378. * @param {StackNode} stack - The current stack.
  14379. * @param {NodeBuilder} builder - The current node builder.
  14380. */
  14381. indirect( context, stack, builder ) {
  14382. this.indirectDiffuse( context, stack, builder );
  14383. this.indirectSpecular( context, stack, builder );
  14384. this.ambientOcclusion( context, stack, builder );
  14385. }
  14386. /**
  14387. * Implements the indirect diffuse term.
  14388. *
  14389. * @param {ContextNode} input - The current node context.
  14390. * @param {StackNode} stack - The current stack.
  14391. * @param {NodeBuilder} builder - The current node builder.
  14392. */
  14393. indirectDiffuse( { irradiance, reflectedLight } ) {
  14394. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14395. }
  14396. /**
  14397. * Implements the indirect specular term.
  14398. *
  14399. * @param {ContextNode} input - The current node context.
  14400. * @param {StackNode} stack - The current stack.
  14401. * @param {NodeBuilder} builder - The current node builder.
  14402. */
  14403. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  14404. if ( this.sheen === true ) {
  14405. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  14406. sheen,
  14407. IBLSheenBRDF( {
  14408. normal: transformedNormalView,
  14409. viewDir: positionViewDirection,
  14410. roughness: sheenRoughness
  14411. } )
  14412. ) );
  14413. }
  14414. if ( this.clearcoat === true ) {
  14415. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14416. const clearcoatEnv = EnvironmentBRDF( {
  14417. dotNV: dotNVcc,
  14418. specularColor: clearcoatF0,
  14419. specularF90: clearcoatF90,
  14420. roughness: clearcoatRoughness
  14421. } );
  14422. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  14423. }
  14424. // Both indirect specular and indirect diffuse light accumulate here
  14425. const singleScattering = vec3().toVar( 'singleScattering' );
  14426. const multiScattering = vec3().toVar( 'multiScattering' );
  14427. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  14428. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  14429. const totalScattering = singleScattering.add( multiScattering );
  14430. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  14431. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  14432. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  14433. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  14434. }
  14435. /**
  14436. * Implements the ambient occlusion term.
  14437. *
  14438. * @param {ContextNode} input - The current node context.
  14439. * @param {StackNode} stack - The current stack.
  14440. * @param {NodeBuilder} builder - The current node builder.
  14441. */
  14442. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  14443. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14444. const aoNV = dotNV.add( ambientOcclusion );
  14445. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  14446. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  14447. if ( this.clearcoat === true ) {
  14448. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  14449. }
  14450. if ( this.sheen === true ) {
  14451. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  14452. }
  14453. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14454. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14455. }
  14456. /**
  14457. * Used for final lighting accumulations depending on the requested features.
  14458. *
  14459. * @param {ContextNode} context - The current node context.
  14460. * @param {StackNode} stack - The current stack.
  14461. * @param {NodeBuilder} builder - The current node builder.
  14462. */
  14463. finish( context ) {
  14464. const { outgoingLight } = context;
  14465. if ( this.clearcoat === true ) {
  14466. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14467. const Fcc = F_Schlick( {
  14468. dotVH: dotNVcc,
  14469. f0: clearcoatF0,
  14470. f90: clearcoatF90
  14471. } );
  14472. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14473. outgoingLight.assign( clearcoatLight );
  14474. }
  14475. if ( this.sheen === true ) {
  14476. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14477. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14478. outgoingLight.assign( sheenLight );
  14479. }
  14480. }
  14481. }
  14482. // These defines must match with PMREMGenerator
  14483. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14484. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  14485. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14486. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  14487. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14488. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14489. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14490. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14491. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14492. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14493. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14494. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14495. // These shader functions convert between the UV coordinates of a single face of
  14496. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14497. // sampling a textureCube (not generally normalized ).
  14498. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14499. const absDirection = vec3( abs( direction ) ).toVar();
  14500. const face = float( -1 ).toVar();
  14501. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14502. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14503. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14504. } ).Else( () => {
  14505. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14506. } );
  14507. } ).Else( () => {
  14508. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14509. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14510. } ).Else( () => {
  14511. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14512. } );
  14513. } );
  14514. return face;
  14515. } ).setLayout( {
  14516. name: 'getFace',
  14517. type: 'float',
  14518. inputs: [
  14519. { name: 'direction', type: 'vec3' }
  14520. ]
  14521. } );
  14522. // RH coordinate system; PMREM face-indexing convention
  14523. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14524. const uv = vec2().toVar();
  14525. If( face.equal( 0.0 ), () => {
  14526. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14527. } ).ElseIf( face.equal( 1.0 ), () => {
  14528. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14529. } ).ElseIf( face.equal( 2.0 ), () => {
  14530. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14531. } ).ElseIf( face.equal( 3.0 ), () => {
  14532. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14533. } ).ElseIf( face.equal( 4.0 ), () => {
  14534. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14535. } ).Else( () => {
  14536. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14537. } );
  14538. return mul( 0.5, uv.add( 1.0 ) );
  14539. } ).setLayout( {
  14540. name: 'getUV',
  14541. type: 'vec2',
  14542. inputs: [
  14543. { name: 'direction', type: 'vec3' },
  14544. { name: 'face', type: 'float' }
  14545. ]
  14546. } );
  14547. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14548. const mip = float( 0.0 ).toVar();
  14549. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14550. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14551. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14552. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14553. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14554. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14555. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14556. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14557. } ).Else( () => {
  14558. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14559. } );
  14560. return mip;
  14561. } ).setLayout( {
  14562. name: 'roughnessToMip',
  14563. type: 'float',
  14564. inputs: [
  14565. { name: 'roughness', type: 'float' }
  14566. ]
  14567. } );
  14568. // RH coordinate system; PMREM face-indexing convention
  14569. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14570. const uv = uv_immutable.toVar();
  14571. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14572. const direction = vec3( uv, 1.0 ).toVar();
  14573. If( face.equal( 0.0 ), () => {
  14574. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14575. } ).ElseIf( face.equal( 1.0 ), () => {
  14576. direction.assign( direction.xzy );
  14577. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  14578. } ).ElseIf( face.equal( 2.0 ), () => {
  14579. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  14580. } ).ElseIf( face.equal( 3.0 ), () => {
  14581. direction.assign( direction.zyx );
  14582. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  14583. } ).ElseIf( face.equal( 4.0 ), () => {
  14584. direction.assign( direction.xzy );
  14585. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  14586. } ).ElseIf( face.equal( 5.0 ), () => {
  14587. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  14588. } );
  14589. return direction;
  14590. } ).setLayout( {
  14591. name: 'getDirection',
  14592. type: 'vec3',
  14593. inputs: [
  14594. { name: 'uv', type: 'vec2' },
  14595. { name: 'face', type: 'float' }
  14596. ]
  14597. } );
  14598. //
  14599. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14600. const roughness = float( roughness_immutable );
  14601. const sampleDir = vec3( sampleDir_immutable );
  14602. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14603. const mipF = fract( mip );
  14604. const mipInt = floor( mip );
  14605. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14606. If( mipF.notEqual( 0.0 ), () => {
  14607. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14608. color0.assign( mix( color0, color1, mipF ) );
  14609. } );
  14610. return color0;
  14611. } );
  14612. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14613. const mipInt = float( mipInt_immutable ).toVar();
  14614. const direction = vec3( direction_immutable );
  14615. const face = float( getFace( direction ) ).toVar();
  14616. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14617. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14618. const faceSize = float( exp2( mipInt ) ).toVar();
  14619. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14620. If( face.greaterThan( 2.0 ), () => {
  14621. uv.y.addAssign( faceSize );
  14622. face.subAssign( 3.0 );
  14623. } );
  14624. uv.x.addAssign( face.mul( faceSize ) );
  14625. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14626. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14627. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14628. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14629. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14630. } );
  14631. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14632. const cosTheta = cos( theta );
  14633. // Rodrigues' axis-angle rotation
  14634. const sampleDirection = outputDirection.mul( cosTheta )
  14635. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14636. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14637. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14638. } );
  14639. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14640. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14641. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14642. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14643. } );
  14644. axis.assign( normalize( axis ) );
  14645. const gl_FragColor = vec3().toVar();
  14646. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14647. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14648. If( i.greaterThanEqual( samples ), () => {
  14649. Break();
  14650. } );
  14651. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14652. 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 } ) ) );
  14653. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14654. } );
  14655. return vec4( gl_FragColor, 1 );
  14656. } );
  14657. let _generator = null;
  14658. const _cache = new WeakMap();
  14659. /**
  14660. * Generates the cubeUV size based on the given image height.
  14661. *
  14662. * @private
  14663. * @param {number} imageHeight - The image height.
  14664. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  14665. */
  14666. function _generateCubeUVSize( imageHeight ) {
  14667. const maxMip = Math.log2( imageHeight ) - 2;
  14668. const texelHeight = 1.0 / imageHeight;
  14669. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14670. return { texelWidth, texelHeight, maxMip };
  14671. }
  14672. /**
  14673. * Generates a PMREM from the given texture .
  14674. *
  14675. * @private
  14676. * @param {Texture} texture - The texture to create the PMREM for.
  14677. * @return {Texture} The PMREM.
  14678. */
  14679. function _getPMREMFromTexture( texture ) {
  14680. let cacheTexture = _cache.get( texture );
  14681. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  14682. if ( pmremVersion !== texture.pmremVersion ) {
  14683. const image = texture.image;
  14684. if ( texture.isCubeTexture ) {
  14685. if ( isCubeMapReady( image ) ) {
  14686. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14687. } else {
  14688. return null;
  14689. }
  14690. } else {
  14691. if ( isEquirectangularMapReady( image ) ) {
  14692. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14693. } else {
  14694. return null;
  14695. }
  14696. }
  14697. cacheTexture.pmremVersion = texture.pmremVersion;
  14698. _cache.set( texture, cacheTexture );
  14699. }
  14700. return cacheTexture.texture;
  14701. }
  14702. /**
  14703. * This node represents a PMREM which is a special type of preprocessed
  14704. * environment map intended for PBR materials.
  14705. *
  14706. * ```js
  14707. * const material = new MeshStandardNodeMaterial();
  14708. * material.envNode = pmremTexture( envMap );
  14709. * ```
  14710. *
  14711. * @augments TempNode
  14712. */
  14713. class PMREMNode extends TempNode {
  14714. static get type() {
  14715. return 'PMREMNode';
  14716. }
  14717. /**
  14718. * Constructs a new function overloading node.
  14719. *
  14720. * @param {Texture} value - The input texture.
  14721. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14722. * @param {Node<float>} [levelNode=null] - The level node.
  14723. */
  14724. constructor( value, uvNode = null, levelNode = null ) {
  14725. super( 'vec3' );
  14726. /**
  14727. * Reference to the input texture.
  14728. *
  14729. * @private
  14730. * @type {Texture}
  14731. */
  14732. this._value = value;
  14733. /**
  14734. * Reference to the generated PMREM.
  14735. *
  14736. * @private
  14737. * @type {Texture | null}
  14738. * @default null
  14739. */
  14740. this._pmrem = null;
  14741. /**
  14742. * The uv node.
  14743. *
  14744. * @type {Node<vec2>}
  14745. */
  14746. this.uvNode = uvNode;
  14747. /**
  14748. * The level node.
  14749. *
  14750. * @type {Node<float>}
  14751. */
  14752. this.levelNode = levelNode;
  14753. /**
  14754. * Reference to a PMREM generator.
  14755. *
  14756. * @private
  14757. * @type {PMREMGenerator}
  14758. * @default null
  14759. */
  14760. this._generator = null;
  14761. const defaultTexture = new Texture();
  14762. defaultTexture.isRenderTargetTexture = true;
  14763. /**
  14764. * The texture node holding the generated PMREM.
  14765. *
  14766. * @private
  14767. * @type {TextureNode}
  14768. */
  14769. this._texture = texture( defaultTexture );
  14770. /**
  14771. * A uniform representing the PMREM's width.
  14772. *
  14773. * @private
  14774. * @type {UniformNode<float>}
  14775. */
  14776. this._width = uniform( 0 );
  14777. /**
  14778. * A uniform representing the PMREM's height.
  14779. *
  14780. * @private
  14781. * @type {UniformNode<float>}
  14782. */
  14783. this._height = uniform( 0 );
  14784. /**
  14785. * A uniform representing the PMREM's max Mip.
  14786. *
  14787. * @private
  14788. * @type {UniformNode<float>}
  14789. */
  14790. this._maxMip = uniform( 0 );
  14791. /**
  14792. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14793. *
  14794. * @type {string}
  14795. * @default 'render'
  14796. */
  14797. this.updateBeforeType = NodeUpdateType.RENDER;
  14798. }
  14799. set value( value ) {
  14800. this._value = value;
  14801. this._pmrem = null;
  14802. }
  14803. /**
  14804. * The node's texture value.
  14805. *
  14806. * @type {Texture}
  14807. */
  14808. get value() {
  14809. return this._value;
  14810. }
  14811. /**
  14812. * Uses the given PMREM texture to update internal values.
  14813. *
  14814. * @param {Texture} texture - The PMREM texture.
  14815. */
  14816. updateFromTexture( texture ) {
  14817. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14818. this._texture.value = texture;
  14819. this._width.value = cubeUVSize.texelWidth;
  14820. this._height.value = cubeUVSize.texelHeight;
  14821. this._maxMip.value = cubeUVSize.maxMip;
  14822. }
  14823. updateBefore() {
  14824. let pmrem = this._pmrem;
  14825. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  14826. const texture = this._value;
  14827. if ( pmremVersion !== texture.pmremVersion ) {
  14828. if ( texture.isPMREMTexture === true ) {
  14829. pmrem = texture;
  14830. } else {
  14831. pmrem = _getPMREMFromTexture( texture );
  14832. }
  14833. if ( pmrem !== null ) {
  14834. this._pmrem = pmrem;
  14835. this.updateFromTexture( pmrem );
  14836. }
  14837. }
  14838. }
  14839. setup( builder ) {
  14840. if ( _generator === null ) {
  14841. _generator = builder.createPMREMGenerator();
  14842. }
  14843. //
  14844. this.updateBefore( builder );
  14845. //
  14846. let uvNode = this.uvNode;
  14847. if ( uvNode === null && builder.context.getUV ) {
  14848. uvNode = builder.context.getUV( this );
  14849. }
  14850. //
  14851. const texture = this.value;
  14852. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14853. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14854. }
  14855. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14856. //
  14857. let levelNode = this.levelNode;
  14858. if ( levelNode === null && builder.context.getTextureLevel ) {
  14859. levelNode = builder.context.getTextureLevel( this );
  14860. }
  14861. //
  14862. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14863. }
  14864. }
  14865. /**
  14866. * Returns `true` if the given cube map image has been fully loaded.
  14867. *
  14868. * @private
  14869. * @param {Array<(Image|Object)>} image - The cube map image.
  14870. * @return {boolean} Whether the given cube map is ready or not.
  14871. */
  14872. function isCubeMapReady( image ) {
  14873. if ( image === null || image === undefined ) return false;
  14874. let count = 0;
  14875. const length = 6;
  14876. for ( let i = 0; i < length; i ++ ) {
  14877. if ( image[ i ] !== undefined ) count ++;
  14878. }
  14879. return count === length;
  14880. }
  14881. /**
  14882. * Returns `true` if the given equirectangular image has been fully loaded.
  14883. *
  14884. * @private
  14885. * @param {(Image|Object)} image - The equirectangular image.
  14886. * @return {boolean} Whether the given cube map is ready or not.
  14887. */
  14888. function isEquirectangularMapReady( image ) {
  14889. if ( image === null || image === undefined ) return false;
  14890. return image.height > 0;
  14891. }
  14892. /**
  14893. * TSL function for creating a PMREM node.
  14894. *
  14895. * @tsl
  14896. * @function
  14897. * @param {Texture} value - The input texture.
  14898. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14899. * @param {Node<float>} [levelNode=null] - The level node.
  14900. * @returns {PMREMNode}
  14901. */
  14902. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14903. const _envNodeCache = new WeakMap();
  14904. /**
  14905. * Represents a physical model for Image-based lighting (IBL). The environment
  14906. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14907. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14908. *
  14909. * @augments LightingNode
  14910. */
  14911. class EnvironmentNode extends LightingNode {
  14912. static get type() {
  14913. return 'EnvironmentNode';
  14914. }
  14915. /**
  14916. * Constructs a new environment node.
  14917. *
  14918. * @param {Node} [envNode=null] - A node representing the environment.
  14919. */
  14920. constructor( envNode = null ) {
  14921. super();
  14922. /**
  14923. * A node representing the environment.
  14924. *
  14925. * @type {?Node}
  14926. * @default null
  14927. */
  14928. this.envNode = envNode;
  14929. }
  14930. setup( builder ) {
  14931. const { material } = builder;
  14932. let envNode = this.envNode;
  14933. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14934. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14935. let cacheEnvNode = _envNodeCache.get( value );
  14936. if ( cacheEnvNode === undefined ) {
  14937. cacheEnvNode = pmremTexture( value );
  14938. _envNodeCache.set( value, cacheEnvNode );
  14939. }
  14940. envNode = cacheEnvNode;
  14941. }
  14942. //
  14943. const envMap = material.envMap;
  14944. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14945. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14946. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14947. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14948. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14949. const isolateRadiance = cache( radiance );
  14950. const isolateIrradiance = cache( irradiance );
  14951. //
  14952. builder.context.radiance.addAssign( isolateRadiance );
  14953. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14954. //
  14955. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14956. if ( clearcoatRadiance ) {
  14957. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14958. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14959. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14960. }
  14961. }
  14962. }
  14963. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14964. let reflectVec = null;
  14965. return {
  14966. getUV: () => {
  14967. if ( reflectVec === null ) {
  14968. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14969. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14970. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14971. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14972. }
  14973. return reflectVec;
  14974. },
  14975. getTextureLevel: () => {
  14976. return roughnessNode;
  14977. }
  14978. };
  14979. };
  14980. const createIrradianceContext = ( normalWorldNode ) => {
  14981. return {
  14982. getUV: () => {
  14983. return normalWorldNode;
  14984. },
  14985. getTextureLevel: () => {
  14986. return float( 1.0 );
  14987. }
  14988. };
  14989. };
  14990. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14991. /**
  14992. * Node material version of `MeshStandardMaterial`.
  14993. *
  14994. * @augments NodeMaterial
  14995. */
  14996. class MeshStandardNodeMaterial extends NodeMaterial {
  14997. static get type() {
  14998. return 'MeshStandardNodeMaterial';
  14999. }
  15000. /**
  15001. * Constructs a new mesh standard node material.
  15002. *
  15003. * @param {?Object} parameters - The configuration parameter.
  15004. */
  15005. constructor( parameters ) {
  15006. super();
  15007. /**
  15008. * This flag can be used for type testing.
  15009. *
  15010. * @type {boolean}
  15011. * @readonly
  15012. * @default true
  15013. */
  15014. this.isMeshStandardNodeMaterial = true;
  15015. /**
  15016. * Set to `true` because standard materials react on lights.
  15017. *
  15018. * @type {boolean}
  15019. * @default true
  15020. */
  15021. this.lights = true;
  15022. /**
  15023. * The emissive color of standard materials is by default inferred from the `emissive`,
  15024. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  15025. * overwrite the default and define the emissive color with a node instead.
  15026. *
  15027. * If you don't want to overwrite the emissive color but modify the existing
  15028. * value instead, use {@link materialEmissive}.
  15029. *
  15030. * @type {?Node<vec3>}
  15031. * @default null
  15032. */
  15033. this.emissiveNode = null;
  15034. /**
  15035. * The metalness of standard materials is by default inferred from the `metalness`,
  15036. * and `metalnessMap` properties. This node property allows to
  15037. * overwrite the default and define the metalness with a node instead.
  15038. *
  15039. * If you don't want to overwrite the metalness but modify the existing
  15040. * value instead, use {@link materialMetalness}.
  15041. *
  15042. * @type {?Node<float>}
  15043. * @default null
  15044. */
  15045. this.metalnessNode = null;
  15046. /**
  15047. * The roughness of standard materials is by default inferred from the `roughness`,
  15048. * and `roughnessMap` properties. This node property allows to
  15049. * overwrite the default and define the roughness with a node instead.
  15050. *
  15051. * If you don't want to overwrite the roughness but modify the existing
  15052. * value instead, use {@link materialRoughness}.
  15053. *
  15054. * @type {?Node<float>}
  15055. * @default null
  15056. */
  15057. this.roughnessNode = null;
  15058. this.setDefaultValues( _defaultValues$6 );
  15059. this.setValues( parameters );
  15060. }
  15061. /**
  15062. * Overwritten since this type of material uses {@link EnvironmentNode}
  15063. * to implement the PBR (PMREM based) environment mapping. Besides, the
  15064. * method honors `Scene.environment`.
  15065. *
  15066. * @param {NodeBuilder} builder - The current node builder.
  15067. * @return {?EnvironmentNode<vec3>} The environment node.
  15068. */
  15069. setupEnvironment( builder ) {
  15070. let envNode = super.setupEnvironment( builder );
  15071. if ( envNode === null && builder.environmentNode ) {
  15072. envNode = builder.environmentNode;
  15073. }
  15074. return envNode ? new EnvironmentNode( envNode ) : null;
  15075. }
  15076. /**
  15077. * Setups the lighting model.
  15078. *
  15079. * @return {PhysicalLightingModel} The lighting model.
  15080. */
  15081. setupLightingModel( /*builder*/ ) {
  15082. return new PhysicalLightingModel();
  15083. }
  15084. /**
  15085. * Setups the specular related node variables.
  15086. */
  15087. setupSpecular() {
  15088. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  15089. specularColor.assign( specularColorNode );
  15090. specularF90.assign( 1.0 );
  15091. }
  15092. /**
  15093. * Setups the standard specific node variables.
  15094. *
  15095. * @param {NodeBuilder} builder - The current node builder.
  15096. */
  15097. setupVariants() {
  15098. // METALNESS
  15099. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  15100. metalness.assign( metalnessNode );
  15101. // ROUGHNESS
  15102. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  15103. roughnessNode = getRoughness( { roughness: roughnessNode } );
  15104. roughness.assign( roughnessNode );
  15105. // SPECULAR COLOR
  15106. this.setupSpecular();
  15107. // DIFFUSE COLOR
  15108. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  15109. }
  15110. copy( source ) {
  15111. this.emissiveNode = source.emissiveNode;
  15112. this.metalnessNode = source.metalnessNode;
  15113. this.roughnessNode = source.roughnessNode;
  15114. return super.copy( source );
  15115. }
  15116. }
  15117. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  15118. /**
  15119. * Node material version of `MeshPhysicalMaterial`.
  15120. *
  15121. * @augments MeshStandardNodeMaterial
  15122. */
  15123. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  15124. static get type() {
  15125. return 'MeshPhysicalNodeMaterial';
  15126. }
  15127. /**
  15128. * Constructs a new mesh physical node material.
  15129. *
  15130. * @param {?Object} parameters - The configuration parameter.
  15131. */
  15132. constructor( parameters ) {
  15133. super();
  15134. /**
  15135. * This flag can be used for type testing.
  15136. *
  15137. * @type {boolean}
  15138. * @readonly
  15139. * @default true
  15140. */
  15141. this.isMeshPhysicalNodeMaterial = true;
  15142. /**
  15143. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  15144. * and `clearcoatMap` properties. This node property allows to overwrite the default
  15145. * and define the clearcoat with a node instead.
  15146. *
  15147. * If you don't want to overwrite the clearcoat but modify the existing
  15148. * value instead, use {@link materialClearcoat}.
  15149. *
  15150. * @type {?Node<float>}
  15151. * @default null
  15152. */
  15153. this.clearcoatNode = null;
  15154. /**
  15155. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  15156. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  15157. * and define the clearcoat roughness with a node instead.
  15158. *
  15159. * If you don't want to overwrite the clearcoat roughness but modify the existing
  15160. * value instead, use {@link materialClearcoatRoughness}.
  15161. *
  15162. * @type {?Node<float>}
  15163. * @default null
  15164. */
  15165. this.clearcoatRoughnessNode = null;
  15166. /**
  15167. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  15168. * property. This node property allows to overwrite the default
  15169. * and define the clearcoat normal with a node instead.
  15170. *
  15171. * If you don't want to overwrite the clearcoat normal but modify the existing
  15172. * value instead, use {@link materialClearcoatNormal}.
  15173. *
  15174. * @type {?Node<vec3>}
  15175. * @default null
  15176. */
  15177. this.clearcoatNormalNode = null;
  15178. /**
  15179. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  15180. * and `sheenColorMap` properties. This node property allows to overwrite the default
  15181. * and define the sheen with a node instead.
  15182. *
  15183. * If you don't want to overwrite the sheen but modify the existing
  15184. * value instead, use {@link materialSheen}.
  15185. *
  15186. * @type {?Node<vec3>}
  15187. * @default null
  15188. */
  15189. this.sheenNode = null;
  15190. /**
  15191. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  15192. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  15193. * and define the sheen roughness with a node instead.
  15194. *
  15195. * If you don't want to overwrite the sheen roughness but modify the existing
  15196. * value instead, use {@link materialSheenRoughness}.
  15197. *
  15198. * @type {?Node<float>}
  15199. * @default null
  15200. */
  15201. this.sheenRoughnessNode = null;
  15202. /**
  15203. * The iridescence of physical materials is by default inferred from the `iridescence`
  15204. * property. This node property allows to overwrite the default
  15205. * and define the iridescence with a node instead.
  15206. *
  15207. * If you don't want to overwrite the iridescence but modify the existing
  15208. * value instead, use {@link materialIridescence}.
  15209. *
  15210. * @type {?Node<float>}
  15211. * @default null
  15212. */
  15213. this.iridescenceNode = null;
  15214. /**
  15215. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  15216. * property. This node property allows to overwrite the default
  15217. * and define the iridescence IOR with a node instead.
  15218. *
  15219. * If you don't want to overwrite the iridescence IOR but modify the existing
  15220. * value instead, use {@link materialIridescenceIOR}.
  15221. *
  15222. * @type {?Node<float>}
  15223. * @default null
  15224. */
  15225. this.iridescenceIORNode = null;
  15226. /**
  15227. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  15228. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  15229. * and define the iridescence thickness with a node instead.
  15230. *
  15231. * If you don't want to overwrite the iridescence thickness but modify the existing
  15232. * value instead, use {@link materialIridescenceThickness}.
  15233. *
  15234. * @type {?Node<float>}
  15235. * @default null
  15236. */
  15237. this.iridescenceThicknessNode = null;
  15238. /**
  15239. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  15240. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  15241. * and define the specular intensity with a node instead.
  15242. *
  15243. * If you don't want to overwrite the specular intensity but modify the existing
  15244. * value instead, use {@link materialSpecularIntensity}.
  15245. *
  15246. * @type {?Node<float>}
  15247. * @default null
  15248. */
  15249. this.specularIntensityNode = null;
  15250. /**
  15251. * The specular color of physical materials is by default inferred from the `specularColor`
  15252. * and `specularColorMap` properties. This node property allows to overwrite the default
  15253. * and define the specular color with a node instead.
  15254. *
  15255. * If you don't want to overwrite the specular color but modify the existing
  15256. * value instead, use {@link materialSpecularColor}.
  15257. *
  15258. * @type {?Node<vec3>}
  15259. * @default null
  15260. */
  15261. this.specularColorNode = null;
  15262. /**
  15263. * The ior of physical materials is by default inferred from the `ior`
  15264. * property. This node property allows to overwrite the default
  15265. * and define the ior with a node instead.
  15266. *
  15267. * If you don't want to overwrite the ior but modify the existing
  15268. * value instead, use {@link materialIOR}.
  15269. *
  15270. * @type {?Node<float>}
  15271. * @default null
  15272. */
  15273. this.iorNode = null;
  15274. /**
  15275. * The transmission of physical materials is by default inferred from the `transmission` and
  15276. * `transmissionMap` properties. This node property allows to overwrite the default
  15277. * and define the transmission with a node instead.
  15278. *
  15279. * If you don't want to overwrite the transmission but modify the existing
  15280. * value instead, use {@link materialTransmission}.
  15281. *
  15282. * @type {?Node<float>}
  15283. * @default null
  15284. */
  15285. this.transmissionNode = null;
  15286. /**
  15287. * The thickness of physical materials is by default inferred from the `thickness` and
  15288. * `thicknessMap` properties. This node property allows to overwrite the default
  15289. * and define the thickness with a node instead.
  15290. *
  15291. * If you don't want to overwrite the thickness but modify the existing
  15292. * value instead, use {@link materialThickness}.
  15293. *
  15294. * @type {?Node<float>}
  15295. * @default null
  15296. */
  15297. this.thicknessNode = null;
  15298. /**
  15299. * The attenuation distance of physical materials is by default inferred from the
  15300. * `attenuationDistance` property. This node property allows to overwrite the default
  15301. * and define the attenuation distance with a node instead.
  15302. *
  15303. * If you don't want to overwrite the attenuation distance but modify the existing
  15304. * value instead, use {@link materialAttenuationDistance}.
  15305. *
  15306. * @type {?Node<float>}
  15307. * @default null
  15308. */
  15309. this.attenuationDistanceNode = null;
  15310. /**
  15311. * The attenuation color of physical materials is by default inferred from the
  15312. * `attenuationColor` property. This node property allows to overwrite the default
  15313. * and define the attenuation color with a node instead.
  15314. *
  15315. * If you don't want to overwrite the attenuation color but modify the existing
  15316. * value instead, use {@link materialAttenuationColor}.
  15317. *
  15318. * @type {?Node<vec3>}
  15319. * @default null
  15320. */
  15321. this.attenuationColorNode = null;
  15322. /**
  15323. * The dispersion of physical materials is by default inferred from the
  15324. * `dispersion` property. This node property allows to overwrite the default
  15325. * and define the dispersion with a node instead.
  15326. *
  15327. * If you don't want to overwrite the dispersion but modify the existing
  15328. * value instead, use {@link materialDispersion}.
  15329. *
  15330. * @type {?Node<float>}
  15331. * @default null
  15332. */
  15333. this.dispersionNode = null;
  15334. /**
  15335. * The anisotropy of physical materials is by default inferred from the
  15336. * `anisotropy` property. This node property allows to overwrite the default
  15337. * and define the anisotropy with a node instead.
  15338. *
  15339. * If you don't want to overwrite the anisotropy but modify the existing
  15340. * value instead, use {@link materialAnisotropy}.
  15341. *
  15342. * @type {?Node<float>}
  15343. * @default null
  15344. */
  15345. this.anisotropyNode = null;
  15346. this.setDefaultValues( _defaultValues$5 );
  15347. this.setValues( parameters );
  15348. }
  15349. /**
  15350. * Whether the lighting model should use clearcoat or not.
  15351. *
  15352. * @type {boolean}
  15353. * @default true
  15354. */
  15355. get useClearcoat() {
  15356. return this.clearcoat > 0 || this.clearcoatNode !== null;
  15357. }
  15358. /**
  15359. * Whether the lighting model should use iridescence or not.
  15360. *
  15361. * @type {boolean}
  15362. * @default true
  15363. */
  15364. get useIridescence() {
  15365. return this.iridescence > 0 || this.iridescenceNode !== null;
  15366. }
  15367. /**
  15368. * Whether the lighting model should use sheen or not.
  15369. *
  15370. * @type {boolean}
  15371. * @default true
  15372. */
  15373. get useSheen() {
  15374. return this.sheen > 0 || this.sheenNode !== null;
  15375. }
  15376. /**
  15377. * Whether the lighting model should use anisotropy or not.
  15378. *
  15379. * @type {boolean}
  15380. * @default true
  15381. */
  15382. get useAnisotropy() {
  15383. return this.anisotropy > 0 || this.anisotropyNode !== null;
  15384. }
  15385. /**
  15386. * Whether the lighting model should use transmission or not.
  15387. *
  15388. * @type {boolean}
  15389. * @default true
  15390. */
  15391. get useTransmission() {
  15392. return this.transmission > 0 || this.transmissionNode !== null;
  15393. }
  15394. /**
  15395. * Whether the lighting model should use dispersion or not.
  15396. *
  15397. * @type {boolean}
  15398. * @default true
  15399. */
  15400. get useDispersion() {
  15401. return this.dispersion > 0 || this.dispersionNode !== null;
  15402. }
  15403. /**
  15404. * Setups the specular related node variables.
  15405. */
  15406. setupSpecular() {
  15407. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  15408. ior.assign( iorNode );
  15409. 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 ) );
  15410. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  15411. }
  15412. /**
  15413. * Setups the lighting model.
  15414. *
  15415. * @return {PhysicalLightingModel} The lighting model.
  15416. */
  15417. setupLightingModel( /*builder*/ ) {
  15418. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  15419. }
  15420. /**
  15421. * Setups the physical specific node variables.
  15422. *
  15423. * @param {NodeBuilder} builder - The current node builder.
  15424. */
  15425. setupVariants( builder ) {
  15426. super.setupVariants( builder );
  15427. // CLEARCOAT
  15428. if ( this.useClearcoat ) {
  15429. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  15430. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  15431. clearcoat.assign( clearcoatNode );
  15432. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  15433. }
  15434. // SHEEN
  15435. if ( this.useSheen ) {
  15436. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  15437. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  15438. sheen.assign( sheenNode );
  15439. sheenRoughness.assign( sheenRoughnessNode );
  15440. }
  15441. // IRIDESCENCE
  15442. if ( this.useIridescence ) {
  15443. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  15444. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  15445. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  15446. iridescence.assign( iridescenceNode );
  15447. iridescenceIOR.assign( iridescenceIORNode );
  15448. iridescenceThickness.assign( iridescenceThicknessNode );
  15449. }
  15450. // ANISOTROPY
  15451. if ( this.useAnisotropy ) {
  15452. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  15453. anisotropy.assign( anisotropyV.length() );
  15454. If( anisotropy.equal( 0.0 ), () => {
  15455. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  15456. } ).Else( () => {
  15457. anisotropyV.divAssign( vec2( anisotropy ) );
  15458. anisotropy.assign( anisotropy.saturate() );
  15459. } );
  15460. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  15461. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  15462. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  15463. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15464. }
  15465. // TRANSMISSION
  15466. if ( this.useTransmission ) {
  15467. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15468. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15469. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15470. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15471. transmission.assign( transmissionNode );
  15472. thickness.assign( thicknessNode );
  15473. attenuationDistance.assign( attenuationDistanceNode );
  15474. attenuationColor.assign( attenuationColorNode );
  15475. if ( this.useDispersion ) {
  15476. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15477. dispersion.assign( dispersionNode );
  15478. }
  15479. }
  15480. }
  15481. /**
  15482. * Setups the clearcoat normal node.
  15483. *
  15484. * @return {Node<vec3>} The clearcoat normal.
  15485. */
  15486. setupClearcoatNormal() {
  15487. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15488. }
  15489. setup( builder ) {
  15490. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15491. super.setup( builder );
  15492. }
  15493. copy( source ) {
  15494. this.clearcoatNode = source.clearcoatNode;
  15495. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15496. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15497. this.sheenNode = source.sheenNode;
  15498. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15499. this.iridescenceNode = source.iridescenceNode;
  15500. this.iridescenceIORNode = source.iridescenceIORNode;
  15501. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15502. this.specularIntensityNode = source.specularIntensityNode;
  15503. this.specularColorNode = source.specularColorNode;
  15504. this.transmissionNode = source.transmissionNode;
  15505. this.thicknessNode = source.thicknessNode;
  15506. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15507. this.attenuationColorNode = source.attenuationColorNode;
  15508. this.dispersionNode = source.dispersionNode;
  15509. this.anisotropyNode = source.anisotropyNode;
  15510. return super.copy( source );
  15511. }
  15512. }
  15513. /**
  15514. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15515. *
  15516. * @augments PhysicalLightingModel
  15517. */
  15518. class SSSLightingModel extends PhysicalLightingModel {
  15519. /**
  15520. * Constructs a new physical lighting model.
  15521. *
  15522. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15523. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15524. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15525. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15526. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15527. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15528. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  15529. */
  15530. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15531. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15532. /**
  15533. * Whether the lighting model should use SSS or not.
  15534. *
  15535. * @type {boolean}
  15536. * @default false
  15537. */
  15538. this.useSSS = sss;
  15539. }
  15540. /**
  15541. * Extends the default implementation with a SSS term.
  15542. *
  15543. * 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/}
  15544. *
  15545. * @param {Object} input - The input data.
  15546. * @param {StackNode} stack - The current stack.
  15547. * @param {NodeBuilder} builder - The current node builder.
  15548. */
  15549. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15550. if ( this.useSSS === true ) {
  15551. const material = builder.material;
  15552. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15553. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15554. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15555. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15556. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15557. }
  15558. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15559. }
  15560. }
  15561. /**
  15562. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15563. * that implements a Subsurface scattering (SSS) term.
  15564. *
  15565. * @augments MeshPhysicalNodeMaterial
  15566. */
  15567. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15568. static get type() {
  15569. return 'MeshSSSNodeMaterial';
  15570. }
  15571. /**
  15572. * Constructs a new mesh SSS node material.
  15573. *
  15574. * @param {?Object} parameters - The configuration parameter.
  15575. */
  15576. constructor( parameters ) {
  15577. super( parameters );
  15578. /**
  15579. * Represents the thickness color.
  15580. *
  15581. * @type {?Node<vec3>}
  15582. * @default null
  15583. */
  15584. this.thicknessColorNode = null;
  15585. /**
  15586. * Represents the distortion factor.
  15587. *
  15588. * @type {?Node<float>}
  15589. */
  15590. this.thicknessDistortionNode = float( 0.1 );
  15591. /**
  15592. * Represents the thickness ambient factor.
  15593. *
  15594. * @type {?Node<float>}
  15595. */
  15596. this.thicknessAmbientNode = float( 0.0 );
  15597. /**
  15598. * Represents the thickness attenuation.
  15599. *
  15600. * @type {?Node<float>}
  15601. */
  15602. this.thicknessAttenuationNode = float( .1 );
  15603. /**
  15604. * Represents the thickness power.
  15605. *
  15606. * @type {?Node<float>}
  15607. */
  15608. this.thicknessPowerNode = float( 2.0 );
  15609. /**
  15610. * Represents the thickness scale.
  15611. *
  15612. * @type {?Node<float>}
  15613. */
  15614. this.thicknessScaleNode = float( 10.0 );
  15615. }
  15616. /**
  15617. * Whether the lighting model should use SSS or not.
  15618. *
  15619. * @type {boolean}
  15620. * @default true
  15621. */
  15622. get useSSS() {
  15623. return this.thicknessColorNode !== null;
  15624. }
  15625. /**
  15626. * Setups the lighting model.
  15627. *
  15628. * @return {SSSLightingModel} The lighting model.
  15629. */
  15630. setupLightingModel( /*builder*/ ) {
  15631. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15632. }
  15633. copy( source ) {
  15634. this.thicknessColorNode = source.thicknessColorNode;
  15635. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15636. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15637. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15638. this.thicknessPowerNode = source.thicknessPowerNode;
  15639. this.thicknessScaleNode = source.thicknessScaleNode;
  15640. return super.copy( source );
  15641. }
  15642. }
  15643. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15644. // dotNL will be from -1.0 to 1.0
  15645. const dotNL = normal.dot( lightDirection );
  15646. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15647. if ( builder.material.gradientMap ) {
  15648. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15649. return vec3( gradientMap.r );
  15650. } else {
  15651. const fw = coord.fwidth().mul( 0.5 );
  15652. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15653. }
  15654. } );
  15655. /**
  15656. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15657. *
  15658. * @augments LightingModel
  15659. */
  15660. class ToonLightingModel extends LightingModel {
  15661. /**
  15662. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15663. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15664. *
  15665. * @param {Object} input - The input data.
  15666. * @param {StackNode} stack - The current stack.
  15667. * @param {NodeBuilder} builder - The current node builder.
  15668. */
  15669. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15670. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15671. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15672. }
  15673. /**
  15674. * Implements the indirect lighting.
  15675. *
  15676. * @param {ContextNode} input - The current node context.
  15677. * @param {StackNode} stack - The current stack.
  15678. * @param {NodeBuilder} builder - The current node builder.
  15679. */
  15680. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15681. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15682. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15683. }
  15684. }
  15685. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15686. /**
  15687. * Node material version of `MeshToonMaterial`.
  15688. *
  15689. * @augments NodeMaterial
  15690. */
  15691. class MeshToonNodeMaterial extends NodeMaterial {
  15692. static get type() {
  15693. return 'MeshToonNodeMaterial';
  15694. }
  15695. /**
  15696. * Constructs a new mesh toon node material.
  15697. *
  15698. * @param {?Object} parameters - The configuration parameter.
  15699. */
  15700. constructor( parameters ) {
  15701. super();
  15702. /**
  15703. * This flag can be used for type testing.
  15704. *
  15705. * @type {boolean}
  15706. * @readonly
  15707. * @default true
  15708. */
  15709. this.isMeshToonNodeMaterial = true;
  15710. /**
  15711. * Set to `true` because toon materials react on lights.
  15712. *
  15713. * @type {boolean}
  15714. * @default true
  15715. */
  15716. this.lights = true;
  15717. this.setDefaultValues( _defaultValues$4 );
  15718. this.setValues( parameters );
  15719. }
  15720. /**
  15721. * Setups the lighting model.
  15722. *
  15723. * @return {ToonLightingModel} The lighting model.
  15724. */
  15725. setupLightingModel( /*builder*/ ) {
  15726. return new ToonLightingModel();
  15727. }
  15728. }
  15729. /**
  15730. * Can be used to compute texture coordinates for projecting a
  15731. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15732. *
  15733. * @augments TempNode
  15734. */
  15735. class MatcapUVNode extends TempNode {
  15736. static get type() {
  15737. return 'MatcapUVNode';
  15738. }
  15739. /**
  15740. * Constructs a new matcap uv node.
  15741. */
  15742. constructor() {
  15743. super( 'vec2' );
  15744. }
  15745. setup() {
  15746. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15747. const y = positionViewDirection.cross( x );
  15748. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15749. }
  15750. }
  15751. /**
  15752. * TSL function for creating a matcap uv node.
  15753. *
  15754. * @tsl
  15755. * @function
  15756. * @returns {MatcapUVNode}
  15757. */
  15758. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15759. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15760. /**
  15761. * Node material version of `MeshMatcapMaterial`.
  15762. *
  15763. * @augments NodeMaterial
  15764. */
  15765. class MeshMatcapNodeMaterial extends NodeMaterial {
  15766. static get type() {
  15767. return 'MeshMatcapNodeMaterial';
  15768. }
  15769. /**
  15770. * Constructs a new mesh normal node material.
  15771. *
  15772. * @param {?Object} parameters - The configuration parameter.
  15773. */
  15774. constructor( parameters ) {
  15775. super();
  15776. /**
  15777. * This flag can be used for type testing.
  15778. *
  15779. * @type {boolean}
  15780. * @readonly
  15781. * @default true
  15782. */
  15783. this.isMeshMatcapNodeMaterial = true;
  15784. this.setDefaultValues( _defaultValues$3 );
  15785. this.setValues( parameters );
  15786. }
  15787. /**
  15788. * Setups the matcap specific node variables.
  15789. *
  15790. * @param {NodeBuilder} builder - The current node builder.
  15791. */
  15792. setupVariants( builder ) {
  15793. const uv = matcapUV;
  15794. let matcapColor;
  15795. if ( builder.material.matcap ) {
  15796. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15797. } else {
  15798. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15799. }
  15800. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15801. }
  15802. }
  15803. /**
  15804. * Applies a rotation to the given position node.
  15805. *
  15806. * @augments TempNode
  15807. */
  15808. class RotateNode extends TempNode {
  15809. static get type() {
  15810. return 'RotateNode';
  15811. }
  15812. /**
  15813. * Constructs a new rotate node.
  15814. *
  15815. * @param {Node} positionNode - The position node.
  15816. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15817. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15818. */
  15819. constructor( positionNode, rotationNode ) {
  15820. super();
  15821. /**
  15822. * The position node.
  15823. *
  15824. * @type {Node}
  15825. */
  15826. this.positionNode = positionNode;
  15827. /**
  15828. * Represents the rotation that is applied to the position node.
  15829. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15830. *
  15831. * @type {Node}
  15832. */
  15833. this.rotationNode = rotationNode;
  15834. }
  15835. /**
  15836. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15837. *
  15838. * @param {NodeBuilder} builder - The current node builder.
  15839. * @return {string} The node's type.
  15840. */
  15841. getNodeType( builder ) {
  15842. return this.positionNode.getNodeType( builder );
  15843. }
  15844. setup( builder ) {
  15845. const { rotationNode, positionNode } = this;
  15846. const nodeType = this.getNodeType( builder );
  15847. if ( nodeType === 'vec2' ) {
  15848. const cosAngle = rotationNode.cos();
  15849. const sinAngle = rotationNode.sin();
  15850. const rotationMatrix = mat2(
  15851. cosAngle, sinAngle,
  15852. sinAngle.negate(), cosAngle
  15853. );
  15854. return rotationMatrix.mul( positionNode );
  15855. } else {
  15856. const rotation = rotationNode;
  15857. 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 ) );
  15858. 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 ) );
  15859. 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 ) );
  15860. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15861. }
  15862. }
  15863. }
  15864. /**
  15865. * TSL function for creating a rotate node.
  15866. *
  15867. * @tsl
  15868. * @function
  15869. * @param {Node} positionNode - The position node.
  15870. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15871. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15872. * @returns {RotateNode}
  15873. */
  15874. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15875. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15876. /**
  15877. * Node material version of `SpriteMaterial`.
  15878. *
  15879. * @augments NodeMaterial
  15880. */
  15881. class SpriteNodeMaterial extends NodeMaterial {
  15882. static get type() {
  15883. return 'SpriteNodeMaterial';
  15884. }
  15885. /**
  15886. * Constructs a new sprite node material.
  15887. *
  15888. * @param {?Object} parameters - The configuration parameter.
  15889. */
  15890. constructor( parameters ) {
  15891. super();
  15892. /**
  15893. * This flag can be used for type testing.
  15894. *
  15895. * @type {boolean}
  15896. * @readonly
  15897. * @default true
  15898. */
  15899. this.isSpriteNodeMaterial = true;
  15900. this._useSizeAttenuation = true;
  15901. /**
  15902. * This property makes it possible to define the position of the sprite with a
  15903. * node. That can be useful when the material is used with instanced rendering
  15904. * and node data are defined with an instanced attribute node:
  15905. * ```js
  15906. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15907. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15908. * ```
  15909. * Another possibility is to compute the instanced data with a compute shader:
  15910. * ```js
  15911. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15912. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15913. * ```
  15914. *
  15915. * @type {?Node<vec2>}
  15916. * @default null
  15917. */
  15918. this.positionNode = null;
  15919. /**
  15920. * The rotation of sprite materials is by default inferred from the `rotation`,
  15921. * property. This node property allows to overwrite the default and define
  15922. * the rotation with a node instead.
  15923. *
  15924. * If you don't want to overwrite the rotation but modify the existing
  15925. * value instead, use {@link materialRotation}.
  15926. *
  15927. * @type {?Node<float>}
  15928. * @default null
  15929. */
  15930. this.rotationNode = null;
  15931. /**
  15932. * This node property provides an additional way to scale sprites next to
  15933. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15934. * is multiplied with the scale value of this node in the vertex shader.
  15935. *
  15936. * @type {?Node<vec2>}
  15937. * @default null
  15938. */
  15939. this.scaleNode = null;
  15940. /**
  15941. * In Sprites, the transparent property is enabled by default.
  15942. *
  15943. * @type {boolean}
  15944. * @default true
  15945. */
  15946. this.transparent = true;
  15947. this.setDefaultValues( _defaultValues$2 );
  15948. this.setValues( parameters );
  15949. }
  15950. /**
  15951. * Setups the position node in view space. This method implements
  15952. * the sprite specific vertex shader.
  15953. *
  15954. * @param {NodeBuilder} builder - The current node builder.
  15955. * @return {Node<vec3>} The position in view space.
  15956. */
  15957. setupPositionView( builder ) {
  15958. const { object, camera } = builder;
  15959. const sizeAttenuation = this.sizeAttenuation;
  15960. const { positionNode, rotationNode, scaleNode } = this;
  15961. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15962. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15963. if ( scaleNode !== null ) {
  15964. scale = scale.mul( float( scaleNode ) );
  15965. }
  15966. if ( sizeAttenuation === false ) {
  15967. if ( camera.isPerspectiveCamera ) {
  15968. scale = scale.mul( mvPosition.z.negate() );
  15969. } else {
  15970. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15971. scale = scale.mul( orthoScale.mul( 2 ) );
  15972. }
  15973. }
  15974. let alignedPosition = positionGeometry.xy;
  15975. if ( object.center && object.center.isVector2 === true ) {
  15976. const center = reference$1( 'center', 'vec2', object );
  15977. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15978. }
  15979. alignedPosition = alignedPosition.mul( scale );
  15980. const rotation = float( rotationNode || materialRotation );
  15981. const rotatedPosition = rotate( alignedPosition, rotation );
  15982. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15983. }
  15984. copy( source ) {
  15985. this.positionNode = source.positionNode;
  15986. this.rotationNode = source.rotationNode;
  15987. this.scaleNode = source.scaleNode;
  15988. return super.copy( source );
  15989. }
  15990. /**
  15991. * Whether to use size attenuation or not.
  15992. *
  15993. * @type {boolean}
  15994. * @default true
  15995. */
  15996. get sizeAttenuation() {
  15997. return this._useSizeAttenuation;
  15998. }
  15999. set sizeAttenuation( value ) {
  16000. if ( this._useSizeAttenuation !== value ) {
  16001. this._useSizeAttenuation = value;
  16002. this.needsUpdate = true;
  16003. }
  16004. }
  16005. }
  16006. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  16007. /**
  16008. * Node material version of `PointsMaterial`.
  16009. *
  16010. * @augments NodeMaterial
  16011. */
  16012. class PointsNodeMaterial extends SpriteNodeMaterial {
  16013. static get type() {
  16014. return 'PointsNodeMaterial';
  16015. }
  16016. /**
  16017. * Constructs a new points node material.
  16018. *
  16019. * @param {?Object} parameters - The configuration parameter.
  16020. */
  16021. constructor( parameters ) {
  16022. super();
  16023. /**
  16024. * This node property provides an additional way to set the point size.
  16025. *
  16026. * @type {?Node<vec2>}
  16027. * @default null
  16028. */
  16029. this.sizeNode = null;
  16030. /**
  16031. * This flag can be used for type testing.
  16032. *
  16033. * @type {boolean}
  16034. * @readonly
  16035. * @default true
  16036. */
  16037. this.isPointsNodeMaterial = true;
  16038. this.setDefaultValues( _defaultValues$1 );
  16039. this.setValues( parameters );
  16040. }
  16041. setupPositionView() {
  16042. const { positionNode } = this;
  16043. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  16044. }
  16045. setupVertex( builder ) {
  16046. const mvp = super.setupVertex( builder );
  16047. // skip further processing if the material is not a node material
  16048. if ( builder.material.isNodeMaterial !== true ) {
  16049. return mvp;
  16050. }
  16051. // ndc space
  16052. const { rotationNode, scaleNode, sizeNode } = this;
  16053. const alignedPosition = positionGeometry.xy.toVar();
  16054. const aspect = viewport.z.div( viewport.w );
  16055. // rotation
  16056. if ( rotationNode && rotationNode.isNode ) {
  16057. const rotation = float( rotationNode );
  16058. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  16059. }
  16060. // point size
  16061. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  16062. if ( this.sizeAttenuation === true ) {
  16063. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  16064. }
  16065. // scale
  16066. if ( scaleNode && scaleNode.isNode ) {
  16067. pointSize = pointSize.mul( vec2( scaleNode ) );
  16068. }
  16069. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  16070. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  16071. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  16072. // back to clip space
  16073. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  16074. //clipPos.xy += offset;
  16075. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  16076. return mvp;
  16077. }
  16078. /**
  16079. * Whether alpha to coverage should be used or not.
  16080. *
  16081. * @type {boolean}
  16082. * @default true
  16083. */
  16084. get alphaToCoverage() {
  16085. return this._useAlphaToCoverage;
  16086. }
  16087. set alphaToCoverage( value ) {
  16088. if ( this._useAlphaToCoverage !== value ) {
  16089. this._useAlphaToCoverage = value;
  16090. this.needsUpdate = true;
  16091. }
  16092. }
  16093. }
  16094. /**
  16095. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  16096. *
  16097. * @augments LightingModel
  16098. */
  16099. class ShadowMaskModel extends LightingModel {
  16100. /**
  16101. * Constructs a new shadow mask model.
  16102. */
  16103. constructor() {
  16104. super();
  16105. /**
  16106. * The shadow mask node.
  16107. *
  16108. * @type {Node}
  16109. */
  16110. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  16111. }
  16112. /**
  16113. * Only used to save the shadow mask.
  16114. *
  16115. * @param {Object} input - The input data.
  16116. */
  16117. direct( { shadowMask } ) {
  16118. this.shadowNode.mulAssign( shadowMask );
  16119. }
  16120. /**
  16121. * Uses the shadow mask to produce the final color.
  16122. *
  16123. * @param {ContextNode} context - The current node context.
  16124. */
  16125. finish( context ) {
  16126. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  16127. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  16128. }
  16129. }
  16130. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  16131. /**
  16132. * Node material version of `ShadowMaterial`.
  16133. *
  16134. * @augments NodeMaterial
  16135. */
  16136. class ShadowNodeMaterial extends NodeMaterial {
  16137. static get type() {
  16138. return 'ShadowNodeMaterial';
  16139. }
  16140. /**
  16141. * Constructs a new shadow node material.
  16142. *
  16143. * @param {?Object} parameters - The configuration parameter.
  16144. */
  16145. constructor( parameters ) {
  16146. super();
  16147. /**
  16148. * This flag can be used for type testing.
  16149. *
  16150. * @type {boolean}
  16151. * @readonly
  16152. * @default true
  16153. */
  16154. this.isShadowNodeMaterial = true;
  16155. /**
  16156. * Set to `true` because so it's possible to implement
  16157. * the shadow mask effect.
  16158. *
  16159. * @type {boolean}
  16160. * @default true
  16161. */
  16162. this.lights = true;
  16163. this.setDefaultValues( _defaultValues );
  16164. this.setValues( parameters );
  16165. }
  16166. /**
  16167. * Setups the lighting model.
  16168. *
  16169. * @return {ShadowMaskModel} The lighting model.
  16170. */
  16171. setupLightingModel( /*builder*/ ) {
  16172. return new ShadowMaskModel();
  16173. }
  16174. }
  16175. const normal = Fn( ( { texture, uv } ) => {
  16176. const epsilon = 0.0001;
  16177. const ret = vec3().toVar();
  16178. If( uv.x.lessThan( epsilon ), () => {
  16179. ret.assign( vec3( 1, 0, 0 ) );
  16180. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  16181. ret.assign( vec3( 0, 1, 0 ) );
  16182. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  16183. ret.assign( vec3( 0, 0, 1 ) );
  16184. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  16185. ret.assign( vec3( -1, 0, 0 ) );
  16186. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  16187. ret.assign( vec3( 0, -1, 0 ) );
  16188. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  16189. ret.assign( vec3( 0, 0, -1 ) );
  16190. } ).Else( () => {
  16191. const step = 0.01;
  16192. 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 );
  16193. 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 );
  16194. 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 );
  16195. ret.assign( vec3( x, y, z ) );
  16196. } );
  16197. return ret.normalize();
  16198. } );
  16199. /**
  16200. * This type of uniform node represents a 3D texture.
  16201. *
  16202. * @augments TextureNode
  16203. */
  16204. class Texture3DNode extends TextureNode {
  16205. static get type() {
  16206. return 'Texture3DNode';
  16207. }
  16208. /**
  16209. * Constructs a new 3D texture node.
  16210. *
  16211. * @param {Data3DTexture} value - The 3D texture.
  16212. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  16213. * @param {?Node<int>} [levelNode=null] - The level node.
  16214. */
  16215. constructor( value, uvNode = null, levelNode = null ) {
  16216. super( value, uvNode, levelNode );
  16217. /**
  16218. * This flag can be used for type testing.
  16219. *
  16220. * @type {boolean}
  16221. * @readonly
  16222. * @default true
  16223. */
  16224. this.isTexture3DNode = true;
  16225. }
  16226. /**
  16227. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  16228. *
  16229. * @param {NodeBuilder} builder - The current node builder.
  16230. * @return {string} The input type.
  16231. */
  16232. getInputType( /*builder*/ ) {
  16233. return 'texture3D';
  16234. }
  16235. /**
  16236. * Returns a default uv node which is in context of 3D textures a three-dimensional
  16237. * uv node.
  16238. *
  16239. * @return {Node<vec3>} The default uv node.
  16240. */
  16241. getDefaultUV() {
  16242. return vec3( 0.5, 0.5, 0.5 );
  16243. }
  16244. /**
  16245. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  16246. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  16247. *
  16248. * @param {boolean} value - The update toggle.
  16249. */
  16250. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  16251. /**
  16252. * Overwrites the default implementation to return the unmodified uv node.
  16253. *
  16254. * @param {NodeBuilder} builder - The current node builder.
  16255. * @param {Node} uvNode - The uv node to setup.
  16256. * @return {Node} The unmodified uv node.
  16257. */
  16258. setupUV( builder, uvNode ) {
  16259. const texture = this.value;
  16260. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  16261. if ( this.sampler ) {
  16262. uvNode = uvNode.flipY();
  16263. } else {
  16264. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  16265. }
  16266. }
  16267. return uvNode;
  16268. }
  16269. /**
  16270. * Generates the uv code snippet.
  16271. *
  16272. * @param {NodeBuilder} builder - The current node builder.
  16273. * @param {Node} uvNode - The uv node to generate code for.
  16274. * @return {string} The generated code snippet.
  16275. */
  16276. generateUV( builder, uvNode ) {
  16277. return uvNode.build( builder, 'vec3' );
  16278. }
  16279. /**
  16280. * TODO.
  16281. *
  16282. * @param {Node<vec3>} uvNode - The uv node .
  16283. * @return {Node<vec3>} TODO.
  16284. */
  16285. normal( uvNode ) {
  16286. return normal( { texture: this, uv: uvNode } );
  16287. }
  16288. }
  16289. /**
  16290. * TSL function for creating a 3D texture node.
  16291. *
  16292. * @tsl
  16293. * @function
  16294. * @param {Data3DTexture} value - The 3D texture.
  16295. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  16296. * @param {?Node<int>} [levelNode=null] - The level node.
  16297. * @returns {Texture3DNode}
  16298. */
  16299. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  16300. /**
  16301. * Node material intended for volume rendering. The volumetric data are
  16302. * defined with an instance of {@link Data3DTexture}.
  16303. *
  16304. * @augments NodeMaterial
  16305. */
  16306. class VolumeNodeMaterial extends NodeMaterial {
  16307. static get type() {
  16308. return 'VolumeNodeMaterial';
  16309. }
  16310. /**
  16311. * Constructs a new volume node material.
  16312. *
  16313. * @param {?Object} parameters - The configuration parameter.
  16314. */
  16315. constructor( parameters ) {
  16316. super();
  16317. /**
  16318. * This flag can be used for type testing.
  16319. *
  16320. * @type {boolean}
  16321. * @readonly
  16322. * @default true
  16323. */
  16324. this.isVolumeNodeMaterial = true;
  16325. /**
  16326. * The base color of the volume.
  16327. *
  16328. * @type {Color}
  16329. * @default 100
  16330. */
  16331. this.base = new Color( 0xffffff );
  16332. /**
  16333. * A 3D data texture holding the volumetric data.
  16334. *
  16335. * @type {?Data3DTexture}
  16336. * @default null
  16337. */
  16338. this.map = null;
  16339. /**
  16340. * This number of samples for each ray that hits the mesh's surface
  16341. * and travels through the volume.
  16342. *
  16343. * @type {number}
  16344. * @default 100
  16345. */
  16346. this.steps = 100;
  16347. /**
  16348. * Callback for {@link VolumeNodeMaterial#testNode}.
  16349. *
  16350. * @callback testNodeCallback
  16351. * @param {Data3DTexture<float>} map - The 3D texture.
  16352. * @param {Node<float>} mapValue - The sampled value inside the volume.
  16353. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  16354. * @param {Node<vec4>} finalColor - The final color.
  16355. */
  16356. /**
  16357. * The volume rendering of this material works by shooting rays
  16358. * from the camera position through each fragment of the mesh's
  16359. * surface and sample the inner volume in a raymarching fashion
  16360. * multiple times.
  16361. *
  16362. * This node can be used to assign a callback function of type `Fn`
  16363. * that will be executed per sample. The callback receives the
  16364. * texture, the sampled texture value as well as position on the surface
  16365. * where the rays enters the volume. The last parameter is a color
  16366. * that allows the callback to determine the final color.
  16367. *
  16368. * @type {?testNodeCallback}
  16369. * @default null
  16370. */
  16371. this.testNode = null;
  16372. this.setValues( parameters );
  16373. }
  16374. /**
  16375. * Setups the vertex and fragment stage of this node material.
  16376. *
  16377. * @param {NodeBuilder} builder - The current node builder.
  16378. */
  16379. setup( builder ) {
  16380. const map = texture3D( this.map, null, 0 );
  16381. const hitBox = Fn( ( { orig, dir } ) => {
  16382. const box_min = vec3( -0.5 );
  16383. const box_max = vec3( 0.5 );
  16384. const inv_dir = dir.reciprocal();
  16385. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  16386. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  16387. const tmin = min$1( tmin_tmp, tmax_tmp );
  16388. const tmax = max$1( tmin_tmp, tmax_tmp );
  16389. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  16390. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  16391. return vec2( t0, t1 );
  16392. } );
  16393. this.fragmentNode = Fn( () => {
  16394. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  16395. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  16396. const rayDir = vDirection.normalize();
  16397. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  16398. bounds.x.greaterThan( bounds.y ).discard();
  16399. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  16400. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  16401. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  16402. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  16403. delta.divAssign( materialReference( 'steps', 'float' ) );
  16404. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  16405. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  16406. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  16407. if ( this.testNode !== null ) {
  16408. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  16409. } else {
  16410. // default to show surface of mesh
  16411. ac.a.assign( 1 );
  16412. Break();
  16413. }
  16414. p.addAssign( rayDir.mul( delta ) );
  16415. } );
  16416. ac.a.equal( 0 ).discard();
  16417. return vec4( ac );
  16418. } )();
  16419. super.setup( builder );
  16420. }
  16421. }
  16422. /**
  16423. * This module manages the internal animation loop of the renderer.
  16424. *
  16425. * @private
  16426. */
  16427. class Animation {
  16428. /**
  16429. * Constructs a new animation loop management component.
  16430. *
  16431. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16432. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16433. */
  16434. constructor( nodes, info ) {
  16435. /**
  16436. * Renderer component for managing nodes related logic.
  16437. *
  16438. * @type {Nodes}
  16439. */
  16440. this.nodes = nodes;
  16441. /**
  16442. * Renderer component for managing metrics and monitoring data.
  16443. *
  16444. * @type {Info}
  16445. */
  16446. this.info = info;
  16447. /**
  16448. * A reference to the context from `requestAnimationFrame()` can
  16449. * be called (usually `window`).
  16450. *
  16451. * @type {Window|XRSession}
  16452. */
  16453. this._context = self;
  16454. /**
  16455. * The user-defined animation loop.
  16456. *
  16457. * @type {?Function}
  16458. * @default null
  16459. */
  16460. this._animationLoop = null;
  16461. /**
  16462. * The requestId which is returned from the `requestAnimationFrame()` call.
  16463. * Can be used to cancel the stop the animation loop.
  16464. *
  16465. * @type {?number}
  16466. * @default null
  16467. */
  16468. this._requestId = null;
  16469. }
  16470. /**
  16471. * Starts the internal animation loop.
  16472. */
  16473. start() {
  16474. const update = ( time, frame ) => {
  16475. this._requestId = this._context.requestAnimationFrame( update );
  16476. if ( this.info.autoReset === true ) this.info.reset();
  16477. this.nodes.nodeFrame.update();
  16478. this.info.frame = this.nodes.nodeFrame.frameId;
  16479. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16480. };
  16481. update();
  16482. }
  16483. /**
  16484. * Stops the internal animation loop.
  16485. */
  16486. stop() {
  16487. this._context.cancelAnimationFrame( this._requestId );
  16488. this._requestId = null;
  16489. }
  16490. /**
  16491. * Returns the user-level animation loop.
  16492. *
  16493. * @return {Function} The animation loop.
  16494. */
  16495. getAnimationLoop() {
  16496. return this._animationLoop;
  16497. }
  16498. /**
  16499. * Defines the user-level animation loop.
  16500. *
  16501. * @param {Function} callback - The animation loop.
  16502. */
  16503. setAnimationLoop( callback ) {
  16504. this._animationLoop = callback;
  16505. }
  16506. /**
  16507. * Returns the animation context.
  16508. *
  16509. * @return {Window|XRSession} The animation context.
  16510. */
  16511. getContext() {
  16512. return this._context;
  16513. }
  16514. /**
  16515. * Defines the context in which `requestAnimationFrame()` is executed.
  16516. *
  16517. * @param {Window|XRSession} context - The context to set.
  16518. */
  16519. setContext( context ) {
  16520. this._context = context;
  16521. }
  16522. /**
  16523. * Frees all internal resources and stops the animation loop.
  16524. */
  16525. dispose() {
  16526. this.stop();
  16527. }
  16528. }
  16529. /**
  16530. * Data structure for the renderer. It allows defining values
  16531. * with chained, hierarchical keys. Keys are meant to be
  16532. * objects since the module internally works with Weak Maps
  16533. * for performance reasons.
  16534. *
  16535. * @private
  16536. */
  16537. class ChainMap {
  16538. /**
  16539. * Constructs a new Chain Map.
  16540. */
  16541. constructor() {
  16542. /**
  16543. * The root Weak Map.
  16544. *
  16545. * @type {WeakMap}
  16546. */
  16547. this.weakMap = new WeakMap();
  16548. }
  16549. /**
  16550. * Returns the value for the given array of keys.
  16551. *
  16552. * @param {Array<Object>} keys - List of keys.
  16553. * @return {any} The value. Returns `undefined` if no value was found.
  16554. */
  16555. get( keys ) {
  16556. let map = this.weakMap;
  16557. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16558. map = map.get( keys[ i ] );
  16559. if ( map === undefined ) return undefined;
  16560. }
  16561. return map.get( keys[ keys.length - 1 ] );
  16562. }
  16563. /**
  16564. * Sets the value for the given keys.
  16565. *
  16566. * @param {Array<Object>} keys - List of keys.
  16567. * @param {any} value - The value to set.
  16568. * @return {ChainMap} A reference to this Chain Map.
  16569. */
  16570. set( keys, value ) {
  16571. let map = this.weakMap;
  16572. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16573. const key = keys[ i ];
  16574. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16575. map = map.get( key );
  16576. }
  16577. map.set( keys[ keys.length - 1 ], value );
  16578. return this;
  16579. }
  16580. /**
  16581. * Deletes a value for the given keys.
  16582. *
  16583. * @param {Array<Object>} keys - The keys.
  16584. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16585. */
  16586. delete( keys ) {
  16587. let map = this.weakMap;
  16588. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16589. map = map.get( keys[ i ] );
  16590. if ( map === undefined ) return false;
  16591. }
  16592. return map.delete( keys[ keys.length - 1 ] );
  16593. }
  16594. }
  16595. let _id$9 = 0;
  16596. function getKeys( obj ) {
  16597. const keys = Object.keys( obj );
  16598. let proto = Object.getPrototypeOf( obj );
  16599. while ( proto ) {
  16600. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16601. for ( const key in descriptors ) {
  16602. if ( descriptors[ key ] !== undefined ) {
  16603. const descriptor = descriptors[ key ];
  16604. if ( descriptor && typeof descriptor.get === 'function' ) {
  16605. keys.push( key );
  16606. }
  16607. }
  16608. }
  16609. proto = Object.getPrototypeOf( proto );
  16610. }
  16611. return keys;
  16612. }
  16613. /**
  16614. * A render object is the renderer's representation of single entity that gets drawn
  16615. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16616. * scene since render objects also depend from the used material, the current render context
  16617. * and the current scene's lighting.
  16618. *
  16619. * In general, the basic process of the renderer is:
  16620. *
  16621. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16622. * - Process the render lists by calling one or more render commands for each render item.
  16623. * - For each render command, request a render object and perform the draw.
  16624. *
  16625. * The module provides an interface to get data required for the draw command like the actual
  16626. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16627. * creating render objects should only be done when necessary.
  16628. *
  16629. * @private
  16630. */
  16631. class RenderObject {
  16632. /**
  16633. * Constructs a new render object.
  16634. *
  16635. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16636. * @param {Geometries} geometries - Renderer component for managing geometries.
  16637. * @param {Renderer} renderer - The renderer.
  16638. * @param {Object3D} object - The 3D object.
  16639. * @param {Material} material - The 3D object's material.
  16640. * @param {Scene} scene - The scene the 3D object belongs to.
  16641. * @param {Camera} camera - The camera the object should be rendered with.
  16642. * @param {LightsNode} lightsNode - The lights node.
  16643. * @param {RenderContext} renderContext - The render context.
  16644. * @param {ClippingContext} clippingContext - The clipping context.
  16645. */
  16646. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16647. this.id = _id$9 ++;
  16648. /**
  16649. * Renderer component for managing nodes related logic.
  16650. *
  16651. * @type {Nodes}
  16652. * @private
  16653. */
  16654. this._nodes = nodes;
  16655. /**
  16656. * Renderer component for managing geometries.
  16657. *
  16658. * @type {Geometries}
  16659. * @private
  16660. */
  16661. this._geometries = geometries;
  16662. /**
  16663. * The renderer.
  16664. *
  16665. * @type {Renderer}
  16666. */
  16667. this.renderer = renderer;
  16668. /**
  16669. * The 3D object.
  16670. *
  16671. * @type {Object3D}
  16672. */
  16673. this.object = object;
  16674. /**
  16675. * The 3D object's material.
  16676. *
  16677. * @type {Material}
  16678. */
  16679. this.material = material;
  16680. /**
  16681. * The scene the 3D object belongs to.
  16682. *
  16683. * @type {Scene}
  16684. */
  16685. this.scene = scene;
  16686. /**
  16687. * The camera the 3D object should be rendered with.
  16688. *
  16689. * @type {Camera}
  16690. */
  16691. this.camera = camera;
  16692. /**
  16693. * The lights node.
  16694. *
  16695. * @type {LightsNode}
  16696. */
  16697. this.lightsNode = lightsNode;
  16698. /**
  16699. * The render context.
  16700. *
  16701. * @type {RenderContext}
  16702. */
  16703. this.context = renderContext;
  16704. /**
  16705. * The 3D object's geometry.
  16706. *
  16707. * @type {BufferGeometry}
  16708. */
  16709. this.geometry = object.geometry;
  16710. /**
  16711. * The render object's version.
  16712. *
  16713. * @type {number}
  16714. */
  16715. this.version = material.version;
  16716. /**
  16717. * The draw range of the geometry.
  16718. *
  16719. * @type {?Object}
  16720. * @default null
  16721. */
  16722. this.drawRange = null;
  16723. /**
  16724. * An array holding the buffer attributes
  16725. * of the render object. This entails attribute
  16726. * definitions on geometry and node level.
  16727. *
  16728. * @type {?Array<BufferAttribute>}
  16729. * @default null
  16730. */
  16731. this.attributes = null;
  16732. /**
  16733. * A reference to a render pipeline the render
  16734. * object is processed with.
  16735. *
  16736. * @type {RenderPipeline}
  16737. * @default null
  16738. */
  16739. this.pipeline = null;
  16740. /**
  16741. * Only relevant for objects using
  16742. * multiple materials. This represents a group entry
  16743. * from the respective `BufferGeometry`.
  16744. *
  16745. * @type {?{start: number, count: number}}
  16746. * @default null
  16747. */
  16748. this.group = null;
  16749. /**
  16750. * An array holding the vertex buffers which can
  16751. * be buffer attributes but also interleaved buffers.
  16752. *
  16753. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  16754. * @default null
  16755. */
  16756. this.vertexBuffers = null;
  16757. /**
  16758. * The parameters for the draw command.
  16759. *
  16760. * @type {?Object}
  16761. * @default null
  16762. */
  16763. this.drawParams = null;
  16764. /**
  16765. * If this render object is used inside a render bundle,
  16766. * this property points to the respective bundle group.
  16767. *
  16768. * @type {?BundleGroup}
  16769. * @default null
  16770. */
  16771. this.bundle = null;
  16772. /**
  16773. * The clipping context.
  16774. *
  16775. * @type {ClippingContext}
  16776. */
  16777. this.clippingContext = clippingContext;
  16778. /**
  16779. * The clipping context's cache key.
  16780. *
  16781. * @type {string}
  16782. */
  16783. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16784. /**
  16785. * The initial node cache key.
  16786. *
  16787. * @type {number}
  16788. */
  16789. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16790. /**
  16791. * The initial cache key.
  16792. *
  16793. * @type {number}
  16794. */
  16795. this.initialCacheKey = this.getCacheKey();
  16796. /**
  16797. * The node builder state.
  16798. *
  16799. * @type {?NodeBuilderState}
  16800. * @private
  16801. * @default null
  16802. */
  16803. this._nodeBuilderState = null;
  16804. /**
  16805. * An array of bindings.
  16806. *
  16807. * @type {?Array<BindGroup>}
  16808. * @private
  16809. * @default null
  16810. */
  16811. this._bindings = null;
  16812. /**
  16813. * Reference to the node material observer.
  16814. *
  16815. * @type {?NodeMaterialObserver}
  16816. * @private
  16817. * @default null
  16818. */
  16819. this._monitor = null;
  16820. /**
  16821. * An event listener which is defined by `RenderObjects`. It performs
  16822. * clean up tasks when `dispose()` on this render object.
  16823. *
  16824. * @method
  16825. */
  16826. this.onDispose = null;
  16827. /**
  16828. * This flag can be used for type testing.
  16829. *
  16830. * @type {boolean}
  16831. * @readonly
  16832. * @default true
  16833. */
  16834. this.isRenderObject = true;
  16835. /**
  16836. * An event listener which is executed when `dispose()` is called on
  16837. * the render object's material.
  16838. *
  16839. * @method
  16840. */
  16841. this.onMaterialDispose = () => {
  16842. this.dispose();
  16843. };
  16844. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16845. }
  16846. /**
  16847. * Updates the clipping context.
  16848. *
  16849. * @param {ClippingContext} context - The clipping context to set.
  16850. */
  16851. updateClipping( context ) {
  16852. this.clippingContext = context;
  16853. }
  16854. /**
  16855. * Whether the clipping requires an update or not.
  16856. *
  16857. * @type {boolean}
  16858. * @readonly
  16859. */
  16860. get clippingNeedsUpdate() {
  16861. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16862. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16863. return true;
  16864. }
  16865. /**
  16866. * The number of clipping planes defined in context of hardware clipping.
  16867. *
  16868. * @type {number}
  16869. * @readonly
  16870. */
  16871. get hardwareClippingPlanes() {
  16872. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16873. }
  16874. /**
  16875. * Returns the node builder state of this render object.
  16876. *
  16877. * @return {NodeBuilderState} The node builder state.
  16878. */
  16879. getNodeBuilderState() {
  16880. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16881. }
  16882. /**
  16883. * Returns the node material observer of this render object.
  16884. *
  16885. * @return {NodeMaterialObserver} The node material observer.
  16886. */
  16887. getMonitor() {
  16888. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  16889. }
  16890. /**
  16891. * Returns an array of bind groups of this render object.
  16892. *
  16893. * @return {Array<BindGroup>} The bindings.
  16894. */
  16895. getBindings() {
  16896. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16897. }
  16898. /**
  16899. * Returns a binding group by group name of this render object.
  16900. *
  16901. * @param {string} name - The name of the binding group.
  16902. * @return {?BindGroup} The bindings.
  16903. */
  16904. getBindingGroup( name ) {
  16905. for ( const bindingGroup of this.getBindings() ) {
  16906. if ( bindingGroup.name === name ) {
  16907. return bindingGroup;
  16908. }
  16909. }
  16910. }
  16911. /**
  16912. * Returns the index of the render object's geometry.
  16913. *
  16914. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  16915. */
  16916. getIndex() {
  16917. return this._geometries.getIndex( this );
  16918. }
  16919. /**
  16920. * Returns the indirect buffer attribute.
  16921. *
  16922. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  16923. */
  16924. getIndirect() {
  16925. return this._geometries.getIndirect( this );
  16926. }
  16927. /**
  16928. * Returns an array that acts as a key for identifying the render object in a chain map.
  16929. *
  16930. * @return {Array<Object>} An array with object references.
  16931. */
  16932. getChainArray() {
  16933. return [ this.object, this.material, this.context, this.lightsNode ];
  16934. }
  16935. /**
  16936. * This method is used when the geometry of a 3D object has been exchanged and the
  16937. * respective render object now requires an update.
  16938. *
  16939. * @param {BufferGeometry} geometry - The geometry to set.
  16940. */
  16941. setGeometry( geometry ) {
  16942. this.geometry = geometry;
  16943. this.attributes = null;
  16944. }
  16945. /**
  16946. * Returns the buffer attributes of the render object. The returned array holds
  16947. * attribute definitions on geometry and node level.
  16948. *
  16949. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16950. */
  16951. getAttributes() {
  16952. if ( this.attributes !== null ) return this.attributes;
  16953. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16954. const geometry = this.geometry;
  16955. const attributes = [];
  16956. const vertexBuffers = new Set();
  16957. for ( const nodeAttribute of nodeAttributes ) {
  16958. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16959. if ( attribute === undefined ) continue;
  16960. attributes.push( attribute );
  16961. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16962. vertexBuffers.add( bufferAttribute );
  16963. }
  16964. this.attributes = attributes;
  16965. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16966. return attributes;
  16967. }
  16968. /**
  16969. * Returns the vertex buffers of the render object.
  16970. *
  16971. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16972. */
  16973. getVertexBuffers() {
  16974. if ( this.vertexBuffers === null ) this.getAttributes();
  16975. return this.vertexBuffers;
  16976. }
  16977. /**
  16978. * Returns the draw parameters for the render object.
  16979. *
  16980. * @return {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  16981. */
  16982. getDrawParameters() {
  16983. const { object, material, geometry, group, drawRange } = this;
  16984. const drawParams = this.drawParams || ( this.drawParams = {
  16985. vertexCount: 0,
  16986. firstVertex: 0,
  16987. instanceCount: 0,
  16988. firstInstance: 0
  16989. } );
  16990. const index = this.getIndex();
  16991. const hasIndex = ( index !== null );
  16992. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16993. if ( instanceCount === 0 ) return null;
  16994. drawParams.instanceCount = instanceCount;
  16995. if ( object.isBatchedMesh === true ) return drawParams;
  16996. let rangeFactor = 1;
  16997. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16998. rangeFactor = 2;
  16999. }
  17000. let firstVertex = drawRange.start * rangeFactor;
  17001. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  17002. if ( group !== null ) {
  17003. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  17004. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  17005. }
  17006. const position = geometry.attributes.position;
  17007. let itemCount = Infinity;
  17008. if ( hasIndex ) {
  17009. itemCount = index.count;
  17010. } else if ( position !== undefined && position !== null ) {
  17011. itemCount = position.count;
  17012. }
  17013. firstVertex = Math.max( firstVertex, 0 );
  17014. lastVertex = Math.min( lastVertex, itemCount );
  17015. const count = lastVertex - firstVertex;
  17016. if ( count < 0 || count === Infinity ) return null;
  17017. drawParams.vertexCount = count;
  17018. drawParams.firstVertex = firstVertex;
  17019. return drawParams;
  17020. }
  17021. /**
  17022. * Returns the render object's geometry cache key.
  17023. *
  17024. * The geometry cache key is part of the material cache key.
  17025. *
  17026. * @return {string} The geometry cache key.
  17027. */
  17028. getGeometryCacheKey() {
  17029. const { geometry } = this;
  17030. let cacheKey = '';
  17031. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  17032. const attribute = geometry.attributes[ name ];
  17033. cacheKey += name + ',';
  17034. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  17035. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  17036. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  17037. if ( attribute.normalized ) cacheKey += 'n,';
  17038. }
  17039. // structural equality isn't sufficient for morph targets since the
  17040. // data are maintained in textures. only if the targets are all equal
  17041. // the texture and thus the instance of `MorphNode` can be shared.
  17042. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  17043. const targets = geometry.morphAttributes[ name ];
  17044. cacheKey += 'morph-' + name + ',';
  17045. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  17046. const attribute = targets[ i ];
  17047. cacheKey += attribute.id + ',';
  17048. }
  17049. }
  17050. if ( geometry.index ) {
  17051. cacheKey += 'index,';
  17052. }
  17053. return cacheKey;
  17054. }
  17055. /**
  17056. * Returns the render object's material cache key.
  17057. *
  17058. * The material cache key is part of the render object cache key.
  17059. *
  17060. * @return {number} The material cache key.
  17061. */
  17062. getMaterialCacheKey() {
  17063. const { object, material } = this;
  17064. let cacheKey = material.customProgramCacheKey();
  17065. for ( const property of getKeys( material ) ) {
  17066. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  17067. const value = material[ property ];
  17068. let valueKey;
  17069. if ( value !== null ) {
  17070. // some material values require a formatting
  17071. const type = typeof value;
  17072. if ( type === 'number' ) {
  17073. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  17074. } else if ( type === 'object' ) {
  17075. valueKey = '{';
  17076. if ( value.isTexture ) {
  17077. valueKey += value.mapping;
  17078. }
  17079. valueKey += '}';
  17080. } else {
  17081. valueKey = String( value );
  17082. }
  17083. } else {
  17084. valueKey = String( value );
  17085. }
  17086. cacheKey += /*property + ':' +*/ valueKey + ',';
  17087. }
  17088. cacheKey += this.clippingContextCacheKey + ',';
  17089. if ( object.geometry ) {
  17090. cacheKey += this.getGeometryCacheKey();
  17091. }
  17092. if ( object.skeleton ) {
  17093. cacheKey += object.skeleton.bones.length + ',';
  17094. }
  17095. if ( object.isBatchedMesh ) {
  17096. cacheKey += object._matricesTexture.uuid + ',';
  17097. if ( object._colorsTexture !== null ) {
  17098. cacheKey += object._colorsTexture.uuid + ',';
  17099. }
  17100. }
  17101. if ( object.count > 1 ) {
  17102. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  17103. cacheKey += object.uuid + ',';
  17104. }
  17105. cacheKey += object.receiveShadow + ',';
  17106. return hashString( cacheKey );
  17107. }
  17108. /**
  17109. * Whether the geometry requires an update or not.
  17110. *
  17111. * @type {boolean}
  17112. * @readonly
  17113. */
  17114. get needsGeometryUpdate() {
  17115. return this.geometry.id !== this.object.geometry.id;
  17116. }
  17117. /**
  17118. * Whether the render object requires an update or not.
  17119. *
  17120. * Note: There are two distinct places where render objects are checked for an update.
  17121. *
  17122. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  17123. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  17124. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  17125. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  17126. * a need for a refresh due to material, geometry or object related value changes.
  17127. *
  17128. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  17129. * that performs the 'needsUpdate' check.
  17130. *
  17131. * @type {boolean}
  17132. * @readonly
  17133. */
  17134. get needsUpdate() {
  17135. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  17136. }
  17137. /**
  17138. * Returns the dynamic cache key which represents a key that is computed per draw command.
  17139. *
  17140. * @return {number} The cache key.
  17141. */
  17142. getDynamicCacheKey() {
  17143. let cacheKey = 0;
  17144. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  17145. // the renderer is inside a shadow pass.
  17146. if ( this.material.isShadowPassMaterial !== true ) {
  17147. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  17148. }
  17149. if ( this.camera.isArrayCamera ) {
  17150. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  17151. }
  17152. if ( this.object.receiveShadow ) {
  17153. cacheKey = hash$1( cacheKey, 1 );
  17154. }
  17155. return cacheKey;
  17156. }
  17157. /**
  17158. * Returns the render object's cache key.
  17159. *
  17160. * @return {number} The cache key.
  17161. */
  17162. getCacheKey() {
  17163. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  17164. }
  17165. /**
  17166. * Frees internal resources.
  17167. */
  17168. dispose() {
  17169. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  17170. this.onDispose();
  17171. }
  17172. }
  17173. const _chainKeys$5 = [];
  17174. /**
  17175. * This module manages the render objects of the renderer.
  17176. *
  17177. * @private
  17178. */
  17179. class RenderObjects {
  17180. /**
  17181. * Constructs a new render object management component.
  17182. *
  17183. * @param {Renderer} renderer - The renderer.
  17184. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17185. * @param {Geometries} geometries - Renderer component for managing geometries.
  17186. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17187. * @param {Bindings} bindings - Renderer component for managing bindings.
  17188. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17189. */
  17190. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  17191. /**
  17192. * The renderer.
  17193. *
  17194. * @type {Renderer}
  17195. */
  17196. this.renderer = renderer;
  17197. /**
  17198. * Renderer component for managing nodes related logic.
  17199. *
  17200. * @type {Nodes}
  17201. */
  17202. this.nodes = nodes;
  17203. /**
  17204. * Renderer component for managing geometries.
  17205. *
  17206. * @type {Geometries}
  17207. */
  17208. this.geometries = geometries;
  17209. /**
  17210. * Renderer component for managing pipelines.
  17211. *
  17212. * @type {Pipelines}
  17213. */
  17214. this.pipelines = pipelines;
  17215. /**
  17216. * Renderer component for managing bindings.
  17217. *
  17218. * @type {Bindings}
  17219. */
  17220. this.bindings = bindings;
  17221. /**
  17222. * Renderer component for managing metrics and monitoring data.
  17223. *
  17224. * @type {Info}
  17225. */
  17226. this.info = info;
  17227. /**
  17228. * A dictionary that manages render contexts in chain maps
  17229. * for each pass ID.
  17230. *
  17231. * @type {Object<string,ChainMap>}
  17232. */
  17233. this.chainMaps = {};
  17234. }
  17235. /**
  17236. * Returns a render object for the given object and state data.
  17237. *
  17238. * @param {Object3D} object - The 3D object.
  17239. * @param {Material} material - The 3D object's material.
  17240. * @param {Scene} scene - The scene the 3D object belongs to.
  17241. * @param {Camera} camera - The camera the 3D object should be rendered with.
  17242. * @param {LightsNode} lightsNode - The lights node.
  17243. * @param {RenderContext} renderContext - The render context.
  17244. * @param {ClippingContext} clippingContext - The clipping context.
  17245. * @param {?string} passId - An optional ID for identifying the pass.
  17246. * @return {RenderObject} The render object.
  17247. */
  17248. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17249. const chainMap = this.getChainMap( passId );
  17250. // reuse chainArray
  17251. _chainKeys$5[ 0 ] = object;
  17252. _chainKeys$5[ 1 ] = material;
  17253. _chainKeys$5[ 2 ] = renderContext;
  17254. _chainKeys$5[ 3 ] = lightsNode;
  17255. let renderObject = chainMap.get( _chainKeys$5 );
  17256. if ( renderObject === undefined ) {
  17257. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17258. chainMap.set( _chainKeys$5, renderObject );
  17259. } else {
  17260. renderObject.updateClipping( clippingContext );
  17261. if ( renderObject.needsGeometryUpdate ) {
  17262. renderObject.setGeometry( object.geometry );
  17263. }
  17264. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  17265. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  17266. renderObject.dispose();
  17267. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17268. } else {
  17269. renderObject.version = material.version;
  17270. }
  17271. }
  17272. }
  17273. _chainKeys$5.length = 0;
  17274. return renderObject;
  17275. }
  17276. /**
  17277. * Returns a chain map for the given pass ID.
  17278. *
  17279. * @param {string} [passId='default'] - The pass ID.
  17280. * @return {ChainMap} The chain map.
  17281. */
  17282. getChainMap( passId = 'default' ) {
  17283. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  17284. }
  17285. /**
  17286. * Frees internal resources.
  17287. */
  17288. dispose() {
  17289. this.chainMaps = {};
  17290. }
  17291. /**
  17292. * Factory method for creating render objects with the given list of parameters.
  17293. *
  17294. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17295. * @param {Geometries} geometries - Renderer component for managing geometries.
  17296. * @param {Renderer} renderer - The renderer.
  17297. * @param {Object3D} object - The 3D object.
  17298. * @param {Material} material - The object's material.
  17299. * @param {Scene} scene - The scene the 3D object belongs to.
  17300. * @param {Camera} camera - The camera the object should be rendered with.
  17301. * @param {LightsNode} lightsNode - The lights node.
  17302. * @param {RenderContext} renderContext - The render context.
  17303. * @param {ClippingContext} clippingContext - The clipping context.
  17304. * @param {?string} passId - An optional ID for identifying the pass.
  17305. * @return {RenderObject} The render object.
  17306. */
  17307. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17308. const chainMap = this.getChainMap( passId );
  17309. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  17310. renderObject.onDispose = () => {
  17311. this.pipelines.delete( renderObject );
  17312. this.bindings.delete( renderObject );
  17313. this.nodes.delete( renderObject );
  17314. chainMap.delete( renderObject.getChainArray() );
  17315. };
  17316. return renderObject;
  17317. }
  17318. }
  17319. /**
  17320. * Data structure for the renderer. It is intended to manage
  17321. * data of objects in dictionaries.
  17322. *
  17323. * @private
  17324. */
  17325. class DataMap {
  17326. /**
  17327. * Constructs a new data map.
  17328. */
  17329. constructor() {
  17330. /**
  17331. * `DataMap` internally uses a weak map
  17332. * to manage its data.
  17333. *
  17334. * @type {WeakMap}
  17335. */
  17336. this.data = new WeakMap();
  17337. }
  17338. /**
  17339. * Returns the dictionary for the given object.
  17340. *
  17341. * @param {Object} object - The object.
  17342. * @return {Object} The dictionary.
  17343. */
  17344. get( object ) {
  17345. let map = this.data.get( object );
  17346. if ( map === undefined ) {
  17347. map = {};
  17348. this.data.set( object, map );
  17349. }
  17350. return map;
  17351. }
  17352. /**
  17353. * Deletes the dictionary for the given object.
  17354. *
  17355. * @param {Object} object - The object.
  17356. * @return {?Object} The deleted dictionary.
  17357. */
  17358. delete( object ) {
  17359. let map = null;
  17360. if ( this.data.has( object ) ) {
  17361. map = this.data.get( object );
  17362. this.data.delete( object );
  17363. }
  17364. return map;
  17365. }
  17366. /**
  17367. * Returns `true` if the given object has a dictionary defined.
  17368. *
  17369. * @param {Object} object - The object to test.
  17370. * @return {boolean} Whether a dictionary is defined or not.
  17371. */
  17372. has( object ) {
  17373. return this.data.has( object );
  17374. }
  17375. /**
  17376. * Frees internal resources.
  17377. */
  17378. dispose() {
  17379. this.data = new WeakMap();
  17380. }
  17381. }
  17382. const AttributeType = {
  17383. VERTEX: 1,
  17384. INDEX: 2,
  17385. STORAGE: 3,
  17386. INDIRECT: 4
  17387. };
  17388. // size of a chunk in bytes (STD140 layout)
  17389. const GPU_CHUNK_BYTES = 16;
  17390. // @TODO: Move to src/constants.js
  17391. const BlendColorFactor = 211;
  17392. const OneMinusBlendColorFactor = 212;
  17393. /**
  17394. * This renderer module manages geometry attributes.
  17395. *
  17396. * @private
  17397. * @augments DataMap
  17398. */
  17399. class Attributes extends DataMap {
  17400. /**
  17401. * Constructs a new attribute management component.
  17402. *
  17403. * @param {Backend} backend - The renderer's backend.
  17404. */
  17405. constructor( backend ) {
  17406. super();
  17407. /**
  17408. * The renderer's backend.
  17409. *
  17410. * @type {Backend}
  17411. */
  17412. this.backend = backend;
  17413. }
  17414. /**
  17415. * Deletes the data for the given attribute.
  17416. *
  17417. * @param {BufferAttribute} attribute - The attribute.
  17418. * @return {Object} The deleted attribute data.
  17419. */
  17420. delete( attribute ) {
  17421. const attributeData = super.delete( attribute );
  17422. if ( attributeData !== undefined ) {
  17423. this.backend.destroyAttribute( attribute );
  17424. }
  17425. return attributeData;
  17426. }
  17427. /**
  17428. * Updates the given attribute. This method creates attribute buffers
  17429. * for new attributes and updates data for existing ones.
  17430. *
  17431. * @param {BufferAttribute} attribute - The attribute to update.
  17432. * @param {number} type - The attribute type.
  17433. */
  17434. update( attribute, type ) {
  17435. const data = this.get( attribute );
  17436. if ( data.version === undefined ) {
  17437. if ( type === AttributeType.VERTEX ) {
  17438. this.backend.createAttribute( attribute );
  17439. } else if ( type === AttributeType.INDEX ) {
  17440. this.backend.createIndexAttribute( attribute );
  17441. } else if ( type === AttributeType.STORAGE ) {
  17442. this.backend.createStorageAttribute( attribute );
  17443. } else if ( type === AttributeType.INDIRECT ) {
  17444. this.backend.createIndirectStorageAttribute( attribute );
  17445. }
  17446. data.version = this._getBufferAttribute( attribute ).version;
  17447. } else {
  17448. const bufferAttribute = this._getBufferAttribute( attribute );
  17449. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  17450. this.backend.updateAttribute( attribute );
  17451. data.version = bufferAttribute.version;
  17452. }
  17453. }
  17454. }
  17455. /**
  17456. * Utility method for handling interleaved buffer attributes correctly.
  17457. * To process them, their `InterleavedBuffer` is returned.
  17458. *
  17459. * @param {BufferAttribute} attribute - The attribute.
  17460. * @return {BufferAttribute|InterleavedBuffer}
  17461. */
  17462. _getBufferAttribute( attribute ) {
  17463. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  17464. return attribute;
  17465. }
  17466. }
  17467. /**
  17468. * Returns the wireframe version for the given geometry.
  17469. *
  17470. * @private
  17471. * @function
  17472. * @param {BufferGeometry} geometry - The geometry.
  17473. * @return {number} The version.
  17474. */
  17475. function getWireframeVersion( geometry ) {
  17476. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17477. }
  17478. /**
  17479. * Returns a wireframe index attribute for the given geometry.
  17480. *
  17481. * @private
  17482. * @function
  17483. * @param {BufferGeometry} geometry - The geometry.
  17484. * @return {BufferAttribute} The wireframe index attribute.
  17485. */
  17486. function getWireframeIndex( geometry ) {
  17487. const indices = [];
  17488. const geometryIndex = geometry.index;
  17489. const geometryPosition = geometry.attributes.position;
  17490. if ( geometryIndex !== null ) {
  17491. const array = geometryIndex.array;
  17492. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17493. const a = array[ i + 0 ];
  17494. const b = array[ i + 1 ];
  17495. const c = array[ i + 2 ];
  17496. indices.push( a, b, b, c, c, a );
  17497. }
  17498. } else {
  17499. const array = geometryPosition.array;
  17500. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17501. const a = i + 0;
  17502. const b = i + 1;
  17503. const c = i + 2;
  17504. indices.push( a, b, b, c, c, a );
  17505. }
  17506. }
  17507. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17508. attribute.version = getWireframeVersion( geometry );
  17509. return attribute;
  17510. }
  17511. /**
  17512. * This renderer module manages geometries.
  17513. *
  17514. * @private
  17515. * @augments DataMap
  17516. */
  17517. class Geometries extends DataMap {
  17518. /**
  17519. * Constructs a new geometry management component.
  17520. *
  17521. * @param {Attributes} attributes - Renderer component for managing attributes.
  17522. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17523. */
  17524. constructor( attributes, info ) {
  17525. super();
  17526. /**
  17527. * Renderer component for managing attributes.
  17528. *
  17529. * @type {Attributes}
  17530. */
  17531. this.attributes = attributes;
  17532. /**
  17533. * Renderer component for managing metrics and monitoring data.
  17534. *
  17535. * @type {Info}
  17536. */
  17537. this.info = info;
  17538. /**
  17539. * Weak Map for managing attributes for wireframe rendering.
  17540. *
  17541. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17542. */
  17543. this.wireframes = new WeakMap();
  17544. /**
  17545. * This Weak Map is used to make sure buffer attributes are
  17546. * updated only once per render call.
  17547. *
  17548. * @type {WeakMap<BufferAttribute,number>}
  17549. */
  17550. this.attributeCall = new WeakMap();
  17551. }
  17552. /**
  17553. * Returns `true` if the given render object has an initialized geometry.
  17554. *
  17555. * @param {RenderObject} renderObject - The render object.
  17556. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  17557. */
  17558. has( renderObject ) {
  17559. const geometry = renderObject.geometry;
  17560. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17561. }
  17562. /**
  17563. * Prepares the geometry of the given render object for rendering.
  17564. *
  17565. * @param {RenderObject} renderObject - The render object.
  17566. */
  17567. updateForRender( renderObject ) {
  17568. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17569. this.updateAttributes( renderObject );
  17570. }
  17571. /**
  17572. * Initializes the geometry of the given render object.
  17573. *
  17574. * @param {RenderObject} renderObject - The render object.
  17575. */
  17576. initGeometry( renderObject ) {
  17577. const geometry = renderObject.geometry;
  17578. const geometryData = this.get( geometry );
  17579. geometryData.initialized = true;
  17580. this.info.memory.geometries ++;
  17581. const onDispose = () => {
  17582. this.info.memory.geometries --;
  17583. const index = geometry.index;
  17584. const geometryAttributes = renderObject.getAttributes();
  17585. if ( index !== null ) {
  17586. this.attributes.delete( index );
  17587. }
  17588. for ( const geometryAttribute of geometryAttributes ) {
  17589. this.attributes.delete( geometryAttribute );
  17590. }
  17591. const wireframeAttribute = this.wireframes.get( geometry );
  17592. if ( wireframeAttribute !== undefined ) {
  17593. this.attributes.delete( wireframeAttribute );
  17594. }
  17595. geometry.removeEventListener( 'dispose', onDispose );
  17596. };
  17597. geometry.addEventListener( 'dispose', onDispose );
  17598. }
  17599. /**
  17600. * Updates the geometry attributes of the given render object.
  17601. *
  17602. * @param {RenderObject} renderObject - The render object.
  17603. */
  17604. updateAttributes( renderObject ) {
  17605. // attributes
  17606. const attributes = renderObject.getAttributes();
  17607. for ( const attribute of attributes ) {
  17608. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17609. this.updateAttribute( attribute, AttributeType.STORAGE );
  17610. } else {
  17611. this.updateAttribute( attribute, AttributeType.VERTEX );
  17612. }
  17613. }
  17614. // indexes
  17615. const index = this.getIndex( renderObject );
  17616. if ( index !== null ) {
  17617. this.updateAttribute( index, AttributeType.INDEX );
  17618. }
  17619. // indirect
  17620. const indirect = renderObject.geometry.indirect;
  17621. if ( indirect !== null ) {
  17622. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17623. }
  17624. }
  17625. /**
  17626. * Updates the given attribute.
  17627. *
  17628. * @param {BufferAttribute} attribute - The attribute to update.
  17629. * @param {number} type - The attribute type.
  17630. */
  17631. updateAttribute( attribute, type ) {
  17632. const callId = this.info.render.calls;
  17633. if ( ! attribute.isInterleavedBufferAttribute ) {
  17634. if ( this.attributeCall.get( attribute ) !== callId ) {
  17635. this.attributes.update( attribute, type );
  17636. this.attributeCall.set( attribute, callId );
  17637. }
  17638. } else {
  17639. if ( this.attributeCall.get( attribute ) === undefined ) {
  17640. this.attributes.update( attribute, type );
  17641. this.attributeCall.set( attribute, callId );
  17642. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17643. this.attributes.update( attribute, type );
  17644. this.attributeCall.set( attribute.data, callId );
  17645. this.attributeCall.set( attribute, callId );
  17646. }
  17647. }
  17648. }
  17649. /**
  17650. * Returns the indirect buffer attribute of the given render object.
  17651. *
  17652. * @param {RenderObject} renderObject - The render object.
  17653. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  17654. */
  17655. getIndirect( renderObject ) {
  17656. return renderObject.geometry.indirect;
  17657. }
  17658. /**
  17659. * Returns the index of the given render object's geometry. This is implemented
  17660. * in a method to return a wireframe index if necessary.
  17661. *
  17662. * @param {RenderObject} renderObject - The render object.
  17663. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  17664. */
  17665. getIndex( renderObject ) {
  17666. const { geometry, material } = renderObject;
  17667. let index = geometry.index;
  17668. if ( material.wireframe === true ) {
  17669. const wireframes = this.wireframes;
  17670. let wireframeAttribute = wireframes.get( geometry );
  17671. if ( wireframeAttribute === undefined ) {
  17672. wireframeAttribute = getWireframeIndex( geometry );
  17673. wireframes.set( geometry, wireframeAttribute );
  17674. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17675. this.attributes.delete( wireframeAttribute );
  17676. wireframeAttribute = getWireframeIndex( geometry );
  17677. wireframes.set( geometry, wireframeAttribute );
  17678. }
  17679. index = wireframeAttribute;
  17680. }
  17681. return index;
  17682. }
  17683. }
  17684. /**
  17685. * This renderer module provides a series of statistical information
  17686. * about the GPU memory and the rendering process. Useful for debugging
  17687. * and monitoring.
  17688. */
  17689. class Info {
  17690. /**
  17691. * Constructs a new info component.
  17692. */
  17693. constructor() {
  17694. /**
  17695. * Whether frame related metrics should automatically
  17696. * be resetted or not. This property should be set to `false`
  17697. * by apps which manage their own animation loop. They must
  17698. * then call `renderer.info.reset()` once per frame manually.
  17699. *
  17700. * @type {boolean}
  17701. * @default true
  17702. */
  17703. this.autoReset = true;
  17704. /**
  17705. * The current frame ID. This ID is managed
  17706. * by `NodeFrame`.
  17707. *
  17708. * @type {number}
  17709. * @readonly
  17710. * @default 0
  17711. */
  17712. this.frame = 0;
  17713. /**
  17714. * The number of render calls since the
  17715. * app has been started.
  17716. *
  17717. * @type {number}
  17718. * @readonly
  17719. * @default 0
  17720. */
  17721. this.calls = 0;
  17722. /**
  17723. * Render related metrics.
  17724. *
  17725. * @type {Object}
  17726. * @readonly
  17727. * @property {number} calls - The number of render calls since the app has been started.
  17728. * @property {number} frameCalls - The number of render calls of the current frame.
  17729. * @property {number} drawCalls - The number of draw calls of the current frame.
  17730. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  17731. * @property {number} points - The number of rendered point primitives of the current frame.
  17732. * @property {number} lines - The number of rendered line primitives of the current frame.
  17733. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17734. */
  17735. this.render = {
  17736. calls: 0,
  17737. frameCalls: 0,
  17738. drawCalls: 0,
  17739. triangles: 0,
  17740. points: 0,
  17741. lines: 0,
  17742. timestamp: 0,
  17743. };
  17744. /**
  17745. * Compute related metrics.
  17746. *
  17747. * @type {Object}
  17748. * @readonly
  17749. * @property {number} calls - The number of compute calls since the app has been started.
  17750. * @property {number} frameCalls - The number of compute calls of the current frame.
  17751. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17752. */
  17753. this.compute = {
  17754. calls: 0,
  17755. frameCalls: 0,
  17756. timestamp: 0
  17757. };
  17758. /**
  17759. * Memory related metrics.
  17760. *
  17761. * @type {Object}
  17762. * @readonly
  17763. * @property {number} geometries - The number of active geometries.
  17764. * @property {number} frameCalls - The number of active textures.
  17765. */
  17766. this.memory = {
  17767. geometries: 0,
  17768. textures: 0
  17769. };
  17770. }
  17771. /**
  17772. * This method should be executed per draw call and updates the corresponding metrics.
  17773. *
  17774. * @param {Object3D} object - The 3D object that is going to be rendered.
  17775. * @param {number} count - The vertex or index count.
  17776. * @param {number} instanceCount - The instance count.
  17777. */
  17778. update( object, count, instanceCount ) {
  17779. this.render.drawCalls ++;
  17780. if ( object.isMesh || object.isSprite ) {
  17781. this.render.triangles += instanceCount * ( count / 3 );
  17782. } else if ( object.isPoints ) {
  17783. this.render.points += instanceCount * count;
  17784. } else if ( object.isLineSegments ) {
  17785. this.render.lines += instanceCount * ( count / 2 );
  17786. } else if ( object.isLine ) {
  17787. this.render.lines += instanceCount * ( count - 1 );
  17788. } else {
  17789. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17790. }
  17791. }
  17792. /**
  17793. * Resets frame related metrics.
  17794. */
  17795. reset() {
  17796. this.render.drawCalls = 0;
  17797. this.render.frameCalls = 0;
  17798. this.compute.frameCalls = 0;
  17799. this.render.triangles = 0;
  17800. this.render.points = 0;
  17801. this.render.lines = 0;
  17802. }
  17803. /**
  17804. * Performs a complete reset of the object.
  17805. */
  17806. dispose() {
  17807. this.reset();
  17808. this.calls = 0;
  17809. this.render.calls = 0;
  17810. this.compute.calls = 0;
  17811. this.render.timestamp = 0;
  17812. this.compute.timestamp = 0;
  17813. this.memory.geometries = 0;
  17814. this.memory.textures = 0;
  17815. }
  17816. }
  17817. /**
  17818. * Abstract class for representing pipelines.
  17819. *
  17820. * @private
  17821. * @abstract
  17822. */
  17823. class Pipeline {
  17824. /**
  17825. * Constructs a new pipeline.
  17826. *
  17827. * @param {string} cacheKey - The pipeline's cache key.
  17828. */
  17829. constructor( cacheKey ) {
  17830. /**
  17831. * The pipeline's cache key.
  17832. *
  17833. * @type {string}
  17834. */
  17835. this.cacheKey = cacheKey;
  17836. /**
  17837. * How often the pipeline is currently in use.
  17838. *
  17839. * @type {number}
  17840. * @default 0
  17841. */
  17842. this.usedTimes = 0;
  17843. }
  17844. }
  17845. /**
  17846. * Class for representing render pipelines.
  17847. *
  17848. * @private
  17849. * @augments Pipeline
  17850. */
  17851. class RenderPipeline extends Pipeline {
  17852. /**
  17853. * Constructs a new render pipeline.
  17854. *
  17855. * @param {string} cacheKey - The pipeline's cache key.
  17856. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17857. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17858. */
  17859. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17860. super( cacheKey );
  17861. /**
  17862. * The pipeline's vertex shader.
  17863. *
  17864. * @type {ProgrammableStage}
  17865. */
  17866. this.vertexProgram = vertexProgram;
  17867. /**
  17868. * The pipeline's fragment shader.
  17869. *
  17870. * @type {ProgrammableStage}
  17871. */
  17872. this.fragmentProgram = fragmentProgram;
  17873. }
  17874. }
  17875. /**
  17876. * Class for representing compute pipelines.
  17877. *
  17878. * @private
  17879. * @augments Pipeline
  17880. */
  17881. class ComputePipeline extends Pipeline {
  17882. /**
  17883. * Constructs a new render pipeline.
  17884. *
  17885. * @param {string} cacheKey - The pipeline's cache key.
  17886. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17887. */
  17888. constructor( cacheKey, computeProgram ) {
  17889. super( cacheKey );
  17890. /**
  17891. * The pipeline's compute shader.
  17892. *
  17893. * @type {ProgrammableStage}
  17894. */
  17895. this.computeProgram = computeProgram;
  17896. /**
  17897. * This flag can be used for type testing.
  17898. *
  17899. * @type {boolean}
  17900. * @readonly
  17901. * @default true
  17902. */
  17903. this.isComputePipeline = true;
  17904. }
  17905. }
  17906. let _id$8 = 0;
  17907. /**
  17908. * Class for representing programmable stages which are vertex,
  17909. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17910. * they represent the programmable part of a pipeline.
  17911. *
  17912. * @private
  17913. */
  17914. class ProgrammableStage {
  17915. /**
  17916. * Constructs a new programmable stage.
  17917. *
  17918. * @param {string} code - The shader code.
  17919. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17920. * @param {string} name - The name of the shader.
  17921. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17922. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17923. */
  17924. constructor( code, stage, name, transforms = null, attributes = null ) {
  17925. /**
  17926. * The id of the programmable stage.
  17927. *
  17928. * @type {number}
  17929. */
  17930. this.id = _id$8 ++;
  17931. /**
  17932. * The shader code.
  17933. *
  17934. * @type {string}
  17935. */
  17936. this.code = code;
  17937. /**
  17938. * The type of stage.
  17939. *
  17940. * @type {string}
  17941. */
  17942. this.stage = stage;
  17943. /**
  17944. * The name of the stage.
  17945. * This is used for debugging purposes.
  17946. *
  17947. * @type {string}
  17948. */
  17949. this.name = name;
  17950. /**
  17951. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17952. *
  17953. * @type {?Array<Object>}
  17954. */
  17955. this.transforms = transforms;
  17956. /**
  17957. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17958. *
  17959. * @type {?Array<Object>}
  17960. */
  17961. this.attributes = attributes;
  17962. /**
  17963. * How often the programmable stage is currently in use.
  17964. *
  17965. * @type {number}
  17966. * @default 0
  17967. */
  17968. this.usedTimes = 0;
  17969. }
  17970. }
  17971. /**
  17972. * This renderer module manages the pipelines of the renderer.
  17973. *
  17974. * @private
  17975. * @augments DataMap
  17976. */
  17977. class Pipelines extends DataMap {
  17978. /**
  17979. * Constructs a new pipeline management component.
  17980. *
  17981. * @param {Backend} backend - The renderer's backend.
  17982. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17983. */
  17984. constructor( backend, nodes ) {
  17985. super();
  17986. /**
  17987. * The renderer's backend.
  17988. *
  17989. * @type {Backend}
  17990. */
  17991. this.backend = backend;
  17992. /**
  17993. * Renderer component for managing nodes related logic.
  17994. *
  17995. * @type {Nodes}
  17996. */
  17997. this.nodes = nodes;
  17998. /**
  17999. * A references to the bindings management component.
  18000. * This reference will be set inside the `Bindings`
  18001. * constructor.
  18002. *
  18003. * @type {?Bindings}
  18004. * @default null
  18005. */
  18006. this.bindings = null;
  18007. /**
  18008. * Internal cache for maintaining pipelines.
  18009. * The key of the map is a cache key, the value the pipeline.
  18010. *
  18011. * @type {Map<string,Pipeline>}
  18012. */
  18013. this.caches = new Map();
  18014. /**
  18015. * This dictionary maintains for each shader stage type (vertex,
  18016. * fragment and compute) the programmable stage objects which
  18017. * represent the actual shader code.
  18018. *
  18019. * @type {Object<string,Map>}
  18020. */
  18021. this.programs = {
  18022. vertex: new Map(),
  18023. fragment: new Map(),
  18024. compute: new Map()
  18025. };
  18026. }
  18027. /**
  18028. * Returns a compute pipeline for the given compute node.
  18029. *
  18030. * @param {Node} computeNode - The compute node.
  18031. * @param {Array<BindGroup>} bindings - The bindings.
  18032. * @return {ComputePipeline} The compute pipeline.
  18033. */
  18034. getForCompute( computeNode, bindings ) {
  18035. const { backend } = this;
  18036. const data = this.get( computeNode );
  18037. if ( this._needsComputeUpdate( computeNode ) ) {
  18038. const previousPipeline = data.pipeline;
  18039. if ( previousPipeline ) {
  18040. previousPipeline.usedTimes --;
  18041. previousPipeline.computeProgram.usedTimes --;
  18042. }
  18043. // get shader
  18044. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  18045. // programmable stage
  18046. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  18047. if ( stageCompute === undefined ) {
  18048. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  18049. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  18050. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  18051. backend.createProgram( stageCompute );
  18052. }
  18053. // determine compute pipeline
  18054. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  18055. let pipeline = this.caches.get( cacheKey );
  18056. if ( pipeline === undefined ) {
  18057. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18058. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  18059. }
  18060. // keep track of all used times
  18061. pipeline.usedTimes ++;
  18062. stageCompute.usedTimes ++;
  18063. //
  18064. data.version = computeNode.version;
  18065. data.pipeline = pipeline;
  18066. }
  18067. return data.pipeline;
  18068. }
  18069. /**
  18070. * Returns a render pipeline for the given render object.
  18071. *
  18072. * @param {RenderObject} renderObject - The render object.
  18073. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18074. * @return {RenderPipeline} The render pipeline.
  18075. */
  18076. getForRender( renderObject, promises = null ) {
  18077. const { backend } = this;
  18078. const data = this.get( renderObject );
  18079. if ( this._needsRenderUpdate( renderObject ) ) {
  18080. const previousPipeline = data.pipeline;
  18081. if ( previousPipeline ) {
  18082. previousPipeline.usedTimes --;
  18083. previousPipeline.vertexProgram.usedTimes --;
  18084. previousPipeline.fragmentProgram.usedTimes --;
  18085. }
  18086. // get shader
  18087. const nodeBuilderState = renderObject.getNodeBuilderState();
  18088. const name = renderObject.material ? renderObject.material.name : '';
  18089. // programmable stages
  18090. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  18091. if ( stageVertex === undefined ) {
  18092. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  18093. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  18094. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  18095. backend.createProgram( stageVertex );
  18096. }
  18097. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  18098. if ( stageFragment === undefined ) {
  18099. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  18100. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  18101. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  18102. backend.createProgram( stageFragment );
  18103. }
  18104. // determine render pipeline
  18105. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18106. let pipeline = this.caches.get( cacheKey );
  18107. if ( pipeline === undefined ) {
  18108. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18109. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  18110. } else {
  18111. renderObject.pipeline = pipeline;
  18112. }
  18113. // keep track of all used times
  18114. pipeline.usedTimes ++;
  18115. stageVertex.usedTimes ++;
  18116. stageFragment.usedTimes ++;
  18117. //
  18118. data.pipeline = pipeline;
  18119. }
  18120. return data.pipeline;
  18121. }
  18122. /**
  18123. * Deletes the pipeline for the given render object.
  18124. *
  18125. * @param {RenderObject} object - The render object.
  18126. * @return {?Object} The deleted dictionary.
  18127. */
  18128. delete( object ) {
  18129. const pipeline = this.get( object ).pipeline;
  18130. if ( pipeline ) {
  18131. // pipeline
  18132. pipeline.usedTimes --;
  18133. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  18134. // programs
  18135. if ( pipeline.isComputePipeline ) {
  18136. pipeline.computeProgram.usedTimes --;
  18137. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  18138. } else {
  18139. pipeline.fragmentProgram.usedTimes --;
  18140. pipeline.vertexProgram.usedTimes --;
  18141. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  18142. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  18143. }
  18144. }
  18145. return super.delete( object );
  18146. }
  18147. /**
  18148. * Frees internal resources.
  18149. */
  18150. dispose() {
  18151. super.dispose();
  18152. this.caches = new Map();
  18153. this.programs = {
  18154. vertex: new Map(),
  18155. fragment: new Map(),
  18156. compute: new Map()
  18157. };
  18158. }
  18159. /**
  18160. * Updates the pipeline for the given render object.
  18161. *
  18162. * @param {RenderObject} renderObject - The render object.
  18163. */
  18164. updateForRender( renderObject ) {
  18165. this.getForRender( renderObject );
  18166. }
  18167. /**
  18168. * Returns a compute pipeline for the given parameters.
  18169. *
  18170. * @private
  18171. * @param {Node} computeNode - The compute node.
  18172. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18173. * @param {string} cacheKey - The cache key.
  18174. * @param {Array<BindGroup>} bindings - The bindings.
  18175. * @return {ComputePipeline} The compute pipeline.
  18176. */
  18177. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  18178. // check for existing pipeline
  18179. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  18180. let pipeline = this.caches.get( cacheKey );
  18181. if ( pipeline === undefined ) {
  18182. pipeline = new ComputePipeline( cacheKey, stageCompute );
  18183. this.caches.set( cacheKey, pipeline );
  18184. this.backend.createComputePipeline( pipeline, bindings );
  18185. }
  18186. return pipeline;
  18187. }
  18188. /**
  18189. * Returns a render pipeline for the given parameters.
  18190. *
  18191. * @private
  18192. * @param {RenderObject} renderObject - The render object.
  18193. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18194. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18195. * @param {string} cacheKey - The cache key.
  18196. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18197. * @return {ComputePipeline} The compute pipeline.
  18198. */
  18199. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  18200. // check for existing pipeline
  18201. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18202. let pipeline = this.caches.get( cacheKey );
  18203. if ( pipeline === undefined ) {
  18204. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  18205. this.caches.set( cacheKey, pipeline );
  18206. renderObject.pipeline = pipeline;
  18207. // The `promises` array is `null` by default and only set to an empty array when
  18208. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  18209. // pending promises that resolve when the render pipelines are ready for rendering.
  18210. this.backend.createRenderPipeline( renderObject, promises );
  18211. }
  18212. return pipeline;
  18213. }
  18214. /**
  18215. * Computes a cache key representing a compute pipeline.
  18216. *
  18217. * @private
  18218. * @param {Node} computeNode - The compute node.
  18219. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18220. * @return {string} The cache key.
  18221. */
  18222. _getComputeCacheKey( computeNode, stageCompute ) {
  18223. return computeNode.id + ',' + stageCompute.id;
  18224. }
  18225. /**
  18226. * Computes a cache key representing a render pipeline.
  18227. *
  18228. * @private
  18229. * @param {RenderObject} renderObject - The render object.
  18230. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18231. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18232. * @return {string} The cache key.
  18233. */
  18234. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  18235. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  18236. }
  18237. /**
  18238. * Releases the given pipeline.
  18239. *
  18240. * @private
  18241. * @param {Pipeline} pipeline - The pipeline to release.
  18242. */
  18243. _releasePipeline( pipeline ) {
  18244. this.caches.delete( pipeline.cacheKey );
  18245. }
  18246. /**
  18247. * Releases the shader program.
  18248. *
  18249. * @private
  18250. * @param {Object} program - The shader program to release.
  18251. */
  18252. _releaseProgram( program ) {
  18253. const code = program.code;
  18254. const stage = program.stage;
  18255. this.programs[ stage ].delete( code );
  18256. }
  18257. /**
  18258. * Returns `true` if the compute pipeline for the given compute node requires an update.
  18259. *
  18260. * @private
  18261. * @param {Node} computeNode - The compute node.
  18262. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  18263. */
  18264. _needsComputeUpdate( computeNode ) {
  18265. const data = this.get( computeNode );
  18266. return data.pipeline === undefined || data.version !== computeNode.version;
  18267. }
  18268. /**
  18269. * Returns `true` if the render pipeline for the given render object requires an update.
  18270. *
  18271. * @private
  18272. * @param {RenderObject} renderObject - The render object.
  18273. * @return {boolean} Whether the render object for the given render object requires an update or not.
  18274. */
  18275. _needsRenderUpdate( renderObject ) {
  18276. const data = this.get( renderObject );
  18277. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  18278. }
  18279. }
  18280. /**
  18281. * This renderer module manages the bindings of the renderer.
  18282. *
  18283. * @private
  18284. * @augments DataMap
  18285. */
  18286. class Bindings extends DataMap {
  18287. /**
  18288. * Constructs a new bindings management component.
  18289. *
  18290. * @param {Backend} backend - The renderer's backend.
  18291. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18292. * @param {Textures} textures - Renderer component for managing textures.
  18293. * @param {Attributes} attributes - Renderer component for managing attributes.
  18294. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18295. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18296. */
  18297. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  18298. super();
  18299. /**
  18300. * The renderer's backend.
  18301. *
  18302. * @type {Backend}
  18303. */
  18304. this.backend = backend;
  18305. /**
  18306. * Renderer component for managing textures.
  18307. *
  18308. * @type {Textures}
  18309. */
  18310. this.textures = textures;
  18311. /**
  18312. * Renderer component for managing pipelines.
  18313. *
  18314. * @type {Pipelines}
  18315. */
  18316. this.pipelines = pipelines;
  18317. /**
  18318. * Renderer component for managing attributes.
  18319. *
  18320. * @type {Attributes}
  18321. */
  18322. this.attributes = attributes;
  18323. /**
  18324. * Renderer component for managing nodes related logic.
  18325. *
  18326. * @type {Nodes}
  18327. */
  18328. this.nodes = nodes;
  18329. /**
  18330. * Renderer component for managing metrics and monitoring data.
  18331. *
  18332. * @type {Info}
  18333. */
  18334. this.info = info;
  18335. this.pipelines.bindings = this; // assign bindings to pipelines
  18336. }
  18337. /**
  18338. * Returns the bind groups for the given render object.
  18339. *
  18340. * @param {RenderObject} renderObject - The render object.
  18341. * @return {Array<BindGroup>} The bind groups.
  18342. */
  18343. getForRender( renderObject ) {
  18344. const bindings = renderObject.getBindings();
  18345. for ( const bindGroup of bindings ) {
  18346. const groupData = this.get( bindGroup );
  18347. if ( groupData.bindGroup === undefined ) {
  18348. // each object defines an array of bindings (ubos, textures, samplers etc.)
  18349. this._init( bindGroup );
  18350. this.backend.createBindings( bindGroup, bindings, 0 );
  18351. groupData.bindGroup = bindGroup;
  18352. }
  18353. }
  18354. return bindings;
  18355. }
  18356. /**
  18357. * Returns the bind groups for the given compute node.
  18358. *
  18359. * @param {Node} computeNode - The compute node.
  18360. * @return {Array<BindGroup>} The bind groups.
  18361. */
  18362. getForCompute( computeNode ) {
  18363. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  18364. for ( const bindGroup of bindings ) {
  18365. const groupData = this.get( bindGroup );
  18366. if ( groupData.bindGroup === undefined ) {
  18367. this._init( bindGroup );
  18368. this.backend.createBindings( bindGroup, bindings, 0 );
  18369. groupData.bindGroup = bindGroup;
  18370. }
  18371. }
  18372. return bindings;
  18373. }
  18374. /**
  18375. * Updates the bindings for the given compute node.
  18376. *
  18377. * @param {Node} computeNode - The compute node.
  18378. */
  18379. updateForCompute( computeNode ) {
  18380. this._updateBindings( this.getForCompute( computeNode ) );
  18381. }
  18382. /**
  18383. * Updates the bindings for the given render object.
  18384. *
  18385. * @param {RenderObject} renderObject - The render object.
  18386. */
  18387. updateForRender( renderObject ) {
  18388. this._updateBindings( this.getForRender( renderObject ) );
  18389. }
  18390. /**
  18391. * Updates the given array of bindings.
  18392. *
  18393. * @param {Array<BindGroup>} bindings - The bind groups.
  18394. */
  18395. _updateBindings( bindings ) {
  18396. for ( const bindGroup of bindings ) {
  18397. this._update( bindGroup, bindings );
  18398. }
  18399. }
  18400. /**
  18401. * Initializes the given bind group.
  18402. *
  18403. * @param {BindGroup} bindGroup - The bind group to initialize.
  18404. */
  18405. _init( bindGroup ) {
  18406. for ( const binding of bindGroup.bindings ) {
  18407. if ( binding.isSampledTexture ) {
  18408. this.textures.updateTexture( binding.texture );
  18409. } else if ( binding.isStorageBuffer ) {
  18410. const attribute = binding.attribute;
  18411. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  18412. this.attributes.update( attribute, attributeType );
  18413. }
  18414. }
  18415. }
  18416. /**
  18417. * Updates the given bind group.
  18418. *
  18419. * @param {BindGroup} bindGroup - The bind group to update.
  18420. * @param {Array<BindGroup>} bindings - The bind groups.
  18421. */
  18422. _update( bindGroup, bindings ) {
  18423. const { backend } = this;
  18424. let needsBindingsUpdate = false;
  18425. let cacheBindings = true;
  18426. let cacheIndex = 0;
  18427. let version = 0;
  18428. // iterate over all bindings and check if buffer updates or a new binding group is required
  18429. for ( const binding of bindGroup.bindings ) {
  18430. if ( binding.isNodeUniformsGroup ) {
  18431. const updated = this.nodes.updateGroup( binding );
  18432. // every uniforms group is a uniform buffer. So if no update is required,
  18433. // we move one with the next binding. Otherwise the next if block will update the group.
  18434. if ( updated === false ) continue;
  18435. }
  18436. if ( binding.isUniformBuffer ) {
  18437. const updated = binding.update();
  18438. if ( updated ) {
  18439. backend.updateBinding( binding );
  18440. }
  18441. } else if ( binding.isSampler ) {
  18442. binding.update();
  18443. } else if ( binding.isSampledTexture ) {
  18444. const texturesTextureData = this.textures.get( binding.texture );
  18445. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18446. const updated = binding.update();
  18447. const texture = binding.texture;
  18448. if ( updated ) {
  18449. this.textures.updateTexture( texture );
  18450. }
  18451. const textureData = backend.get( texture );
  18452. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18453. cacheBindings = false;
  18454. } else {
  18455. cacheIndex = cacheIndex * 10 + texture.id;
  18456. version += texture.version;
  18457. }
  18458. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18459. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18460. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18461. this.textures.updateTexture( texture );
  18462. needsBindingsUpdate = true;
  18463. }
  18464. if ( texture.isStorageTexture === true ) {
  18465. const textureData = this.get( texture );
  18466. if ( binding.store === true ) {
  18467. textureData.needsMipmap = true;
  18468. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18469. this.backend.generateMipmaps( texture );
  18470. textureData.needsMipmap = false;
  18471. }
  18472. }
  18473. }
  18474. }
  18475. if ( needsBindingsUpdate === true ) {
  18476. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18477. }
  18478. }
  18479. }
  18480. /**
  18481. * Default sorting function for opaque render items.
  18482. *
  18483. * @private
  18484. * @function
  18485. * @param {Object} a - The first render item.
  18486. * @param {Object} b - The second render item.
  18487. * @return {number} A numeric value which defines the sort order.
  18488. */
  18489. function painterSortStable( a, b ) {
  18490. if ( a.groupOrder !== b.groupOrder ) {
  18491. return a.groupOrder - b.groupOrder;
  18492. } else if ( a.renderOrder !== b.renderOrder ) {
  18493. return a.renderOrder - b.renderOrder;
  18494. } else if ( a.material.id !== b.material.id ) {
  18495. return a.material.id - b.material.id;
  18496. } else if ( a.z !== b.z ) {
  18497. return a.z - b.z;
  18498. } else {
  18499. return a.id - b.id;
  18500. }
  18501. }
  18502. /**
  18503. * Default sorting function for transparent render items.
  18504. *
  18505. * @private
  18506. * @function
  18507. * @param {Object} a - The first render item.
  18508. * @param {Object} b - The second render item.
  18509. * @return {number} A numeric value which defines the sort order.
  18510. */
  18511. function reversePainterSortStable( a, b ) {
  18512. if ( a.groupOrder !== b.groupOrder ) {
  18513. return a.groupOrder - b.groupOrder;
  18514. } else if ( a.renderOrder !== b.renderOrder ) {
  18515. return a.renderOrder - b.renderOrder;
  18516. } else if ( a.z !== b.z ) {
  18517. return b.z - a.z;
  18518. } else {
  18519. return a.id - b.id;
  18520. }
  18521. }
  18522. /**
  18523. * Returns `true` if the given transparent material requires a double pass.
  18524. *
  18525. * @private
  18526. * @function
  18527. * @param {Material} material - The transparent material.
  18528. * @return {boolean} Whether the given material requires a double pass or not.
  18529. */
  18530. function needsDoublePass( material ) {
  18531. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18532. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18533. }
  18534. /**
  18535. * When the renderer analyzes the scene at the beginning of a render call,
  18536. * it stores 3D object for further processing in render lists. Depending on the
  18537. * properties of a 3D objects (like their transformation or material state), the
  18538. * objects are maintained in ordered lists for the actual rendering.
  18539. *
  18540. * Render lists are unique per scene and camera combination.
  18541. *
  18542. * @private
  18543. * @augments Pipeline
  18544. */
  18545. class RenderList {
  18546. /**
  18547. * Constructs a render list.
  18548. *
  18549. * @param {Lighting} lighting - The lighting management component.
  18550. * @param {Scene} scene - The scene.
  18551. * @param {Camera} camera - The camera the scene is rendered with.
  18552. */
  18553. constructor( lighting, scene, camera ) {
  18554. /**
  18555. * 3D objects are transformed into render items and stored in this array.
  18556. *
  18557. * @type {Array<Object>}
  18558. */
  18559. this.renderItems = [];
  18560. /**
  18561. * The current render items index.
  18562. *
  18563. * @type {number}
  18564. * @default 0
  18565. */
  18566. this.renderItemsIndex = 0;
  18567. /**
  18568. * A list with opaque render items.
  18569. *
  18570. * @type {Array<Object>}
  18571. */
  18572. this.opaque = [];
  18573. /**
  18574. * A list with transparent render items which require
  18575. * double pass rendering (e.g. transmissive objects).
  18576. *
  18577. * @type {Array<Object>}
  18578. */
  18579. this.transparentDoublePass = [];
  18580. /**
  18581. * A list with transparent render items.
  18582. *
  18583. * @type {Array<Object>}
  18584. */
  18585. this.transparent = [];
  18586. /**
  18587. * A list with transparent render bundle data.
  18588. *
  18589. * @type {Array<Object>}
  18590. */
  18591. this.bundles = [];
  18592. /**
  18593. * The render list's lights node. This node is later
  18594. * relevant for the actual analytical light nodes which
  18595. * compute the scene's lighting in the shader.
  18596. *
  18597. * @type {LightsNode}
  18598. */
  18599. this.lightsNode = lighting.getNode( scene, camera );
  18600. /**
  18601. * The scene's lights stored in an array. This array
  18602. * is used to setup the lights node.
  18603. *
  18604. * @type {Array<Light>}
  18605. */
  18606. this.lightsArray = [];
  18607. /**
  18608. * The scene.
  18609. *
  18610. * @type {Scene}
  18611. */
  18612. this.scene = scene;
  18613. /**
  18614. * The camera the scene is rendered with.
  18615. *
  18616. * @type {Camera}
  18617. */
  18618. this.camera = camera;
  18619. /**
  18620. * How many objects perform occlusion query tests.
  18621. *
  18622. * @type {number}
  18623. * @default 0
  18624. */
  18625. this.occlusionQueryCount = 0;
  18626. }
  18627. /**
  18628. * This method is called right at the beginning of a render call
  18629. * before the scene is analyzed. It prepares the internal data
  18630. * structures for the upcoming render lists generation.
  18631. *
  18632. * @return {RenderList} A reference to this render list.
  18633. */
  18634. begin() {
  18635. this.renderItemsIndex = 0;
  18636. this.opaque.length = 0;
  18637. this.transparentDoublePass.length = 0;
  18638. this.transparent.length = 0;
  18639. this.bundles.length = 0;
  18640. this.lightsArray.length = 0;
  18641. this.occlusionQueryCount = 0;
  18642. return this;
  18643. }
  18644. /**
  18645. * Returns a render item for the giving render item state. The state is defined
  18646. * by a series of object-related parameters.
  18647. *
  18648. * The method avoids object creation by holding render items and reusing them in
  18649. * subsequent render calls (just with different property values).
  18650. *
  18651. * @param {Object3D} object - The 3D object.
  18652. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18653. * @param {Material} material - The 3D object's material.
  18654. * @param {number} groupOrder - The current group order.
  18655. * @param {number} z - Th 3D object's depth value (z value in clip space).
  18656. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18657. * @param {ClippingContext} clippingContext - The current clipping context.
  18658. * @return {Object} The render item.
  18659. */
  18660. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18661. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18662. if ( renderItem === undefined ) {
  18663. renderItem = {
  18664. id: object.id,
  18665. object: object,
  18666. geometry: geometry,
  18667. material: material,
  18668. groupOrder: groupOrder,
  18669. renderOrder: object.renderOrder,
  18670. z: z,
  18671. group: group,
  18672. clippingContext: clippingContext
  18673. };
  18674. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18675. } else {
  18676. renderItem.id = object.id;
  18677. renderItem.object = object;
  18678. renderItem.geometry = geometry;
  18679. renderItem.material = material;
  18680. renderItem.groupOrder = groupOrder;
  18681. renderItem.renderOrder = object.renderOrder;
  18682. renderItem.z = z;
  18683. renderItem.group = group;
  18684. renderItem.clippingContext = clippingContext;
  18685. }
  18686. this.renderItemsIndex ++;
  18687. return renderItem;
  18688. }
  18689. /**
  18690. * Pushes the given object as a render item to the internal render lists.
  18691. * The selected lists depend on the object properties.
  18692. *
  18693. * @param {Object3D} object - The 3D object.
  18694. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18695. * @param {Material} material - The 3D object's material.
  18696. * @param {number} groupOrder - The current group order.
  18697. * @param {number} z - Th 3D object's depth value (z value in clip space).
  18698. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18699. * @param {ClippingContext} clippingContext - The current clipping context.
  18700. */
  18701. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18702. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18703. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18704. if ( material.transparent === true || material.transmission > 0 ) {
  18705. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18706. this.transparent.push( renderItem );
  18707. } else {
  18708. this.opaque.push( renderItem );
  18709. }
  18710. }
  18711. /**
  18712. * Inserts the given object as a render item at the start of the internal render lists.
  18713. * The selected lists depend on the object properties.
  18714. *
  18715. * @param {Object3D} object - The 3D object.
  18716. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18717. * @param {Material} material - The 3D object's material.
  18718. * @param {number} groupOrder - The current group order.
  18719. * @param {number} z - Th 3D object's depth value (z value in clip space).
  18720. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18721. * @param {ClippingContext} clippingContext - The current clipping context.
  18722. */
  18723. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18724. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18725. if ( material.transparent === true || material.transmission > 0 ) {
  18726. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18727. this.transparent.unshift( renderItem );
  18728. } else {
  18729. this.opaque.unshift( renderItem );
  18730. }
  18731. }
  18732. /**
  18733. * Pushes render bundle group data into the render list.
  18734. *
  18735. * @param {Object} group - Bundle group data.
  18736. */
  18737. pushBundle( group ) {
  18738. this.bundles.push( group );
  18739. }
  18740. /**
  18741. * Pushes a light into the render list.
  18742. *
  18743. * @param {Light} light - The light.
  18744. */
  18745. pushLight( light ) {
  18746. this.lightsArray.push( light );
  18747. }
  18748. /**
  18749. * Sorts the internal render lists.
  18750. *
  18751. * @param {function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  18752. * @param {function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  18753. */
  18754. sort( customOpaqueSort, customTransparentSort ) {
  18755. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18756. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18757. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18758. }
  18759. /**
  18760. * This method performs finalizing tasks right after the render lists
  18761. * have been generated.
  18762. */
  18763. finish() {
  18764. // update lights
  18765. this.lightsNode.setLights( this.lightsArray );
  18766. // Clear references from inactive renderItems in the list
  18767. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18768. const renderItem = this.renderItems[ i ];
  18769. if ( renderItem.id === null ) break;
  18770. renderItem.id = null;
  18771. renderItem.object = null;
  18772. renderItem.geometry = null;
  18773. renderItem.material = null;
  18774. renderItem.groupOrder = null;
  18775. renderItem.renderOrder = null;
  18776. renderItem.z = null;
  18777. renderItem.group = null;
  18778. renderItem.clippingContext = null;
  18779. }
  18780. }
  18781. }
  18782. const _chainKeys$4 = [];
  18783. /**
  18784. * This renderer module manages the render lists which are unique
  18785. * per scene and camera combination.
  18786. *
  18787. * @private
  18788. */
  18789. class RenderLists {
  18790. /**
  18791. * Constructs a render lists management component.
  18792. *
  18793. * @param {Lighting} lighting - The lighting management component.
  18794. */
  18795. constructor( lighting ) {
  18796. /**
  18797. * The lighting management component.
  18798. *
  18799. * @type {Lighting}
  18800. */
  18801. this.lighting = lighting;
  18802. /**
  18803. * The internal chain map which holds the render lists.
  18804. *
  18805. * @type {ChainMap}
  18806. */
  18807. this.lists = new ChainMap();
  18808. }
  18809. /**
  18810. * Returns a render list for the given scene and camera.
  18811. *
  18812. * @param {Scene} scene - The scene.
  18813. * @param {Camera} camera - The camera.
  18814. * @return {RenderList} The render list.
  18815. */
  18816. get( scene, camera ) {
  18817. const lists = this.lists;
  18818. _chainKeys$4[ 0 ] = scene;
  18819. _chainKeys$4[ 1 ] = camera;
  18820. let list = lists.get( _chainKeys$4 );
  18821. if ( list === undefined ) {
  18822. list = new RenderList( this.lighting, scene, camera );
  18823. lists.set( _chainKeys$4, list );
  18824. }
  18825. _chainKeys$4.length = 0;
  18826. return list;
  18827. }
  18828. /**
  18829. * Frees all internal resources.
  18830. */
  18831. dispose() {
  18832. this.lists = new ChainMap();
  18833. }
  18834. }
  18835. let _id$7 = 0;
  18836. /**
  18837. * Any render or compute command is executed in a specific context that defines
  18838. * the state of the renderer and its backend. Typical examples for such context
  18839. * data are the current clear values or data from the active framebuffer. This
  18840. * module is used to represent these contexts as objects.
  18841. *
  18842. * @private
  18843. */
  18844. class RenderContext {
  18845. /**
  18846. * Constructs a new render context.
  18847. */
  18848. constructor() {
  18849. /**
  18850. * The context's ID.
  18851. *
  18852. * @type {number}
  18853. */
  18854. this.id = _id$7 ++;
  18855. /**
  18856. * Whether the current active framebuffer has a color attachment.
  18857. *
  18858. * @type {boolean}
  18859. * @default true
  18860. */
  18861. this.color = true;
  18862. /**
  18863. * Whether the color attachment should be cleared or not.
  18864. *
  18865. * @type {boolean}
  18866. * @default true
  18867. */
  18868. this.clearColor = true;
  18869. /**
  18870. * The clear color value.
  18871. *
  18872. * @type {Object}
  18873. * @default true
  18874. */
  18875. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18876. /**
  18877. * Whether the current active framebuffer has a depth attachment.
  18878. *
  18879. * @type {boolean}
  18880. * @default true
  18881. */
  18882. this.depth = true;
  18883. /**
  18884. * Whether the depth attachment should be cleared or not.
  18885. *
  18886. * @type {boolean}
  18887. * @default true
  18888. */
  18889. this.clearDepth = true;
  18890. /**
  18891. * The clear depth value.
  18892. *
  18893. * @type {number}
  18894. * @default 1
  18895. */
  18896. this.clearDepthValue = 1;
  18897. /**
  18898. * Whether the current active framebuffer has a stencil attachment.
  18899. *
  18900. * @type {boolean}
  18901. * @default false
  18902. */
  18903. this.stencil = false;
  18904. /**
  18905. * Whether the stencil attachment should be cleared or not.
  18906. *
  18907. * @type {boolean}
  18908. * @default true
  18909. */
  18910. this.clearStencil = true;
  18911. /**
  18912. * The clear stencil value.
  18913. *
  18914. * @type {number}
  18915. * @default 1
  18916. */
  18917. this.clearStencilValue = 1;
  18918. /**
  18919. * By default the viewport encloses the entire framebuffer If a smaller
  18920. * viewport is manually defined, this property is to `true` by the renderer.
  18921. *
  18922. * @type {boolean}
  18923. * @default false
  18924. */
  18925. this.viewport = false;
  18926. /**
  18927. * The viewport value. This value is in physical pixels meaning it incorporates
  18928. * the renderer's pixel ratio. The viewport property of render targets or
  18929. * the renderer is in logical pixels.
  18930. *
  18931. * @type {Vector4}
  18932. */
  18933. this.viewportValue = new Vector4();
  18934. /**
  18935. * When the scissor test is active and scissor rectangle smaller than the
  18936. * framebuffers dimensions, this property is to `true` by the renderer.
  18937. *
  18938. * @type {boolean}
  18939. * @default false
  18940. */
  18941. this.scissor = false;
  18942. /**
  18943. * The scissor rectangle.
  18944. *
  18945. * @type {Vector4}
  18946. */
  18947. this.scissorValue = new Vector4();
  18948. /**
  18949. * The active render target.
  18950. *
  18951. * @type {?RenderTarget}
  18952. * @default null
  18953. */
  18954. this.renderTarget = null;
  18955. /**
  18956. * The textures of the active render target.
  18957. * `null` when no render target is set.
  18958. *
  18959. * @type {?Array<Texture>}
  18960. * @default null
  18961. */
  18962. this.textures = null;
  18963. /**
  18964. * The depth texture of the active render target.
  18965. * `null` when no render target is set.
  18966. *
  18967. * @type {?DepthTexture}
  18968. * @default null
  18969. */
  18970. this.depthTexture = null;
  18971. /**
  18972. * The active cube face.
  18973. *
  18974. * @type {number}
  18975. * @default 0
  18976. */
  18977. this.activeCubeFace = 0;
  18978. /**
  18979. * The active mipmap level.
  18980. *
  18981. * @type {number}
  18982. * @default 0
  18983. */
  18984. this.activeMipmapLevel = 0;
  18985. /**
  18986. * The number of MSAA samples. This value is always `1` when
  18987. * MSAA isn't used.
  18988. *
  18989. * @type {number}
  18990. * @default 1
  18991. */
  18992. this.sampleCount = 1;
  18993. /**
  18994. * The active render target's width in physical pixels.
  18995. *
  18996. * @type {number}
  18997. * @default 0
  18998. */
  18999. this.width = 0;
  19000. /**
  19001. * The active render target's height in physical pixels.
  19002. *
  19003. * @type {number}
  19004. * @default 0
  19005. */
  19006. this.height = 0;
  19007. /**
  19008. * The occlusion query count.
  19009. *
  19010. * @type {number}
  19011. * @default 0
  19012. */
  19013. this.occlusionQueryCount = 0;
  19014. /**
  19015. * The current clipping context.
  19016. *
  19017. * @type {?ClippingContext}
  19018. * @default null
  19019. */
  19020. this.clippingContext = null;
  19021. /**
  19022. * This flag can be used for type testing.
  19023. *
  19024. * @type {boolean}
  19025. * @readonly
  19026. * @default true
  19027. */
  19028. this.isRenderContext = true;
  19029. }
  19030. /**
  19031. * Returns the cache key of this render context.
  19032. *
  19033. * @return {number} The cache key.
  19034. */
  19035. getCacheKey() {
  19036. return getCacheKey( this );
  19037. }
  19038. }
  19039. /**
  19040. * Computes a cache key for the given render context. This key
  19041. * should identify the render target state so it is possible to
  19042. * configure the correct attachments in the respective backend.
  19043. *
  19044. * @param {RenderContext} renderContext - The render context.
  19045. * @return {number} The cache key.
  19046. */
  19047. function getCacheKey( renderContext ) {
  19048. const { textures, activeCubeFace } = renderContext;
  19049. const values = [ activeCubeFace ];
  19050. for ( const texture of textures ) {
  19051. values.push( texture.id );
  19052. }
  19053. return hashArray( values );
  19054. }
  19055. const _chainKeys$3 = [];
  19056. const _defaultScene = /*@__PURE__*/ new Scene();
  19057. const _defaultCamera = /*@__PURE__*/ new Camera();
  19058. /**
  19059. * This module manages the render contexts of the renderer.
  19060. *
  19061. * @private
  19062. */
  19063. class RenderContexts {
  19064. /**
  19065. * Constructs a new render context management component.
  19066. */
  19067. constructor() {
  19068. /**
  19069. * A dictionary that manages render contexts in chain maps
  19070. * for each attachment state.
  19071. *
  19072. * @type {Object<string,ChainMap>}
  19073. */
  19074. this.chainMaps = {};
  19075. }
  19076. /**
  19077. * Returns a render context for the given scene, camera and render target.
  19078. *
  19079. * @param {Scene} scene - The scene.
  19080. * @param {Camera} camera - The camera that is used to render the scene.
  19081. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19082. * @return {RenderContext} The render context.
  19083. */
  19084. get( scene, camera, renderTarget = null ) {
  19085. _chainKeys$3[ 0 ] = scene;
  19086. _chainKeys$3[ 1 ] = camera;
  19087. let attachmentState;
  19088. if ( renderTarget === null ) {
  19089. attachmentState = 'default';
  19090. } else {
  19091. const format = renderTarget.texture.format;
  19092. const count = renderTarget.textures.length;
  19093. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  19094. }
  19095. const chainMap = this._getChainMap( attachmentState );
  19096. let renderState = chainMap.get( _chainKeys$3 );
  19097. if ( renderState === undefined ) {
  19098. renderState = new RenderContext();
  19099. chainMap.set( _chainKeys$3, renderState );
  19100. }
  19101. _chainKeys$3.length = 0;
  19102. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19103. return renderState;
  19104. }
  19105. /**
  19106. * Returns a render context intended for clear operations.
  19107. *
  19108. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19109. * @return {RenderContext} The render context.
  19110. */
  19111. getForClear( renderTarget = null ) {
  19112. return this.get( _defaultScene, _defaultCamera, renderTarget );
  19113. }
  19114. /**
  19115. * Returns a chain map for the given attachment state.
  19116. *
  19117. * @private
  19118. * @param {string} attachmentState - The attachment state.
  19119. * @return {ChainMap} The chain map.
  19120. */
  19121. _getChainMap( attachmentState ) {
  19122. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  19123. }
  19124. /**
  19125. * Frees internal resources.
  19126. */
  19127. dispose() {
  19128. this.chainMaps = {};
  19129. }
  19130. }
  19131. const _size$3 = /*@__PURE__*/ new Vector3();
  19132. /**
  19133. * This module manages the textures of the renderer.
  19134. *
  19135. * @private
  19136. * @augments DataMap
  19137. */
  19138. class Textures extends DataMap {
  19139. /**
  19140. * Constructs a new texture management component.
  19141. *
  19142. * @param {Renderer} renderer - The renderer.
  19143. * @param {Backend} backend - The renderer's backend.
  19144. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19145. */
  19146. constructor( renderer, backend, info ) {
  19147. super();
  19148. /**
  19149. * The renderer.
  19150. *
  19151. * @type {Renderer}
  19152. */
  19153. this.renderer = renderer;
  19154. /**
  19155. * The backend.
  19156. *
  19157. * @type {Backend}
  19158. */
  19159. this.backend = backend;
  19160. /**
  19161. * Renderer component for managing metrics and monitoring data.
  19162. *
  19163. * @type {Info}
  19164. */
  19165. this.info = info;
  19166. }
  19167. /**
  19168. * Updates the given render target. Based on the given render target configuration,
  19169. * it updates the texture states representing the attachments of the framebuffer.
  19170. *
  19171. * @param {RenderTarget} renderTarget - The render target to update.
  19172. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  19173. */
  19174. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  19175. const renderTargetData = this.get( renderTarget );
  19176. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19177. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  19178. const textures = renderTarget.textures;
  19179. const size = this.getSize( textures[ 0 ] );
  19180. const mipWidth = size.width >> activeMipmapLevel;
  19181. const mipHeight = size.height >> activeMipmapLevel;
  19182. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  19183. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  19184. let textureNeedsUpdate = false;
  19185. if ( depthTexture === undefined && useDepthTexture ) {
  19186. depthTexture = new DepthTexture();
  19187. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  19188. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  19189. depthTexture.image.width = mipWidth;
  19190. depthTexture.image.height = mipHeight;
  19191. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  19192. }
  19193. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  19194. textureNeedsUpdate = true;
  19195. if ( depthTexture ) {
  19196. depthTexture.needsUpdate = true;
  19197. depthTexture.image.width = mipWidth;
  19198. depthTexture.image.height = mipHeight;
  19199. }
  19200. }
  19201. renderTargetData.width = size.width;
  19202. renderTargetData.height = size.height;
  19203. renderTargetData.textures = textures;
  19204. renderTargetData.depthTexture = depthTexture || null;
  19205. renderTargetData.depth = renderTarget.depthBuffer;
  19206. renderTargetData.stencil = renderTarget.stencilBuffer;
  19207. renderTargetData.renderTarget = renderTarget;
  19208. if ( renderTargetData.sampleCount !== sampleCount ) {
  19209. textureNeedsUpdate = true;
  19210. if ( depthTexture ) {
  19211. depthTexture.needsUpdate = true;
  19212. }
  19213. renderTargetData.sampleCount = sampleCount;
  19214. }
  19215. //
  19216. const options = { sampleCount };
  19217. // XR render targets require no texture updates
  19218. if ( renderTarget.isXRRenderTarget !== true ) {
  19219. for ( let i = 0; i < textures.length; i ++ ) {
  19220. const texture = textures[ i ];
  19221. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  19222. this.updateTexture( texture, options );
  19223. }
  19224. if ( depthTexture ) {
  19225. this.updateTexture( depthTexture, options );
  19226. }
  19227. }
  19228. // dispose handler
  19229. if ( renderTargetData.initialized !== true ) {
  19230. renderTargetData.initialized = true;
  19231. // dispose
  19232. const onDispose = () => {
  19233. renderTarget.removeEventListener( 'dispose', onDispose );
  19234. for ( let i = 0; i < textures.length; i ++ ) {
  19235. this._destroyTexture( textures[ i ] );
  19236. }
  19237. if ( depthTexture ) {
  19238. this._destroyTexture( depthTexture );
  19239. }
  19240. this.delete( renderTarget );
  19241. };
  19242. renderTarget.addEventListener( 'dispose', onDispose );
  19243. }
  19244. }
  19245. /**
  19246. * Updates the given texture. Depending on the texture state, this method
  19247. * triggers the upload of texture data to the GPU memory. If the texture data are
  19248. * not yet ready for the upload, it uses default texture data for as a placeholder.
  19249. *
  19250. * @param {Texture} texture - The texture to update.
  19251. * @param {Object} [options={}] - The options.
  19252. */
  19253. updateTexture( texture, options = {} ) {
  19254. const textureData = this.get( texture );
  19255. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  19256. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  19257. const backend = this.backend;
  19258. if ( isRenderTarget && textureData.initialized === true ) {
  19259. // it's an update
  19260. backend.destroySampler( texture );
  19261. backend.destroyTexture( texture );
  19262. }
  19263. //
  19264. if ( texture.isFramebufferTexture ) {
  19265. const renderTarget = this.renderer.getRenderTarget();
  19266. if ( renderTarget ) {
  19267. texture.type = renderTarget.texture.type;
  19268. } else {
  19269. texture.type = UnsignedByteType;
  19270. }
  19271. }
  19272. //
  19273. const { width, height, depth } = this.getSize( texture );
  19274. options.width = width;
  19275. options.height = height;
  19276. options.depth = depth;
  19277. options.needsMipmaps = this.needsMipmaps( texture );
  19278. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  19279. //
  19280. if ( isRenderTarget || texture.isStorageTexture === true ) {
  19281. backend.createSampler( texture );
  19282. backend.createTexture( texture, options );
  19283. textureData.generation = texture.version;
  19284. } else {
  19285. const needsCreate = textureData.initialized !== true;
  19286. if ( needsCreate ) backend.createSampler( texture );
  19287. if ( texture.version > 0 ) {
  19288. const image = texture.image;
  19289. if ( image === undefined ) {
  19290. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  19291. } else if ( image.complete === false ) {
  19292. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  19293. } else {
  19294. if ( texture.images ) {
  19295. const images = [];
  19296. for ( const image of texture.images ) {
  19297. images.push( image );
  19298. }
  19299. options.images = images;
  19300. } else {
  19301. options.image = image;
  19302. }
  19303. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  19304. backend.createTexture( texture, options );
  19305. textureData.isDefaultTexture = false;
  19306. textureData.generation = texture.version;
  19307. }
  19308. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  19309. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  19310. }
  19311. } else {
  19312. // async update
  19313. backend.createDefaultTexture( texture );
  19314. textureData.isDefaultTexture = true;
  19315. textureData.generation = texture.version;
  19316. }
  19317. }
  19318. // dispose handler
  19319. if ( textureData.initialized !== true ) {
  19320. textureData.initialized = true;
  19321. textureData.generation = texture.version;
  19322. //
  19323. this.info.memory.textures ++;
  19324. // dispose
  19325. const onDispose = () => {
  19326. texture.removeEventListener( 'dispose', onDispose );
  19327. this._destroyTexture( texture );
  19328. this.info.memory.textures --;
  19329. };
  19330. texture.addEventListener( 'dispose', onDispose );
  19331. }
  19332. //
  19333. textureData.version = texture.version;
  19334. }
  19335. /**
  19336. * Computes the size of the given texture and writes the result
  19337. * into the target vector. This vector is also returned by the
  19338. * method.
  19339. *
  19340. * If no texture data are available for the compute yet, the method
  19341. * returns default size values.
  19342. *
  19343. * @param {Texture} texture - The texture to compute the size for.
  19344. * @param {Vector3} target - The target vector.
  19345. * @return {Vector3} The target vector.
  19346. */
  19347. getSize( texture, target = _size$3 ) {
  19348. let image = texture.images ? texture.images[ 0 ] : texture.image;
  19349. if ( image ) {
  19350. if ( image.image !== undefined ) image = image.image;
  19351. target.width = image.width || 1;
  19352. target.height = image.height || 1;
  19353. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  19354. } else {
  19355. target.width = target.height = target.depth = 1;
  19356. }
  19357. return target;
  19358. }
  19359. /**
  19360. * Computes the number of mipmap levels for the given texture.
  19361. *
  19362. * @param {Texture} texture - The texture.
  19363. * @param {number} width - The texture's width.
  19364. * @param {number} height - The texture's height.
  19365. * @return {number} The number of mipmap levels.
  19366. */
  19367. getMipLevels( texture, width, height ) {
  19368. let mipLevelCount;
  19369. if ( texture.isCompressedTexture ) {
  19370. if ( texture.mipmaps ) {
  19371. mipLevelCount = texture.mipmaps.length;
  19372. } else {
  19373. mipLevelCount = 1;
  19374. }
  19375. } else {
  19376. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  19377. }
  19378. return mipLevelCount;
  19379. }
  19380. /**
  19381. * Returns `true` if the given texture requires mipmaps.
  19382. *
  19383. * @param {Texture} texture - The texture.
  19384. * @return {boolean} Whether mipmaps are required or not.
  19385. */
  19386. needsMipmaps( texture ) {
  19387. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  19388. }
  19389. /**
  19390. * Returns `true` if the given texture is an environment map.
  19391. *
  19392. * @param {Texture} texture - The texture.
  19393. * @return {boolean} Whether the given texture is an environment map or not.
  19394. */
  19395. isEnvironmentTexture( texture ) {
  19396. const mapping = texture.mapping;
  19397. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  19398. }
  19399. /**
  19400. * Frees internal resource when the given texture isn't
  19401. * required anymore.
  19402. *
  19403. * @param {Texture} texture - The texture to destroy.
  19404. */
  19405. _destroyTexture( texture ) {
  19406. this.backend.destroySampler( texture );
  19407. this.backend.destroyTexture( texture );
  19408. this.delete( texture );
  19409. }
  19410. }
  19411. /**
  19412. * A four-component version of {@link Color} which is internally
  19413. * used by the renderer to represents clear color with alpha as
  19414. * one object.
  19415. *
  19416. * @private
  19417. * @augments Color
  19418. */
  19419. class Color4 extends Color {
  19420. /**
  19421. * Constructs a new four-component color.
  19422. * You can also pass a single THREE.Color, hex or
  19423. * string argument to this constructor.
  19424. *
  19425. * @param {number|string} [r=1] - The red value.
  19426. * @param {number} [g=1] - The green value.
  19427. * @param {number} [b=1] - The blue value.
  19428. * @param {number} [a=1] - The alpha value.
  19429. */
  19430. constructor( r, g, b, a = 1 ) {
  19431. super( r, g, b );
  19432. this.a = a;
  19433. }
  19434. /**
  19435. * Overwrites the default to honor alpha.
  19436. * You can also pass a single THREE.Color, hex or
  19437. * string argument to this method.
  19438. *
  19439. * @param {number|string} r - The red value.
  19440. * @param {number} g - The green value.
  19441. * @param {number} b - The blue value.
  19442. * @param {number} [a=1] - The alpha value.
  19443. * @return {Color4} A reference to this object.
  19444. */
  19445. set( r, g, b, a = 1 ) {
  19446. this.a = a;
  19447. return super.set( r, g, b );
  19448. }
  19449. /**
  19450. * Overwrites the default to honor alpha.
  19451. *
  19452. * @param {Color4} color - The color to copy.
  19453. * @return {Color4} A reference to this object.
  19454. */
  19455. copy( color ) {
  19456. if ( color.a !== undefined ) this.a = color.a;
  19457. return super.copy( color );
  19458. }
  19459. /**
  19460. * Overwrites the default to honor alpha.
  19461. *
  19462. * @return {Color4} The cloned color.
  19463. */
  19464. clone() {
  19465. return new this.constructor( this.r, this.g, this.b, this.a );
  19466. }
  19467. }
  19468. /**
  19469. * Special version of {@link PropertyNode} which is used for parameters.
  19470. *
  19471. * @augments PropertyNode
  19472. */
  19473. class ParameterNode extends PropertyNode {
  19474. static get type() {
  19475. return 'ParameterNode';
  19476. }
  19477. /**
  19478. * Constructs a new parameter node.
  19479. *
  19480. * @param {string} nodeType - The type of the node.
  19481. * @param {?string} [name=null] - The name of the parameter in the shader.
  19482. */
  19483. constructor( nodeType, name = null ) {
  19484. super( nodeType, name );
  19485. /**
  19486. * This flag can be used for type testing.
  19487. *
  19488. * @type {boolean}
  19489. * @readonly
  19490. * @default true
  19491. */
  19492. this.isParameterNode = true;
  19493. }
  19494. getHash() {
  19495. return this.uuid;
  19496. }
  19497. generate() {
  19498. return this.name;
  19499. }
  19500. }
  19501. /**
  19502. * TSL function for creating a parameter node.
  19503. *
  19504. * @tsl
  19505. * @function
  19506. * @param {string} type - The type of the node.
  19507. * @param {?string} name - The name of the parameter in the shader.
  19508. * @returns {ParameterNode}
  19509. */
  19510. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19511. /**
  19512. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19513. * They are usually needed in cases like `If`, `Else`.
  19514. *
  19515. * @augments Node
  19516. */
  19517. class StackNode extends Node {
  19518. static get type() {
  19519. return 'StackNode';
  19520. }
  19521. /**
  19522. * Constructs a new stack node.
  19523. *
  19524. * @param {?StackNode} [parent=null] - The parent stack node.
  19525. */
  19526. constructor( parent = null ) {
  19527. super();
  19528. /**
  19529. * List of nodes.
  19530. *
  19531. * @type {Array<Node>}
  19532. */
  19533. this.nodes = [];
  19534. /**
  19535. * The output node.
  19536. *
  19537. * @type {?Node}
  19538. * @default null
  19539. */
  19540. this.outputNode = null;
  19541. /**
  19542. * The parent stack node.
  19543. *
  19544. * @type {?StackNode}
  19545. * @default null
  19546. */
  19547. this.parent = parent;
  19548. /**
  19549. * The current conditional node.
  19550. *
  19551. * @private
  19552. * @type {ConditionalNode}
  19553. * @default null
  19554. */
  19555. this._currentCond = null;
  19556. /**
  19557. * This flag can be used for type testing.
  19558. *
  19559. * @type {boolean}
  19560. * @readonly
  19561. * @default true
  19562. */
  19563. this.isStackNode = true;
  19564. }
  19565. getNodeType( builder ) {
  19566. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19567. }
  19568. getMemberType( builder, name ) {
  19569. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  19570. }
  19571. /**
  19572. * Adds a node to this stack.
  19573. *
  19574. * @param {Node} node - The node to add.
  19575. * @return {StackNode} A reference to this stack node.
  19576. */
  19577. add( node ) {
  19578. this.nodes.push( node );
  19579. return this;
  19580. }
  19581. /**
  19582. * Represent an `if` statement in TSL.
  19583. *
  19584. * @param {Node} boolNode - Represents the condition.
  19585. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19586. * @return {StackNode} A reference to this stack node.
  19587. */
  19588. If( boolNode, method ) {
  19589. const methodNode = new ShaderNode( method );
  19590. this._currentCond = select( boolNode, methodNode );
  19591. return this.add( this._currentCond );
  19592. }
  19593. /**
  19594. * Represent an `elseif` statement in TSL.
  19595. *
  19596. * @param {Node} boolNode - Represents the condition.
  19597. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19598. * @return {StackNode} A reference to this stack node.
  19599. */
  19600. ElseIf( boolNode, method ) {
  19601. const methodNode = new ShaderNode( method );
  19602. const ifNode = select( boolNode, methodNode );
  19603. this._currentCond.elseNode = ifNode;
  19604. this._currentCond = ifNode;
  19605. return this;
  19606. }
  19607. /**
  19608. * Represent an `else` statement in TSL.
  19609. *
  19610. * @param {Function} method - TSL code which is executed in the `else` case.
  19611. * @return {StackNode} A reference to this stack node.
  19612. */
  19613. Else( method ) {
  19614. this._currentCond.elseNode = new ShaderNode( method );
  19615. return this;
  19616. }
  19617. build( builder, ...params ) {
  19618. const previousStack = getCurrentStack();
  19619. setCurrentStack( this );
  19620. for ( const node of this.nodes ) {
  19621. node.build( builder, 'void' );
  19622. }
  19623. setCurrentStack( previousStack );
  19624. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19625. }
  19626. // Deprecated
  19627. /**
  19628. * @function
  19629. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19630. *
  19631. * @param {...any} params
  19632. * @returns {StackNode}
  19633. */
  19634. else( ...params ) { // @deprecated, r168
  19635. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19636. return this.Else( ...params );
  19637. }
  19638. /**
  19639. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19640. *
  19641. * @param {...any} params
  19642. * @returns {StackNode}
  19643. */
  19644. elseif( ...params ) { // @deprecated, r168
  19645. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19646. return this.ElseIf( ...params );
  19647. }
  19648. }
  19649. /**
  19650. * TSL function for creating a stack node.
  19651. *
  19652. * @tsl
  19653. * @function
  19654. * @param {?StackNode} [parent=null] - The parent stack node.
  19655. * @returns {StackNode}
  19656. */
  19657. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19658. /**
  19659. * Generates a layout for struct members.
  19660. * This function takes an object representing struct members and returns an array of member layouts.
  19661. * Each member layout includes the member's name, type, and whether it is atomic.
  19662. *
  19663. * @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.
  19664. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  19665. */
  19666. function getMembersLayout( members ) {
  19667. return Object.entries( members ).map( ( [ name, value ] ) => {
  19668. if ( typeof value === 'string' ) {
  19669. return { name, type: value, atomic: false };
  19670. }
  19671. return { name, type: value.type, atomic: value.atomic || false };
  19672. } );
  19673. }
  19674. /**
  19675. * Represents a struct type node in the node-based system.
  19676. * This class is used to define and manage the layout and types of struct members.
  19677. * It extends the base Node class and provides methods to get the length of the struct,
  19678. * retrieve member types, and generate the struct type for a builder.
  19679. *
  19680. * @augments Node
  19681. */
  19682. class StructTypeNode extends Node {
  19683. static get type() {
  19684. return 'StructTypeNode';
  19685. }
  19686. /**
  19687. * Creates an instance of StructTypeNode.
  19688. *
  19689. * @param {Object} membersLayout - The layout of the members for the struct.
  19690. * @param {string} [name=null] - The optional name of the struct.
  19691. */
  19692. constructor( membersLayout, name = null ) {
  19693. super( 'struct' );
  19694. /**
  19695. * The layout of the members for the struct
  19696. *
  19697. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  19698. */
  19699. this.membersLayout = getMembersLayout( membersLayout );
  19700. /**
  19701. * The name of the struct.
  19702. *
  19703. * @type {string}
  19704. * @default null
  19705. */
  19706. this.name = name;
  19707. /**
  19708. * This flag can be used for type testing.
  19709. *
  19710. * @type {boolean}
  19711. * @readonly
  19712. * @default true
  19713. */
  19714. this.isStructLayoutNode = true;
  19715. }
  19716. /**
  19717. * Returns the length of the struct.
  19718. * The length is calculated by summing the lengths of the struct's members.
  19719. *
  19720. * @returns {number} The length of the struct.
  19721. */
  19722. getLength() {
  19723. let length = 0;
  19724. for ( const member of this.membersLayout ) {
  19725. length += getLengthFromType( member.type );
  19726. }
  19727. return length;
  19728. }
  19729. getMemberType( builder, name ) {
  19730. const member = this.membersLayout.find( m => m.name === name );
  19731. return member ? member.type : 'void';
  19732. }
  19733. getNodeType( builder ) {
  19734. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  19735. return structType.name;
  19736. }
  19737. setup( builder ) {
  19738. builder.addInclude( this );
  19739. }
  19740. generate( builder ) {
  19741. return this.getNodeType( builder );
  19742. }
  19743. }
  19744. /**
  19745. * StructNode allows to create custom structures with multiple members.
  19746. * This can also be used to define structures in attribute and uniform data.
  19747. *
  19748. * ```js
  19749. * // Define a custom struct
  19750. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  19751. *
  19752. * // Create a new instance of the struct
  19753. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  19754. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  19755. *
  19756. * // Access the struct members
  19757. * const min = bb.get( 'min' );
  19758. *
  19759. * // Assign a new value to a member
  19760. * min.assign( vec3() );
  19761. * ```
  19762. * @augments Node
  19763. */
  19764. class StructNode extends Node {
  19765. static get type() {
  19766. return 'StructNode';
  19767. }
  19768. constructor( structLayoutNode, values ) {
  19769. super( 'vec3' );
  19770. this.structLayoutNode = structLayoutNode;
  19771. this.values = values;
  19772. this.isStructNode = true;
  19773. }
  19774. getNodeType( builder ) {
  19775. return this.structLayoutNode.getNodeType( builder );
  19776. }
  19777. getMemberType( builder, name ) {
  19778. return this.structLayoutNode.getMemberType( builder, name );
  19779. }
  19780. generate( builder ) {
  19781. const nodeVar = builder.getVarFromNode( this );
  19782. const structType = nodeVar.type;
  19783. const propertyName = builder.getPropertyName( nodeVar );
  19784. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  19785. return nodeVar.name;
  19786. }
  19787. }
  19788. /**
  19789. * TSL function for creating a struct node.
  19790. *
  19791. * @tsl
  19792. * @function
  19793. * @param {Object} membersLayout - The layout of the struct members.
  19794. * @param {string} [name=null] - The name of the struct.
  19795. * @returns {Function} The struct function.
  19796. */
  19797. const struct = ( membersLayout, name = null ) => {
  19798. const structLayout = new StructTypeNode( membersLayout, name );
  19799. const struct = ( ...params ) => {
  19800. let values = null;
  19801. if ( params.length > 0 ) {
  19802. if ( params[ 0 ].isNode ) {
  19803. values = {};
  19804. const names = Object.keys( membersLayout );
  19805. for ( let i = 0; i < params.length; i ++ ) {
  19806. values[ names[ i ] ] = params[ i ];
  19807. }
  19808. } else {
  19809. values = params[ 0 ];
  19810. }
  19811. }
  19812. return nodeObject( new StructNode( structLayout, values ) );
  19813. };
  19814. struct.layout = structLayout;
  19815. struct.isStruct = true;
  19816. return struct;
  19817. };
  19818. /**
  19819. * This node can be used to define multiple outputs in a shader programs.
  19820. *
  19821. * @augments Node
  19822. */
  19823. class OutputStructNode extends Node {
  19824. static get type() {
  19825. return 'OutputStructNode';
  19826. }
  19827. /**
  19828. * Constructs a new output struct node. The constructor can be invoked with an
  19829. * arbitrary number of nodes representing the members.
  19830. *
  19831. * @param {...Node} members - A parameter list of nodes.
  19832. */
  19833. constructor( ...members ) {
  19834. super();
  19835. /**
  19836. * An array of nodes which defines the output.
  19837. *
  19838. * @type {Array<Node>}
  19839. */
  19840. this.members = members;
  19841. /**
  19842. * This flag can be used for type testing.
  19843. *
  19844. * @type {boolean}
  19845. * @readonly
  19846. * @default true
  19847. */
  19848. this.isOutputStructNode = true;
  19849. }
  19850. getNodeType( builder ) {
  19851. const properties = builder.getNodeProperties( this );
  19852. if ( properties.membersLayout === undefined ) {
  19853. const members = this.members;
  19854. const membersLayout = [];
  19855. for ( let i = 0; i < members.length; i ++ ) {
  19856. const name = 'm' + i;
  19857. const type = members[ i ].getNodeType( builder );
  19858. membersLayout.push( { name, type, index: i } );
  19859. }
  19860. properties.membersLayout = membersLayout;
  19861. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  19862. }
  19863. return properties.structType.name;
  19864. }
  19865. generate( builder ) {
  19866. const propertyName = builder.getOutputStructName();
  19867. const members = this.members;
  19868. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19869. for ( let i = 0; i < members.length; i ++ ) {
  19870. const snippet = members[ i ].build( builder );
  19871. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19872. }
  19873. return propertyName;
  19874. }
  19875. }
  19876. /**
  19877. * TSL function for creating an output struct node.
  19878. *
  19879. * @tsl
  19880. * @function
  19881. * @param {...Node} members - A parameter list of nodes.
  19882. * @returns {OutputStructNode}
  19883. */
  19884. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19885. /**
  19886. * Returns the MRT texture index for the given name.
  19887. *
  19888. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19889. * @param {string} name - The name of the MRT texture which index is requested.
  19890. * @return {number} The texture index.
  19891. */
  19892. function getTextureIndex( textures, name ) {
  19893. for ( let i = 0; i < textures.length; i ++ ) {
  19894. if ( textures[ i ].name === name ) {
  19895. return i;
  19896. }
  19897. }
  19898. return -1;
  19899. }
  19900. /**
  19901. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19902. * post-processing is shown below:
  19903. * ```js
  19904. * const mrtNode = mrt( {
  19905. * output: output,
  19906. * normal: normalView
  19907. * } ) );
  19908. * ```
  19909. * The MRT output is defined as a dictionary.
  19910. *
  19911. * @augments OutputStructNode
  19912. */
  19913. class MRTNode extends OutputStructNode {
  19914. static get type() {
  19915. return 'MRTNode';
  19916. }
  19917. /**
  19918. * Constructs a new output struct node.
  19919. *
  19920. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  19921. */
  19922. constructor( outputNodes ) {
  19923. super();
  19924. /**
  19925. * A dictionary representing the MRT outputs. The key
  19926. * is the name of the output, the value the node which produces
  19927. * the output result.
  19928. *
  19929. * @type {Object<string, Node>}
  19930. */
  19931. this.outputNodes = outputNodes;
  19932. /**
  19933. * This flag can be used for type testing.
  19934. *
  19935. * @type {boolean}
  19936. * @readonly
  19937. * @default true
  19938. */
  19939. this.isMRTNode = true;
  19940. }
  19941. /**
  19942. * Returns `true` if the MRT node has an output with the given name.
  19943. *
  19944. * @param {string} name - The name of the output.
  19945. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19946. */
  19947. has( name ) {
  19948. return this.outputNodes[ name ] !== undefined;
  19949. }
  19950. /**
  19951. * Returns the output node for the given name.
  19952. *
  19953. * @param {string} name - The name of the output.
  19954. * @return {Node} The output node.
  19955. */
  19956. get( name ) {
  19957. return this.outputNodes[ name ];
  19958. }
  19959. /**
  19960. * Merges the outputs of the given MRT node with the outputs of this node.
  19961. *
  19962. * @param {MRTNode} mrtNode - The MRT to merge.
  19963. * @return {MRTNode} A new MRT node with merged outputs..
  19964. */
  19965. merge( mrtNode ) {
  19966. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19967. return mrt( outputs );
  19968. }
  19969. setup( builder ) {
  19970. const outputNodes = this.outputNodes;
  19971. const mrt = builder.renderer.getRenderTarget();
  19972. const members = [];
  19973. const textures = mrt.textures;
  19974. for ( const name in outputNodes ) {
  19975. const index = getTextureIndex( textures, name );
  19976. members[ index ] = vec4( outputNodes[ name ] );
  19977. }
  19978. this.members = members;
  19979. return super.setup( builder );
  19980. }
  19981. }
  19982. /**
  19983. * TSL function for creating a MRT node.
  19984. *
  19985. * @tsl
  19986. * @function
  19987. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  19988. * @returns {MRTNode}
  19989. */
  19990. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19991. /**
  19992. * Generates a hash value in the range `[0, 1]` from the given seed.
  19993. *
  19994. * @tsl
  19995. * @function
  19996. * @param {Node<float>} seed - The seed.
  19997. * @return {Node<float>} The hash value.
  19998. */
  19999. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  20000. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  20001. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  20002. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  20003. const result = word.shiftRight( 22 ).bitXor( word );
  20004. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  20005. } );
  20006. /**
  20007. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20008. * The corners are mapped to `0` and the center to `1`.
  20009. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20010. *
  20011. * @tsl
  20012. * @function
  20013. * @param {Node<float>} x - The value to remap.
  20014. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  20015. * @return {Node<float>} The remapped value.
  20016. */
  20017. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  20018. /**
  20019. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20020. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  20021. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20022. *
  20023. * @tsl
  20024. * @function
  20025. * @param {Node<float>} x - The value to remap.
  20026. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  20027. * @return {Node<float>} The remapped value.
  20028. */
  20029. 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 ) );
  20030. /**
  20031. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20032. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  20033. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20034. *
  20035. * @tsl
  20036. * @function
  20037. * @param {Node<float>} x - The value to remap.
  20038. * @param {Node<float>} a - First control parameter.
  20039. * @param {Node<float>} b - Second control parameter.
  20040. * @return {Node<float>} The remapped value.
  20041. */
  20042. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  20043. /**
  20044. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  20045. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20046. *
  20047. * @tsl
  20048. * @function
  20049. * @param {Node<float>} x - The value to compute the sin for.
  20050. * @param {Node<float>} k - Controls the amount of bounces.
  20051. * @return {Node<float>} The result value.
  20052. */
  20053. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  20054. // https://github.com/cabbibo/glsl-tri-noise-3d
  20055. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  20056. return x.fract().sub( .5 ).abs();
  20057. } ).setLayout( {
  20058. name: 'tri',
  20059. type: 'float',
  20060. inputs: [
  20061. { name: 'x', type: 'float' }
  20062. ]
  20063. } );
  20064. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  20065. 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. ) ) ) ) );
  20066. } ).setLayout( {
  20067. name: 'tri3',
  20068. type: 'vec3',
  20069. inputs: [
  20070. { name: 'p', type: 'vec3' }
  20071. ]
  20072. } );
  20073. /**
  20074. * Generates a noise value from the given position, speed and time parameters.
  20075. *
  20076. * @tsl
  20077. * @function
  20078. * @param {Node<vec3>} position - The position.
  20079. * @param {Node<float>} speed - The speed.
  20080. * @param {Node<float>} time - The time.
  20081. * @return {Node<float>} The generated noise.
  20082. */
  20083. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  20084. const p = vec3( position ).toVar();
  20085. const z = float( 1.4 ).toVar();
  20086. const rz = float( 0.0 ).toVar();
  20087. const bp = vec3( p ).toVar();
  20088. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  20089. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  20090. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  20091. bp.mulAssign( 1.8 );
  20092. z.mulAssign( 1.5 );
  20093. p.mulAssign( 1.2 );
  20094. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  20095. rz.addAssign( t.div( z ) );
  20096. bp.addAssign( 0.14 );
  20097. } );
  20098. return rz;
  20099. } ).setLayout( {
  20100. name: 'triNoise3D',
  20101. type: 'float',
  20102. inputs: [
  20103. { name: 'position', type: 'vec3' },
  20104. { name: 'speed', type: 'float' },
  20105. { name: 'time', type: 'float' }
  20106. ]
  20107. } );
  20108. /**
  20109. * This class allows to define multiple overloaded versions
  20110. * of the same function. Depending on the parameters of the function
  20111. * call, the node picks the best-fit overloaded version.
  20112. *
  20113. * @augments Node
  20114. */
  20115. class FunctionOverloadingNode extends Node {
  20116. static get type() {
  20117. return 'FunctionOverloadingNode';
  20118. }
  20119. /**
  20120. * Constructs a new function overloading node.
  20121. *
  20122. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20123. * @param {...Node} parametersNodes - A list of parameter nodes.
  20124. */
  20125. constructor( functionNodes = [], ...parametersNodes ) {
  20126. super();
  20127. /**
  20128. * Array of `Fn` function definitions.
  20129. *
  20130. * @type {Array<Function>}
  20131. */
  20132. this.functionNodes = functionNodes;
  20133. /**
  20134. * A list of parameter nodes.
  20135. *
  20136. * @type {Array<Node>}
  20137. */
  20138. this.parametersNodes = parametersNodes;
  20139. /**
  20140. * The selected overloaded function call.
  20141. *
  20142. * @private
  20143. * @type {ShaderCallNodeInternal}
  20144. */
  20145. this._candidateFnCall = null;
  20146. /**
  20147. * This node is marked as global.
  20148. *
  20149. * @type {boolean}
  20150. * @default true
  20151. */
  20152. this.global = true;
  20153. }
  20154. /**
  20155. * This method is overwritten since the node type is inferred from
  20156. * the function's return type.
  20157. *
  20158. * @param {NodeBuilder} builder - The current node builder.
  20159. * @return {string} The node type.
  20160. */
  20161. getNodeType() {
  20162. return this.functionNodes[ 0 ].shaderNode.layout.type;
  20163. }
  20164. setup( builder ) {
  20165. const params = this.parametersNodes;
  20166. let candidateFnCall = this._candidateFnCall;
  20167. if ( candidateFnCall === null ) {
  20168. let candidateFn = null;
  20169. let candidateScore = -1;
  20170. for ( const functionNode of this.functionNodes ) {
  20171. const shaderNode = functionNode.shaderNode;
  20172. const layout = shaderNode.layout;
  20173. if ( layout === null ) {
  20174. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  20175. }
  20176. const inputs = layout.inputs;
  20177. if ( params.length === inputs.length ) {
  20178. let score = 0;
  20179. for ( let i = 0; i < params.length; i ++ ) {
  20180. const param = params[ i ];
  20181. const input = inputs[ i ];
  20182. if ( param.getNodeType( builder ) === input.type ) {
  20183. score ++;
  20184. } else {
  20185. score = 0;
  20186. }
  20187. }
  20188. if ( score > candidateScore ) {
  20189. candidateFn = functionNode;
  20190. candidateScore = score;
  20191. }
  20192. }
  20193. }
  20194. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  20195. }
  20196. return candidateFnCall;
  20197. }
  20198. }
  20199. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  20200. /**
  20201. * TSL function for creating a function overloading node.
  20202. *
  20203. * @tsl
  20204. * @function
  20205. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20206. * @returns {FunctionOverloadingNode}
  20207. */
  20208. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  20209. /**
  20210. * Represents the elapsed time in seconds.
  20211. *
  20212. * @tsl
  20213. * @type {UniformNode<float>}
  20214. */
  20215. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  20216. /**
  20217. * Represents the delta time in seconds.
  20218. *
  20219. * @tsl
  20220. * @type {UniformNode<float>}
  20221. */
  20222. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  20223. /**
  20224. * Represents the current frame ID.
  20225. *
  20226. * @tsl
  20227. * @type {UniformNode<uint>}
  20228. */
  20229. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  20230. // Deprecated
  20231. /**
  20232. * @tsl
  20233. * @function
  20234. * @deprecated since r170. Use {@link time} instead.
  20235. *
  20236. * @param {number} [timeScale=1] - The time scale.
  20237. * @returns {UniformNode<float>}
  20238. */
  20239. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  20240. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  20241. return time.mul( timeScale );
  20242. };
  20243. /**
  20244. * @tsl
  20245. * @function
  20246. * @deprecated since r170. Use {@link time} instead.
  20247. *
  20248. * @param {number} [timeScale=1] - The time scale.
  20249. * @returns {UniformNode<float>}
  20250. */
  20251. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  20252. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  20253. return time.mul( timeScale );
  20254. };
  20255. /**
  20256. * @tsl
  20257. * @function
  20258. * @deprecated since r170. Use {@link deltaTime} instead.
  20259. *
  20260. * @param {number} [timeScale=1] - The time scale.
  20261. * @returns {UniformNode<float>}
  20262. */
  20263. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  20264. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  20265. return deltaTime.mul( timeScale );
  20266. };
  20267. /**
  20268. * Generates a sine wave oscillation based on a timer.
  20269. *
  20270. * @tsl
  20271. * @function
  20272. * @param {Node<float>} t - The timer to generate the oscillation with.
  20273. * @return {Node<float>} The oscillation node.
  20274. */
  20275. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  20276. /**
  20277. * Generates a square wave oscillation based on a timer.
  20278. *
  20279. * @tsl
  20280. * @function
  20281. * @param {Node<float>} t - The timer to generate the oscillation with.
  20282. * @return {Node<float>} The oscillation node.
  20283. */
  20284. const oscSquare = ( t = time ) => t.fract().round();
  20285. /**
  20286. * Generates a triangle wave oscillation based on a timer.
  20287. *
  20288. * @tsl
  20289. * @function
  20290. * @param {Node<float>} t - The timer to generate the oscillation with.
  20291. * @return {Node<float>} The oscillation node.
  20292. */
  20293. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  20294. /**
  20295. * Generates a sawtooth wave oscillation based on a timer.
  20296. *
  20297. * @tsl
  20298. * @function
  20299. * @param {Node<float>} t - The timer to generate the oscillation with.
  20300. * @return {Node<float>} The oscillation node.
  20301. */
  20302. const oscSawtooth = ( t = time ) => t.fract();
  20303. /**
  20304. * Rotates the given uv coordinates around a center point
  20305. *
  20306. * @tsl
  20307. * @function
  20308. * @param {Node<vec2>} uv - The uv coordinates.
  20309. * @param {Node<float>} rotation - The rotation defined in radians.
  20310. * @param {Node<vec2>} center - The center of rotation
  20311. * @return {Node<vec2>} The rotated uv coordinates.
  20312. */
  20313. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  20314. return rotate( uv.sub( center ), rotation ).add( center );
  20315. } );
  20316. /**
  20317. * Applies a spherical warping effect to the given uv coordinates.
  20318. *
  20319. * @tsl
  20320. * @function
  20321. * @param {Node<vec2>} uv - The uv coordinates.
  20322. * @param {Node<float>} strength - The strength of the effect.
  20323. * @param {Node<vec2>} center - The center point
  20324. * @return {Node<vec2>} The updated uv coordinates.
  20325. */
  20326. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  20327. const delta = uv.sub( center );
  20328. const delta2 = delta.dot( delta );
  20329. const delta4 = delta2.mul( delta2 );
  20330. const deltaOffset = delta4.mul( strength );
  20331. return uv.add( delta.mul( deltaOffset ) );
  20332. } );
  20333. /**
  20334. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  20335. * oriented always towards the camera.
  20336. *
  20337. * ```js
  20338. * material.vertexNode = billboarding();
  20339. * ```
  20340. *
  20341. * @tsl
  20342. * @function
  20343. * @param {Object} config - The configuration object.
  20344. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  20345. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  20346. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  20347. * @return {Node<vec3>} The updated vertex position in clip space.
  20348. */
  20349. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  20350. let worldMatrix;
  20351. if ( position !== null ) {
  20352. worldMatrix = modelWorldMatrix.toVar();
  20353. worldMatrix[ 3 ][ 0 ] = position.x;
  20354. worldMatrix[ 3 ][ 1 ] = position.y;
  20355. worldMatrix[ 3 ][ 2 ] = position.z;
  20356. } else {
  20357. worldMatrix = modelWorldMatrix;
  20358. }
  20359. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  20360. if ( defined( horizontal ) ) {
  20361. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  20362. modelViewMatrix[ 0 ][ 1 ] = 0;
  20363. modelViewMatrix[ 0 ][ 2 ] = 0;
  20364. }
  20365. if ( defined( vertical ) ) {
  20366. modelViewMatrix[ 1 ][ 0 ] = 0;
  20367. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  20368. modelViewMatrix[ 1 ][ 2 ] = 0;
  20369. }
  20370. modelViewMatrix[ 2 ][ 0 ] = 0;
  20371. modelViewMatrix[ 2 ][ 1 ] = 0;
  20372. modelViewMatrix[ 2 ][ 2 ] = 1;
  20373. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  20374. } );
  20375. /**
  20376. * A special version of a screen uv function that involves a depth comparison
  20377. * when computing the final uvs. The function mitigates visual errors when
  20378. * using viewport texture nodes for refraction purposes. Without this function
  20379. * objects in front of a refractive surface might appear on the refractive surface
  20380. * which is incorrect.
  20381. *
  20382. * @tsl
  20383. * @function
  20384. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  20385. * @return {Node<vec2>} The update uv coordinates.
  20386. */
  20387. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  20388. const depth = linearDepth();
  20389. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  20390. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  20391. return finalUV;
  20392. } );
  20393. /**
  20394. * Can be used to compute texture coordinates for animated sprite sheets.
  20395. *
  20396. * ```js
  20397. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  20398. *
  20399. * material.colorNode = texture( spriteSheet, uvNode );
  20400. * ```
  20401. *
  20402. * @augments Node
  20403. */
  20404. class SpriteSheetUVNode extends Node {
  20405. static get type() {
  20406. return 'SpriteSheetUVNode';
  20407. }
  20408. /**
  20409. * Constructs a new sprite sheet uv node.
  20410. *
  20411. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20412. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  20413. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  20414. */
  20415. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  20416. super( 'vec2' );
  20417. /**
  20418. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20419. *
  20420. * @type {Node<vec2>}
  20421. */
  20422. this.countNode = countNode;
  20423. /**
  20424. * The uv node.
  20425. *
  20426. * @type {Node<vec2>}
  20427. */
  20428. this.uvNode = uvNode;
  20429. /**
  20430. * The node that defines the current frame/sprite.
  20431. *
  20432. * @type {Node<float>}
  20433. */
  20434. this.frameNode = frameNode;
  20435. }
  20436. setup() {
  20437. const { frameNode, uvNode, countNode } = this;
  20438. const { width, height } = countNode;
  20439. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  20440. const column = frameNum.mod( width );
  20441. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  20442. const scale = countNode.reciprocal();
  20443. const uvFrameOffset = vec2( column, row );
  20444. return uvNode.add( uvFrameOffset ).mul( scale );
  20445. }
  20446. }
  20447. /**
  20448. * TSL function for creating a sprite sheet uv node.
  20449. *
  20450. * @tsl
  20451. * @function
  20452. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20453. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  20454. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  20455. * @returns {SpriteSheetUVNode}
  20456. */
  20457. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  20458. /**
  20459. * Can be used for triplanar texture mapping.
  20460. *
  20461. * ```js
  20462. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  20463. * ```
  20464. *
  20465. * @augments Node
  20466. */
  20467. class TriplanarTexturesNode extends Node {
  20468. static get type() {
  20469. return 'TriplanarTexturesNode';
  20470. }
  20471. /**
  20472. * Constructs a new triplanar textures node.
  20473. *
  20474. * @param {Node} textureXNode - First texture node.
  20475. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20476. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20477. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  20478. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  20479. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  20480. */
  20481. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  20482. super( 'vec4' );
  20483. /**
  20484. * First texture node.
  20485. *
  20486. * @type {Node}
  20487. */
  20488. this.textureXNode = textureXNode;
  20489. /**
  20490. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20491. *
  20492. * @type {Node}
  20493. * @default null
  20494. */
  20495. this.textureYNode = textureYNode;
  20496. /**
  20497. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20498. *
  20499. * @type {Node}
  20500. * @default null
  20501. */
  20502. this.textureZNode = textureZNode;
  20503. /**
  20504. * The scale node.
  20505. *
  20506. * @type {Node<float>}
  20507. * @default float(1)
  20508. */
  20509. this.scaleNode = scaleNode;
  20510. /**
  20511. * Vertex positions in local space.
  20512. *
  20513. * @type {Node<vec3>}
  20514. * @default positionLocal
  20515. */
  20516. this.positionNode = positionNode;
  20517. /**
  20518. * Normals in local space.
  20519. *
  20520. * @type {Node<vec3>}
  20521. * @default normalLocal
  20522. */
  20523. this.normalNode = normalNode;
  20524. }
  20525. setup() {
  20526. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  20527. // Ref: https://github.com/keijiro/StandardTriplanar
  20528. // Blending factor of triplanar mapping
  20529. let bf = normalNode.abs().normalize();
  20530. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  20531. // Triplanar mapping
  20532. const tx = positionNode.yz.mul( scaleNode );
  20533. const ty = positionNode.zx.mul( scaleNode );
  20534. const tz = positionNode.xy.mul( scaleNode );
  20535. // Base color
  20536. const textureX = textureXNode.value;
  20537. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  20538. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  20539. const cx = texture( textureX, tx ).mul( bf.x );
  20540. const cy = texture( textureY, ty ).mul( bf.y );
  20541. const cz = texture( textureZ, tz ).mul( bf.z );
  20542. return add( cx, cy, cz );
  20543. }
  20544. }
  20545. /**
  20546. * TSL function for creating a triplanar textures node.
  20547. *
  20548. * @tsl
  20549. * @function
  20550. * @param {Node} textureXNode - First texture node.
  20551. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20552. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20553. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  20554. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  20555. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  20556. * @returns {TriplanarTexturesNode}
  20557. */
  20558. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  20559. /**
  20560. * TSL function for creating a triplanar textures node.
  20561. *
  20562. * @tsl
  20563. * @function
  20564. * @param {Node} textureXNode - First texture node.
  20565. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20566. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20567. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  20568. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  20569. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  20570. * @returns {TriplanarTexturesNode}
  20571. */
  20572. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  20573. const _reflectorPlane = new Plane();
  20574. const _normal = new Vector3();
  20575. const _reflectorWorldPosition = new Vector3();
  20576. const _cameraWorldPosition = new Vector3();
  20577. const _rotationMatrix = new Matrix4();
  20578. const _lookAtPosition = new Vector3( 0, 0, -1 );
  20579. const clipPlane = new Vector4();
  20580. const _view = new Vector3();
  20581. const _target = new Vector3();
  20582. const _q = new Vector4();
  20583. const _size$2 = new Vector2();
  20584. const _defaultRT = new RenderTarget();
  20585. const _defaultUV = screenUV.flipX();
  20586. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  20587. let _inReflector = false;
  20588. /**
  20589. * This node can be used to implement mirror-like flat reflective surfaces.
  20590. *
  20591. * ```js
  20592. * const groundReflector = reflector();
  20593. * material.colorNode = groundReflector;
  20594. *
  20595. * const plane = new Mesh( geometry, material );
  20596. * plane.add( groundReflector.target );
  20597. * ```
  20598. *
  20599. * @augments TextureNode
  20600. */
  20601. class ReflectorNode extends TextureNode {
  20602. static get type() {
  20603. return 'ReflectorNode';
  20604. }
  20605. /**
  20606. * Constructs a new reflector node.
  20607. *
  20608. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20609. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20610. * @param {number} [parameters.resolution=1] - The resolution scale.
  20611. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20612. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20613. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20614. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20615. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20616. */
  20617. constructor( parameters = {} ) {
  20618. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20619. /**
  20620. * A reference to the internal reflector base node which holds the actual implementation.
  20621. *
  20622. * @private
  20623. * @type {?ReflectorBaseNode}
  20624. * @default null
  20625. */
  20626. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20627. /**
  20628. * A reference to the internal depth node.
  20629. *
  20630. * @private
  20631. * @type {?Node}
  20632. * @default null
  20633. */
  20634. this._depthNode = null;
  20635. this.setUpdateMatrix( false );
  20636. }
  20637. /**
  20638. * A reference to the internal reflector node.
  20639. *
  20640. * @type {ReflectorBaseNode}
  20641. */
  20642. get reflector() {
  20643. return this._reflectorBaseNode;
  20644. }
  20645. /**
  20646. * A reference to 3D object the reflector is linked to.
  20647. *
  20648. * @type {Object3D}
  20649. */
  20650. get target() {
  20651. return this._reflectorBaseNode.target;
  20652. }
  20653. /**
  20654. * Returns a node representing the mirror's depth. That can be used
  20655. * to implement more advanced reflection effects like distance attenuation.
  20656. *
  20657. * @return {Node} The depth node.
  20658. */
  20659. getDepthNode() {
  20660. if ( this._depthNode === null ) {
  20661. if ( this._reflectorBaseNode.depth !== true ) {
  20662. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20663. }
  20664. this._depthNode = nodeObject( new ReflectorNode( {
  20665. defaultTexture: _defaultRT.depthTexture,
  20666. reflector: this._reflectorBaseNode
  20667. } ) );
  20668. }
  20669. return this._depthNode;
  20670. }
  20671. setup( builder ) {
  20672. // ignore if used in post-processing
  20673. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20674. return super.setup( builder );
  20675. }
  20676. clone() {
  20677. const texture = new this.constructor( this.reflectorNode );
  20678. texture._reflectorBaseNode = this._reflectorBaseNode;
  20679. return texture;
  20680. }
  20681. }
  20682. /**
  20683. * Holds the actual implementation of the reflector.
  20684. *
  20685. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20686. * in `ReflectorNode`, see #29619.
  20687. *
  20688. * @private
  20689. * @augments Node
  20690. */
  20691. class ReflectorBaseNode extends Node {
  20692. static get type() {
  20693. return 'ReflectorBaseNode';
  20694. }
  20695. /**
  20696. * Constructs a new reflector base node.
  20697. *
  20698. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20699. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20700. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20701. * @param {number} [parameters.resolution=1] - The resolution scale.
  20702. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20703. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20704. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20705. */
  20706. constructor( textureNode, parameters = {} ) {
  20707. super();
  20708. const {
  20709. target = new Object3D(),
  20710. resolution = 1,
  20711. generateMipmaps = false,
  20712. bounces = true,
  20713. depth = false
  20714. } = parameters;
  20715. /**
  20716. * Represents the rendered reflections as a texture node.
  20717. *
  20718. * @type {TextureNode}
  20719. */
  20720. this.textureNode = textureNode;
  20721. /**
  20722. * The 3D object the reflector is linked to.
  20723. *
  20724. * @type {Object3D}
  20725. * @default {new Object3D()}
  20726. */
  20727. this.target = target;
  20728. /**
  20729. * The resolution scale.
  20730. *
  20731. * @type {number}
  20732. * @default {1}
  20733. */
  20734. this.resolution = resolution;
  20735. /**
  20736. * Whether mipmaps should be generated or not.
  20737. *
  20738. * @type {boolean}
  20739. * @default {false}
  20740. */
  20741. this.generateMipmaps = generateMipmaps;
  20742. /**
  20743. * Whether reflectors can render other reflector nodes or not.
  20744. *
  20745. * @type {boolean}
  20746. * @default {true}
  20747. */
  20748. this.bounces = bounces;
  20749. /**
  20750. * Whether depth data should be generated or not.
  20751. *
  20752. * @type {boolean}
  20753. * @default {false}
  20754. */
  20755. this.depth = depth;
  20756. /**
  20757. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20758. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20759. *
  20760. * @type {string}
  20761. * @default 'render'
  20762. */
  20763. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20764. /**
  20765. * Weak map for managing virtual cameras.
  20766. *
  20767. * @type {WeakMap<Camera, Camera>}
  20768. */
  20769. this.virtualCameras = new WeakMap();
  20770. /**
  20771. * Weak map for managing render targets.
  20772. *
  20773. * @type {WeakMap<Camera, RenderTarget>}
  20774. */
  20775. this.renderTargets = new WeakMap();
  20776. }
  20777. /**
  20778. * Updates the resolution of the internal render target.
  20779. *
  20780. * @private
  20781. * @param {RenderTarget} renderTarget - The render target to resize.
  20782. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20783. */
  20784. _updateResolution( renderTarget, renderer ) {
  20785. const resolution = this.resolution;
  20786. renderer.getDrawingBufferSize( _size$2 );
  20787. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20788. }
  20789. setup( builder ) {
  20790. this._updateResolution( _defaultRT, builder.renderer );
  20791. return super.setup( builder );
  20792. }
  20793. /**
  20794. * Returns a virtual camera for the given camera. The virtual camera is used to
  20795. * render the scene from the reflector's view so correct reflections can be produced.
  20796. *
  20797. * @param {Camera} camera - The scene's camera.
  20798. * @return {Camera} The corresponding virtual camera.
  20799. */
  20800. getVirtualCamera( camera ) {
  20801. let virtualCamera = this.virtualCameras.get( camera );
  20802. if ( virtualCamera === undefined ) {
  20803. virtualCamera = camera.clone();
  20804. this.virtualCameras.set( camera, virtualCamera );
  20805. }
  20806. return virtualCamera;
  20807. }
  20808. /**
  20809. * Returns a render target for the given camera. The reflections are rendered
  20810. * into this render target.
  20811. *
  20812. * @param {Camera} camera - The scene's camera.
  20813. * @return {RenderTarget} The render target.
  20814. */
  20815. getRenderTarget( camera ) {
  20816. let renderTarget = this.renderTargets.get( camera );
  20817. if ( renderTarget === undefined ) {
  20818. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20819. if ( this.generateMipmaps === true ) {
  20820. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20821. renderTarget.texture.generateMipmaps = true;
  20822. }
  20823. if ( this.depth === true ) {
  20824. renderTarget.depthTexture = new DepthTexture();
  20825. }
  20826. this.renderTargets.set( camera, renderTarget );
  20827. }
  20828. return renderTarget;
  20829. }
  20830. updateBefore( frame ) {
  20831. if ( this.bounces === false && _inReflector ) return false;
  20832. _inReflector = true;
  20833. const { scene, camera, renderer, material } = frame;
  20834. const { target } = this;
  20835. const virtualCamera = this.getVirtualCamera( camera );
  20836. const renderTarget = this.getRenderTarget( virtualCamera );
  20837. renderer.getDrawingBufferSize( _size$2 );
  20838. this._updateResolution( renderTarget, renderer );
  20839. //
  20840. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20841. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20842. _rotationMatrix.extractRotation( target.matrixWorld );
  20843. _normal.set( 0, 0, 1 );
  20844. _normal.applyMatrix4( _rotationMatrix );
  20845. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20846. // Avoid rendering when reflector is facing away
  20847. if ( _view.dot( _normal ) > 0 ) return;
  20848. _view.reflect( _normal ).negate();
  20849. _view.add( _reflectorWorldPosition );
  20850. _rotationMatrix.extractRotation( camera.matrixWorld );
  20851. _lookAtPosition.set( 0, 0, -1 );
  20852. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20853. _lookAtPosition.add( _cameraWorldPosition );
  20854. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20855. _target.reflect( _normal ).negate();
  20856. _target.add( _reflectorWorldPosition );
  20857. //
  20858. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20859. virtualCamera.position.copy( _view );
  20860. virtualCamera.up.set( 0, 1, 0 );
  20861. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20862. virtualCamera.up.reflect( _normal );
  20863. virtualCamera.lookAt( _target );
  20864. virtualCamera.near = camera.near;
  20865. virtualCamera.far = camera.far;
  20866. virtualCamera.updateMatrixWorld();
  20867. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20868. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20869. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20870. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20871. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20872. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20873. const projectionMatrix = virtualCamera.projectionMatrix;
  20874. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20875. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20876. _q.z = -1;
  20877. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20878. // Calculate the scaled plane vector
  20879. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20880. const clipBias = 0;
  20881. // Replacing the third row of the projection matrix
  20882. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20883. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20884. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20885. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20886. //
  20887. this.textureNode.value = renderTarget.texture;
  20888. if ( this.depth === true ) {
  20889. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20890. }
  20891. material.visible = false;
  20892. const currentRenderTarget = renderer.getRenderTarget();
  20893. const currentMRT = renderer.getMRT();
  20894. const currentAutoClear = renderer.autoClear;
  20895. renderer.setMRT( null );
  20896. renderer.setRenderTarget( renderTarget );
  20897. renderer.autoClear = true;
  20898. renderer.render( scene, virtualCamera );
  20899. renderer.setMRT( currentMRT );
  20900. renderer.setRenderTarget( currentRenderTarget );
  20901. renderer.autoClear = currentAutoClear;
  20902. material.visible = true;
  20903. _inReflector = false;
  20904. }
  20905. }
  20906. /**
  20907. * TSL function for creating a reflector node.
  20908. *
  20909. * @tsl
  20910. * @function
  20911. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20912. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20913. * @param {number} [parameters.resolution=1] - The resolution scale.
  20914. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20915. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20916. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20917. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20918. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20919. * @returns {ReflectorNode}
  20920. */
  20921. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20922. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  20923. /**
  20924. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20925. *
  20926. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20927. *
  20928. * @private
  20929. * @augments BufferGeometry
  20930. */
  20931. class QuadGeometry extends BufferGeometry {
  20932. /**
  20933. * Constructs a new quad geometry.
  20934. *
  20935. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20936. */
  20937. constructor( flipY = false ) {
  20938. super();
  20939. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20940. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  20941. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20942. }
  20943. }
  20944. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20945. /**
  20946. * This module is a helper for passes which need to render a full
  20947. * screen effect which is quite common in context of post processing.
  20948. *
  20949. * The intended usage is to reuse a single quad mesh for rendering
  20950. * subsequent passes by just reassigning the `material` reference.
  20951. *
  20952. * @augments Mesh
  20953. */
  20954. class QuadMesh extends Mesh {
  20955. /**
  20956. * Constructs a new quad mesh.
  20957. *
  20958. * @param {?Material} [material=null] - The material to render the quad mesh with.
  20959. */
  20960. constructor( material = null ) {
  20961. super( _geometry, material );
  20962. /**
  20963. * The camera to render the quad mesh with.
  20964. *
  20965. * @type {OrthographicCamera}
  20966. * @readonly
  20967. */
  20968. this.camera = _camera;
  20969. /**
  20970. * This flag can be used for type testing.
  20971. *
  20972. * @type {boolean}
  20973. * @readonly
  20974. * @default true
  20975. */
  20976. this.isQuadMesh = true;
  20977. }
  20978. /**
  20979. * Async version of `render()`.
  20980. *
  20981. * @async
  20982. * @param {Renderer} renderer - The renderer.
  20983. * @return {Promise} A Promise that resolves when the render has been finished.
  20984. */
  20985. async renderAsync( renderer ) {
  20986. return renderer.renderAsync( this, _camera );
  20987. }
  20988. /**
  20989. * Renders the quad mesh
  20990. *
  20991. * @param {Renderer} renderer - The renderer.
  20992. */
  20993. render( renderer ) {
  20994. renderer.render( this, _camera );
  20995. }
  20996. }
  20997. const _size$1 = /*@__PURE__*/ new Vector2();
  20998. /**
  20999. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  21000. * This module is especially relevant in context of post processing where certain nodes require
  21001. * texture input for their effects. With the helper function `convertToTexture()` which is based
  21002. * on this module, the node system can automatically ensure texture input if required.
  21003. *
  21004. * @augments TextureNode
  21005. */
  21006. class RTTNode extends TextureNode {
  21007. static get type() {
  21008. return 'RTTNode';
  21009. }
  21010. /**
  21011. * Constructs a new RTT node.
  21012. *
  21013. * @param {Node} node - The node to render a texture with.
  21014. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21015. * @param {?number} [height=null] - The height of the internal render target.
  21016. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21017. */
  21018. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  21019. const renderTarget = new RenderTarget( width, height, options );
  21020. super( renderTarget.texture, uv() );
  21021. /**
  21022. * The node to render a texture with.
  21023. *
  21024. * @type {Node}
  21025. */
  21026. this.node = node;
  21027. /**
  21028. * The width of the internal render target.
  21029. * If not width is applied, the render target is automatically resized.
  21030. *
  21031. * @type {?number}
  21032. * @default null
  21033. */
  21034. this.width = width;
  21035. /**
  21036. * The height of the internal render target.
  21037. *
  21038. * @type {?number}
  21039. * @default null
  21040. */
  21041. this.height = height;
  21042. /**
  21043. * The pixel ratio
  21044. *
  21045. * @type {number}
  21046. * @default 1
  21047. */
  21048. this.pixelRatio = 1;
  21049. /**
  21050. * The render target
  21051. *
  21052. * @type {RenderTarget}
  21053. */
  21054. this.renderTarget = renderTarget;
  21055. /**
  21056. * Whether the texture requires an update or not.
  21057. *
  21058. * @type {boolean}
  21059. * @default true
  21060. */
  21061. this.textureNeedsUpdate = true;
  21062. /**
  21063. * Whether the texture should automatically be updated or not.
  21064. *
  21065. * @type {boolean}
  21066. * @default true
  21067. */
  21068. this.autoUpdate = true;
  21069. /**
  21070. * The node which is used with the quad mesh for RTT.
  21071. *
  21072. * @private
  21073. * @type {Node}
  21074. * @default null
  21075. */
  21076. this._rttNode = null;
  21077. /**
  21078. * The internal quad mesh for RTT.
  21079. *
  21080. * @private
  21081. * @type {QuadMesh}
  21082. */
  21083. this._quadMesh = new QuadMesh( new NodeMaterial() );
  21084. /**
  21085. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  21086. * the texture once per render in its {@link RTTNode#updateBefore} method.
  21087. *
  21088. * @type {string}
  21089. * @default 'render'
  21090. */
  21091. this.updateBeforeType = NodeUpdateType.RENDER;
  21092. }
  21093. /**
  21094. * Whether the internal render target should automatically be resized or not.
  21095. *
  21096. * @type {boolean}
  21097. * @readonly
  21098. * @default true
  21099. */
  21100. get autoSize() {
  21101. return this.width === null;
  21102. }
  21103. setup( builder ) {
  21104. this._rttNode = this.node.context( builder.getSharedContext() );
  21105. this._quadMesh.material.name = 'RTT';
  21106. this._quadMesh.material.needsUpdate = true;
  21107. return super.setup( builder );
  21108. }
  21109. /**
  21110. * Sets the size of the internal render target
  21111. *
  21112. * @param {number} width - The width to set.
  21113. * @param {number} height - The width to set.
  21114. */
  21115. setSize( width, height ) {
  21116. this.width = width;
  21117. this.height = height;
  21118. const effectiveWidth = width * this.pixelRatio;
  21119. const effectiveHeight = height * this.pixelRatio;
  21120. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  21121. this.textureNeedsUpdate = true;
  21122. }
  21123. /**
  21124. * Sets the pixel ratio. This will also resize the render target.
  21125. *
  21126. * @param {number} pixelRatio - The pixel ratio to set.
  21127. */
  21128. setPixelRatio( pixelRatio ) {
  21129. this.pixelRatio = pixelRatio;
  21130. this.setSize( this.width, this.height );
  21131. }
  21132. updateBefore( { renderer } ) {
  21133. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  21134. this.textureNeedsUpdate = false;
  21135. //
  21136. if ( this.autoSize === true ) {
  21137. this.pixelRatio = renderer.getPixelRatio();
  21138. const size = renderer.getSize( _size$1 );
  21139. this.setSize( size.width, size.height );
  21140. }
  21141. //
  21142. this._quadMesh.material.fragmentNode = this._rttNode;
  21143. //
  21144. const currentRenderTarget = renderer.getRenderTarget();
  21145. renderer.setRenderTarget( this.renderTarget );
  21146. this._quadMesh.render( renderer );
  21147. renderer.setRenderTarget( currentRenderTarget );
  21148. }
  21149. clone() {
  21150. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  21151. newNode.sampler = this.sampler;
  21152. newNode.referenceNode = this;
  21153. return newNode;
  21154. }
  21155. }
  21156. /**
  21157. * TSL function for creating a RTT node.
  21158. *
  21159. * @tsl
  21160. * @function
  21161. * @param {Node} node - The node to render a texture with.
  21162. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21163. * @param {?number} [height=null] - The height of the internal render target.
  21164. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21165. * @returns {RTTNode}
  21166. */
  21167. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  21168. /**
  21169. * TSL function for converting nodes to textures nodes.
  21170. *
  21171. * @tsl
  21172. * @function
  21173. * @param {Node} node - The node to render a texture with.
  21174. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21175. * @param {?number} [height=null] - The height of the internal render target.
  21176. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21177. * @returns {RTTNode}
  21178. */
  21179. const convertToTexture = ( node, ...params ) => {
  21180. if ( node.isTextureNode ) return node;
  21181. if ( node.isPassNode ) return node.getTextureNode();
  21182. return rtt( node, ...params );
  21183. };
  21184. /**
  21185. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  21186. * depth value and the camera's inverse projection matrix.
  21187. *
  21188. * @tsl
  21189. * @function
  21190. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  21191. * @param {Node<float>} depth - The fragment's depth value.
  21192. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21193. * @return {Node<vec3>} The fragments position in view space.
  21194. */
  21195. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  21196. let clipSpacePosition;
  21197. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  21198. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  21199. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  21200. } else {
  21201. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  21202. }
  21203. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  21204. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  21205. } );
  21206. /**
  21207. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  21208. * and the camera's projection matrix
  21209. *
  21210. * @tsl
  21211. * @function
  21212. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  21213. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  21214. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  21215. */
  21216. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  21217. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  21218. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  21219. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  21220. } );
  21221. /**
  21222. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  21223. * target is available or if flat surface normals are required.
  21224. *
  21225. * @tsl
  21226. * @function
  21227. * @param {Node<vec2>} uv - The texture coordinate.
  21228. * @param {DepthTexture} depthTexture - The depth texture.
  21229. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21230. * @return {Node<vec3>} The computed normal vector.
  21231. */
  21232. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  21233. const size = textureSize( textureLoad( depthTexture ) );
  21234. const p = ivec2( uv.mul( size ) ).toVar();
  21235. const c0 = textureLoad( depthTexture, p ).toVar();
  21236. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  21237. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  21238. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  21239. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  21240. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  21241. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  21242. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  21243. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  21244. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  21245. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  21246. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  21247. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  21248. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  21249. 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 ) ) );
  21250. 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 ) ) );
  21251. return normalize( cross( dpdx, dpdy ) );
  21252. } );
  21253. /**
  21254. * This special type of instanced buffer attribute is intended for compute shaders.
  21255. * In earlier three.js versions it was only possible to update attribute data
  21256. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21257. * new material system and renderer it is now possible to use compute shaders
  21258. * to compute the data for an attribute more efficiently on the GPU.
  21259. *
  21260. * The idea is to create an instance of this class and provide it as an input
  21261. * to {@link StorageBufferNode}.
  21262. *
  21263. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21264. *
  21265. * @augments InstancedBufferAttribute
  21266. */
  21267. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  21268. /**
  21269. * Constructs a new storage instanced buffer attribute.
  21270. *
  21271. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21272. * The subsequent parameters are then obsolete.
  21273. * @param {number} itemSize - The item size.
  21274. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21275. */
  21276. constructor( count, itemSize, typeClass = Float32Array ) {
  21277. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21278. super( array, itemSize );
  21279. /**
  21280. * This flag can be used for type testing.
  21281. *
  21282. * @type {boolean}
  21283. * @readonly
  21284. * @default true
  21285. */
  21286. this.isStorageInstancedBufferAttribute = true;
  21287. }
  21288. }
  21289. /**
  21290. * This special type of buffer attribute is intended for compute shaders.
  21291. * In earlier three.js versions it was only possible to update attribute data
  21292. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21293. * new material system and renderer it is now possible to use compute shaders
  21294. * to compute the data for an attribute more efficiently on the GPU.
  21295. *
  21296. * The idea is to create an instance of this class and provide it as an input
  21297. * to {@link StorageBufferNode}.
  21298. *
  21299. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21300. *
  21301. * @augments BufferAttribute
  21302. */
  21303. class StorageBufferAttribute extends BufferAttribute {
  21304. /**
  21305. * Constructs a new storage buffer attribute.
  21306. *
  21307. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21308. * The subsequent parameters are then obsolete.
  21309. * @param {number} itemSize - The item size.
  21310. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21311. */
  21312. constructor( count, itemSize, typeClass = Float32Array ) {
  21313. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21314. super( array, itemSize );
  21315. /**
  21316. * This flag can be used for type testing.
  21317. *
  21318. * @type {boolean}
  21319. * @readonly
  21320. * @default true
  21321. */
  21322. this.isStorageBufferAttribute = true;
  21323. }
  21324. }
  21325. /**
  21326. * This class enables element access on instances of {@link StorageBufferNode}.
  21327. * In most cases, it is indirectly used when accessing elements with the
  21328. * {@link StorageBufferNode#element} method.
  21329. *
  21330. * ```js
  21331. * const position = positionStorage.element( instanceIndex );
  21332. * ```
  21333. *
  21334. * @augments ArrayElementNode
  21335. */
  21336. class StorageArrayElementNode extends ArrayElementNode {
  21337. static get type() {
  21338. return 'StorageArrayElementNode';
  21339. }
  21340. /**
  21341. * Constructs storage buffer element node.
  21342. *
  21343. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  21344. * @param {Node} indexNode - The index node that defines the element access.
  21345. */
  21346. constructor( storageBufferNode, indexNode ) {
  21347. super( storageBufferNode, indexNode );
  21348. /**
  21349. * This flag can be used for type testing.
  21350. *
  21351. * @type {boolean}
  21352. * @readonly
  21353. * @default true
  21354. */
  21355. this.isStorageArrayElementNode = true;
  21356. }
  21357. /**
  21358. * The storage buffer node.
  21359. *
  21360. * @param {Node} value
  21361. * @type {StorageBufferNode}
  21362. */
  21363. set storageBufferNode( value ) {
  21364. this.node = value;
  21365. }
  21366. get storageBufferNode() {
  21367. return this.node;
  21368. }
  21369. getMemberType( builder, name ) {
  21370. const structTypeNode = this.storageBufferNode.structTypeNode;
  21371. if ( structTypeNode ) {
  21372. return structTypeNode.getMemberType( builder, name );
  21373. }
  21374. return 'void';
  21375. }
  21376. setup( builder ) {
  21377. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  21378. if ( this.node.isPBO === true ) {
  21379. builder.setupPBO( this.node );
  21380. }
  21381. }
  21382. return super.setup( builder );
  21383. }
  21384. generate( builder, output ) {
  21385. let snippet;
  21386. const isAssignContext = builder.context.assign;
  21387. //
  21388. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  21389. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  21390. snippet = builder.generatePBO( this );
  21391. } else {
  21392. snippet = this.node.build( builder );
  21393. }
  21394. } else {
  21395. snippet = super.generate( builder );
  21396. }
  21397. if ( isAssignContext !== true ) {
  21398. const type = this.getNodeType( builder );
  21399. snippet = builder.format( snippet, type, output );
  21400. }
  21401. return snippet;
  21402. }
  21403. }
  21404. /**
  21405. * TSL function for creating a storage element node.
  21406. *
  21407. * @tsl
  21408. * @function
  21409. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  21410. * @param {Node} indexNode - The index node that defines the element access.
  21411. * @returns {StorageArrayElementNode}
  21412. */
  21413. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  21414. /**
  21415. * This node is used in context of compute shaders and allows to define a
  21416. * storage buffer for data. A typical workflow is to create instances of
  21417. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  21418. * setup up a compute shader that writes into the buffers and then convert
  21419. * the storage buffers to attribute nodes for rendering.
  21420. *
  21421. * ```js
  21422. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  21423. *
  21424. * const computeInit = Fn( () => { // the compute shader
  21425. *
  21426. * const position = positionBuffer.element( instanceIndex );
  21427. *
  21428. * // compute position data
  21429. *
  21430. * position.x = 1;
  21431. * position.y = 1;
  21432. * position.z = 1;
  21433. *
  21434. * } )().compute( particleCount );
  21435. *
  21436. * const particleMaterial = new THREE.SpriteNodeMaterial();
  21437. * particleMaterial.positionNode = positionBuffer.toAttribute();
  21438. *
  21439. * renderer.computeAsync( computeInit );
  21440. *
  21441. * ```
  21442. *
  21443. * @augments BufferNode
  21444. */
  21445. class StorageBufferNode extends BufferNode {
  21446. static get type() {
  21447. return 'StorageBufferNode';
  21448. }
  21449. /**
  21450. * Constructs a new storage buffer node.
  21451. *
  21452. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21453. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  21454. * @param {number} [bufferCount=0] - The buffer count.
  21455. */
  21456. constructor( value, bufferType = null, bufferCount = 0 ) {
  21457. let nodeType, structTypeNode = null;
  21458. if ( bufferType && bufferType.isStruct ) {
  21459. nodeType = 'struct';
  21460. structTypeNode = bufferType.layout;
  21461. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  21462. nodeType = getTypeFromLength( value.itemSize );
  21463. bufferCount = value.count;
  21464. } else {
  21465. nodeType = bufferType;
  21466. }
  21467. super( value, nodeType, bufferCount );
  21468. /**
  21469. * This flag can be used for type testing.
  21470. *
  21471. * @type {boolean}
  21472. * @readonly
  21473. * @default true
  21474. */
  21475. this.isStorageBufferNode = true;
  21476. /**
  21477. * The buffer struct type.
  21478. *
  21479. * @type {?structTypeNode}
  21480. * @default null
  21481. */
  21482. this.structTypeNode = structTypeNode;
  21483. /**
  21484. * The access type of the texture node.
  21485. *
  21486. * @type {string}
  21487. * @default 'readWrite'
  21488. */
  21489. this.access = NodeAccess.READ_WRITE;
  21490. /**
  21491. * Whether the node is atomic or not.
  21492. *
  21493. * @type {boolean}
  21494. * @default false
  21495. */
  21496. this.isAtomic = false;
  21497. /**
  21498. * Whether the node represents a PBO or not.
  21499. * Only relevant for WebGL.
  21500. *
  21501. * @type {boolean}
  21502. * @default false
  21503. */
  21504. this.isPBO = false;
  21505. /**
  21506. * A reference to the internal buffer attribute node.
  21507. *
  21508. * @type {?BufferAttributeNode}
  21509. * @default null
  21510. */
  21511. this._attribute = null;
  21512. /**
  21513. * A reference to the internal varying node.
  21514. *
  21515. * @type {?VaryingNode}
  21516. * @default null
  21517. */
  21518. this._varying = null;
  21519. /**
  21520. * `StorageBufferNode` sets this property to `true` by default.
  21521. *
  21522. * @type {boolean}
  21523. * @default true
  21524. */
  21525. this.global = true;
  21526. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  21527. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  21528. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  21529. else value.isStorageBufferAttribute = true;
  21530. }
  21531. }
  21532. /**
  21533. * This method is overwritten since the buffer data might be shared
  21534. * and thus the hash should be shared as well.
  21535. *
  21536. * @param {NodeBuilder} builder - The current node builder.
  21537. * @return {string} The hash.
  21538. */
  21539. getHash( builder ) {
  21540. if ( this.bufferCount === 0 ) {
  21541. let bufferData = builder.globalCache.getData( this.value );
  21542. if ( bufferData === undefined ) {
  21543. bufferData = {
  21544. node: this
  21545. };
  21546. builder.globalCache.setData( this.value, bufferData );
  21547. }
  21548. return bufferData.node.uuid;
  21549. }
  21550. return this.uuid;
  21551. }
  21552. /**
  21553. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  21554. *
  21555. * @param {NodeBuilder} builder - The current node builder.
  21556. * @return {string} The input type.
  21557. */
  21558. getInputType( /*builder*/ ) {
  21559. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  21560. }
  21561. /**
  21562. * Enables element access with the given index node.
  21563. *
  21564. * @param {IndexNode} indexNode - The index node.
  21565. * @return {StorageArrayElementNode} A node representing the element access.
  21566. */
  21567. element( indexNode ) {
  21568. return storageElement( this, indexNode );
  21569. }
  21570. /**
  21571. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  21572. *
  21573. * @param {boolean} value - The value so set.
  21574. * @return {StorageBufferNode} A reference to this node.
  21575. */
  21576. setPBO( value ) {
  21577. this.isPBO = value;
  21578. return this;
  21579. }
  21580. /**
  21581. * Returns the `isPBO` value.
  21582. *
  21583. * @return {boolean} Whether the node represents a PBO or not.
  21584. */
  21585. getPBO() {
  21586. return this.isPBO;
  21587. }
  21588. /**
  21589. * Defines the node access.
  21590. *
  21591. * @param {string} value - The node access.
  21592. * @return {StorageBufferNode} A reference to this node.
  21593. */
  21594. setAccess( value ) {
  21595. this.access = value;
  21596. return this;
  21597. }
  21598. /**
  21599. * Convenience method for configuring a read-only node access.
  21600. *
  21601. * @return {StorageBufferNode} A reference to this node.
  21602. */
  21603. toReadOnly() {
  21604. return this.setAccess( NodeAccess.READ_ONLY );
  21605. }
  21606. /**
  21607. * Defines whether the node is atomic or not.
  21608. *
  21609. * @param {boolean} value - The atomic flag.
  21610. * @return {StorageBufferNode} A reference to this node.
  21611. */
  21612. setAtomic( value ) {
  21613. this.isAtomic = value;
  21614. return this;
  21615. }
  21616. /**
  21617. * Convenience method for making this node atomic.
  21618. *
  21619. * @return {StorageBufferNode} A reference to this node.
  21620. */
  21621. toAtomic() {
  21622. return this.setAtomic( true );
  21623. }
  21624. /**
  21625. * Returns attribute data for this storage buffer node.
  21626. *
  21627. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  21628. */
  21629. getAttributeData() {
  21630. if ( this._attribute === null ) {
  21631. this._attribute = bufferAttribute( this.value );
  21632. this._varying = varying( this._attribute );
  21633. }
  21634. return {
  21635. attribute: this._attribute,
  21636. varying: this._varying
  21637. };
  21638. }
  21639. /**
  21640. * This method is overwritten since the node type from the availability of storage buffers
  21641. * and the attribute data.
  21642. *
  21643. * @param {NodeBuilder} builder - The current node builder.
  21644. * @return {string} The node type.
  21645. */
  21646. getNodeType( builder ) {
  21647. if ( this.structTypeNode !== null ) {
  21648. return this.structTypeNode.getNodeType( builder );
  21649. }
  21650. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21651. return super.getNodeType( builder );
  21652. }
  21653. const { attribute } = this.getAttributeData();
  21654. return attribute.getNodeType( builder );
  21655. }
  21656. /**
  21657. * Generates the code snippet of the storage buffer node.
  21658. *
  21659. * @param {NodeBuilder} builder - The current node builder.
  21660. * @return {string} The generated code snippet.
  21661. */
  21662. generate( builder ) {
  21663. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  21664. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21665. return super.generate( builder );
  21666. }
  21667. const { attribute, varying } = this.getAttributeData();
  21668. const output = varying.build( builder );
  21669. builder.registerTransform( output, attribute );
  21670. return output;
  21671. }
  21672. }
  21673. /**
  21674. * TSL function for creating a storage buffer node.
  21675. *
  21676. * @tsl
  21677. * @function
  21678. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21679. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  21680. * @param {number} [count=0] - The buffer count.
  21681. * @returns {StorageBufferNode}
  21682. */
  21683. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21684. /**
  21685. * @tsl
  21686. * @function
  21687. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21688. *
  21689. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21690. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  21691. * @param {number} count - The buffer count.
  21692. * @returns {StorageBufferNode}
  21693. */
  21694. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21695. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21696. return storage( value, type, count ).setPBO( true );
  21697. };
  21698. /**
  21699. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21700. *
  21701. * @tsl
  21702. * @function
  21703. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21704. * @param {string|Struct} [type='float'] - The data type.
  21705. * @returns {StorageBufferNode}
  21706. */
  21707. const attributeArray = ( count, type = 'float' ) => {
  21708. let itemSize, typedArray;
  21709. if ( type.isStruct === true ) {
  21710. itemSize = type.layout.getLength();
  21711. typedArray = getTypedArrayFromType( 'float' );
  21712. } else {
  21713. itemSize = getLengthFromType( type );
  21714. typedArray = getTypedArrayFromType( type );
  21715. }
  21716. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21717. const node = storage( buffer, type, count );
  21718. return node;
  21719. };
  21720. /**
  21721. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21722. *
  21723. * @tsl
  21724. * @function
  21725. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21726. * @param {string|Struct} [type='float'] - The data type.
  21727. * @returns {StorageBufferNode}
  21728. */
  21729. const instancedArray = ( count, type = 'float' ) => {
  21730. let itemSize, typedArray;
  21731. if ( type.isStruct === true ) {
  21732. itemSize = type.layout.getLength();
  21733. typedArray = getTypedArrayFromType( 'float' );
  21734. } else {
  21735. itemSize = getLengthFromType( type );
  21736. typedArray = getTypedArrayFromType( type );
  21737. }
  21738. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21739. const node = storage( buffer, type, count );
  21740. return node;
  21741. };
  21742. /**
  21743. * An attribute node for representing vertex colors.
  21744. *
  21745. * @augments AttributeNode
  21746. */
  21747. class VertexColorNode extends AttributeNode {
  21748. static get type() {
  21749. return 'VertexColorNode';
  21750. }
  21751. /**
  21752. * Constructs a new vertex color node.
  21753. *
  21754. * @param {number} [index=0] - The attribute index.
  21755. */
  21756. constructor( index = 0 ) {
  21757. super( null, 'vec4' );
  21758. /**
  21759. * This flag can be used for type testing.
  21760. *
  21761. * @type {boolean}
  21762. * @readonly
  21763. * @default true
  21764. */
  21765. this.isVertexColorNode = true;
  21766. /**
  21767. * The attribute index to enable more than one sets of vertex colors.
  21768. *
  21769. * @type {number}
  21770. * @default 0
  21771. */
  21772. this.index = index;
  21773. }
  21774. /**
  21775. * Overwrites the default implementation by honoring the attribute index.
  21776. *
  21777. * @param {NodeBuilder} builder - The current node builder.
  21778. * @return {string} The attribute name.
  21779. */
  21780. getAttributeName( /*builder*/ ) {
  21781. const index = this.index;
  21782. return 'color' + ( index > 0 ? index : '' );
  21783. }
  21784. generate( builder ) {
  21785. const attributeName = this.getAttributeName( builder );
  21786. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21787. let result;
  21788. if ( geometryAttribute === true ) {
  21789. result = super.generate( builder );
  21790. } else {
  21791. // Vertex color fallback should be white
  21792. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21793. }
  21794. return result;
  21795. }
  21796. serialize( data ) {
  21797. super.serialize( data );
  21798. data.index = this.index;
  21799. }
  21800. deserialize( data ) {
  21801. super.deserialize( data );
  21802. this.index = data.index;
  21803. }
  21804. }
  21805. /**
  21806. * TSL function for creating a reference node.
  21807. *
  21808. * @tsl
  21809. * @function
  21810. * @param {number} index - The attribute index.
  21811. * @returns {VertexColorNode}
  21812. */
  21813. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21814. /**
  21815. * A node for representing the uv coordinates of points.
  21816. *
  21817. * Can only be used with a WebGL backend. In WebGPU, point
  21818. * primitives always have the size of one pixel and can thus
  21819. * can't be used as sprite-like objects that display textures.
  21820. *
  21821. * @augments Node
  21822. */
  21823. class PointUVNode extends Node {
  21824. static get type() {
  21825. return 'PointUVNode';
  21826. }
  21827. /**
  21828. * Constructs a new point uv node.
  21829. */
  21830. constructor() {
  21831. super( 'vec2' );
  21832. /**
  21833. * This flag can be used for type testing.
  21834. *
  21835. * @type {boolean}
  21836. * @readonly
  21837. * @default true
  21838. */
  21839. this.isPointUVNode = true;
  21840. }
  21841. generate( /*builder*/ ) {
  21842. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21843. }
  21844. }
  21845. /**
  21846. * TSL object that represents the uv coordinates of points.
  21847. *
  21848. * @tsl
  21849. * @type {PointUVNode}
  21850. */
  21851. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21852. const _e1 = /*@__PURE__*/ new Euler();
  21853. const _m1 = /*@__PURE__*/ new Matrix4();
  21854. /**
  21855. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21856. * are available for easier use:
  21857. *
  21858. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21859. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21860. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21861. *
  21862. * @augments Node
  21863. */
  21864. class SceneNode extends Node {
  21865. static get type() {
  21866. return 'SceneNode';
  21867. }
  21868. /**
  21869. * Constructs a new scene node.
  21870. *
  21871. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21872. * @param {?Scene} [scene=null] - A reference to the scene.
  21873. */
  21874. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21875. super();
  21876. /**
  21877. * The scope defines the type of scene property that is accessed.
  21878. *
  21879. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21880. */
  21881. this.scope = scope;
  21882. /**
  21883. * A reference to the scene that is going to be accessed.
  21884. *
  21885. * @type {?Scene}
  21886. * @default null
  21887. */
  21888. this.scene = scene;
  21889. }
  21890. /**
  21891. * Depending on the scope, the method returns a different type of node that represents
  21892. * the respective scene property.
  21893. *
  21894. * @param {NodeBuilder} builder - The current node builder.
  21895. * @return {Node} The output node.
  21896. */
  21897. setup( builder ) {
  21898. const scope = this.scope;
  21899. const scene = this.scene !== null ? this.scene : builder.scene;
  21900. let output;
  21901. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21902. output = reference( 'backgroundBlurriness', 'float', scene );
  21903. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21904. output = reference( 'backgroundIntensity', 'float', scene );
  21905. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21906. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21907. const background = scene.background;
  21908. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21909. _e1.copy( scene.backgroundRotation );
  21910. // accommodate left-handed frame
  21911. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  21912. _m1.makeRotationFromEuler( _e1 );
  21913. } else {
  21914. _m1.identity();
  21915. }
  21916. return _m1;
  21917. } );
  21918. } else {
  21919. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21920. }
  21921. return output;
  21922. }
  21923. }
  21924. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21925. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21926. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21927. /**
  21928. * TSL object that represents the scene's background blurriness.
  21929. *
  21930. * @tsl
  21931. * @type {SceneNode}
  21932. */
  21933. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21934. /**
  21935. * TSL object that represents the scene's background intensity.
  21936. *
  21937. * @tsl
  21938. * @type {SceneNode}
  21939. */
  21940. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21941. /**
  21942. * TSL object that represents the scene's background rotation.
  21943. *
  21944. * @tsl
  21945. * @type {SceneNode}
  21946. */
  21947. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21948. /**
  21949. * This special version of a texture node can be used to
  21950. * write data into a storage texture with a compute shader.
  21951. *
  21952. * ```js
  21953. * const storageTexture = new THREE.StorageTexture( width, height );
  21954. *
  21955. * const computeTexture = Fn( ( { storageTexture } ) => {
  21956. *
  21957. * const posX = instanceIndex.modInt( width );
  21958. * const posY = instanceIndex.div( width );
  21959. * const indexUV = uvec2( posX, posY );
  21960. *
  21961. * // generate RGB values
  21962. *
  21963. * const r = 1;
  21964. * const g = 1;
  21965. * const b = 1;
  21966. *
  21967. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21968. *
  21969. * } );
  21970. *
  21971. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21972. * renderer.computeAsync( computeNode );
  21973. * ```
  21974. *
  21975. * This node can only be used with a WebGPU backend.
  21976. *
  21977. * @augments TextureNode
  21978. */
  21979. class StorageTextureNode extends TextureNode {
  21980. static get type() {
  21981. return 'StorageTextureNode';
  21982. }
  21983. /**
  21984. * Constructs a new storage texture node.
  21985. *
  21986. * @param {StorageTexture} value - The storage texture.
  21987. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21988. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  21989. */
  21990. constructor( value, uvNode, storeNode = null ) {
  21991. super( value, uvNode );
  21992. /**
  21993. * The value node that should be stored in the texture.
  21994. *
  21995. * @type {?Node}
  21996. * @default null
  21997. */
  21998. this.storeNode = storeNode;
  21999. /**
  22000. * This flag can be used for type testing.
  22001. *
  22002. * @type {boolean}
  22003. * @readonly
  22004. * @default true
  22005. */
  22006. this.isStorageTextureNode = true;
  22007. /**
  22008. * The access type of the texture node.
  22009. *
  22010. * @type {string}
  22011. * @default 'writeOnly'
  22012. */
  22013. this.access = NodeAccess.WRITE_ONLY;
  22014. }
  22015. /**
  22016. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  22017. *
  22018. * @param {NodeBuilder} builder - The current node builder.
  22019. * @return {string} The input type.
  22020. */
  22021. getInputType( /*builder*/ ) {
  22022. return 'storageTexture';
  22023. }
  22024. setup( builder ) {
  22025. super.setup( builder );
  22026. const properties = builder.getNodeProperties( this );
  22027. properties.storeNode = this.storeNode;
  22028. }
  22029. /**
  22030. * Defines the node access.
  22031. *
  22032. * @param {string} value - The node access.
  22033. * @return {StorageTextureNode} A reference to this node.
  22034. */
  22035. setAccess( value ) {
  22036. this.access = value;
  22037. return this;
  22038. }
  22039. /**
  22040. * Generates the code snippet of the stroge node. If no `storeNode`
  22041. * is defined, the texture node is generated as normal texture.
  22042. *
  22043. * @param {NodeBuilder} builder - The current node builder.
  22044. * @param {string} output - The current output.
  22045. * @return {string} The generated code snippet.
  22046. */
  22047. generate( builder, output ) {
  22048. let snippet;
  22049. if ( this.storeNode !== null ) {
  22050. snippet = this.generateStore( builder );
  22051. } else {
  22052. snippet = super.generate( builder, output );
  22053. }
  22054. return snippet;
  22055. }
  22056. /**
  22057. * Convenience method for configuring a read/write node access.
  22058. *
  22059. * @return {StorageTextureNode} A reference to this node.
  22060. */
  22061. toReadWrite() {
  22062. return this.setAccess( NodeAccess.READ_WRITE );
  22063. }
  22064. /**
  22065. * Convenience method for configuring a read-only node access.
  22066. *
  22067. * @return {StorageTextureNode} A reference to this node.
  22068. */
  22069. toReadOnly() {
  22070. return this.setAccess( NodeAccess.READ_ONLY );
  22071. }
  22072. /**
  22073. * Convenience method for configuring a write-only node access.
  22074. *
  22075. * @return {StorageTextureNode} A reference to this node.
  22076. */
  22077. toWriteOnly() {
  22078. return this.setAccess( NodeAccess.WRITE_ONLY );
  22079. }
  22080. /**
  22081. * Generates the code snippet of the storage texture node.
  22082. *
  22083. * @param {NodeBuilder} builder - The current node builder.
  22084. */
  22085. generateStore( builder ) {
  22086. const properties = builder.getNodeProperties( this );
  22087. const { uvNode, storeNode } = properties;
  22088. const textureProperty = super.generate( builder, 'property' );
  22089. const uvSnippet = uvNode.build( builder, 'uvec2' );
  22090. const storeSnippet = storeNode.build( builder, 'vec4' );
  22091. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  22092. builder.addLineFlowCode( snippet, this );
  22093. }
  22094. }
  22095. /**
  22096. * TSL function for creating a storage texture node.
  22097. *
  22098. * @tsl
  22099. * @function
  22100. * @param {StorageTexture} value - The storage texture.
  22101. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22102. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22103. * @returns {StorageTextureNode}
  22104. */
  22105. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  22106. /**
  22107. * TODO: Explain difference to `storageTexture()`.
  22108. *
  22109. * @tsl
  22110. * @function
  22111. * @param {StorageTexture} value - The storage texture.
  22112. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22113. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22114. * @returns {StorageTextureNode}
  22115. */
  22116. const textureStore = ( value, uvNode, storeNode ) => {
  22117. const node = storageTexture( value, uvNode, storeNode );
  22118. if ( storeNode !== null ) node.append();
  22119. return node;
  22120. };
  22121. /**
  22122. * A special type of reference node that allows to link values in
  22123. * `userData` fields to node objects.
  22124. * ```js
  22125. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  22126. *
  22127. * const material = new THREE.SpriteNodeMaterial();
  22128. * material.rotationNode = userData( 'rotation', 'float' );
  22129. * ```
  22130. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  22131. * will automatically be updated when the `rotation` user data field changes.
  22132. *
  22133. * @augments ReferenceNode
  22134. */
  22135. class UserDataNode extends ReferenceNode {
  22136. static get type() {
  22137. return 'UserDataNode';
  22138. }
  22139. /**
  22140. * Constructs a new user data node.
  22141. *
  22142. * @param {string} property - The property name that should be referenced by the node.
  22143. * @param {string} inputType - The node data type of the reference.
  22144. * @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.
  22145. */
  22146. constructor( property, inputType, userData = null ) {
  22147. super( property, inputType, userData );
  22148. /**
  22149. * A reference to the `userData` object. If not provided, the `userData`
  22150. * property of the 3D object that uses the node material is evaluated.
  22151. *
  22152. * @type {?Object}
  22153. * @default null
  22154. */
  22155. this.userData = userData;
  22156. }
  22157. /**
  22158. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  22159. * `userData` field.
  22160. *
  22161. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  22162. * @return {Object} A reference to the `userData` field.
  22163. */
  22164. updateReference( state ) {
  22165. this.reference = this.userData !== null ? this.userData : state.object.userData;
  22166. return this.reference;
  22167. }
  22168. }
  22169. /**
  22170. * TSL function for creating a user data node.
  22171. *
  22172. * @tsl
  22173. * @function
  22174. * @param {string} name - The property name that should be referenced by the node.
  22175. * @param {string} inputType - The node data type of the reference.
  22176. * @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.
  22177. * @returns {UserDataNode}
  22178. */
  22179. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  22180. const _objectData = new WeakMap();
  22181. /**
  22182. * A node for representing motion or velocity vectors. Foundation
  22183. * for advanced post processing effects like motion blur or TRAA.
  22184. *
  22185. * The node keeps track of the model, view and projection matrices
  22186. * of the previous frame and uses them to compute offsets in NDC space.
  22187. * These offsets represent the final velocity.
  22188. *
  22189. * @augments TempNode
  22190. */
  22191. class VelocityNode extends TempNode {
  22192. static get type() {
  22193. return 'VelocityNode';
  22194. }
  22195. /**
  22196. * Constructs a new vertex color node.
  22197. */
  22198. constructor() {
  22199. super( 'vec2' );
  22200. /**
  22201. * The current projection matrix.
  22202. *
  22203. * @type {?Matrix4}
  22204. * @default null
  22205. */
  22206. this.projectionMatrix = null;
  22207. /**
  22208. * Overwritten since velocity nodes are updated per object.
  22209. *
  22210. * @type {string}
  22211. * @default 'object'
  22212. */
  22213. this.updateType = NodeUpdateType.OBJECT;
  22214. /**
  22215. * Overwritten since velocity nodes save data after the update.
  22216. *
  22217. * @type {string}
  22218. * @default 'object'
  22219. */
  22220. this.updateAfterType = NodeUpdateType.OBJECT;
  22221. /**
  22222. * Uniform node representing the previous model matrix in world space.
  22223. *
  22224. * @type {UniformNode<mat4>}
  22225. * @default null
  22226. */
  22227. this.previousModelWorldMatrix = uniform( new Matrix4() );
  22228. /**
  22229. * Uniform node representing the previous projection matrix.
  22230. *
  22231. * @type {UniformNode<mat4>}
  22232. * @default null
  22233. */
  22234. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  22235. /**
  22236. * Uniform node representing the previous view matrix.
  22237. *
  22238. * @type {UniformNode<mat4>}
  22239. * @default null
  22240. */
  22241. this.previousCameraViewMatrix = uniform( new Matrix4() );
  22242. }
  22243. /**
  22244. * Sets the given projection matrix.
  22245. *
  22246. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  22247. */
  22248. setProjectionMatrix( projectionMatrix ) {
  22249. this.projectionMatrix = projectionMatrix;
  22250. }
  22251. /**
  22252. * Updates velocity specific uniforms.
  22253. *
  22254. * @param {NodeFrame} frame - A reference to the current node frame.
  22255. */
  22256. update( { frameId, camera, object } ) {
  22257. const previousModelMatrix = getPreviousMatrix( object );
  22258. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  22259. //
  22260. const cameraData = getData( camera );
  22261. if ( cameraData.frameId !== frameId ) {
  22262. cameraData.frameId = frameId;
  22263. if ( cameraData.previousProjectionMatrix === undefined ) {
  22264. cameraData.previousProjectionMatrix = new Matrix4();
  22265. cameraData.previousCameraViewMatrix = new Matrix4();
  22266. cameraData.currentProjectionMatrix = new Matrix4();
  22267. cameraData.currentCameraViewMatrix = new Matrix4();
  22268. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  22269. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  22270. } else {
  22271. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  22272. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  22273. }
  22274. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  22275. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  22276. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  22277. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  22278. }
  22279. }
  22280. /**
  22281. * Overwritten to updated velocity specific uniforms.
  22282. *
  22283. * @param {NodeFrame} frame - A reference to the current node frame.
  22284. */
  22285. updateAfter( { object } ) {
  22286. getPreviousMatrix( object ).copy( object.matrixWorld );
  22287. }
  22288. /**
  22289. * Implements the velocity computation based on the previous and current vertex data.
  22290. *
  22291. * @param {NodeBuilder} builder - A reference to the current node builder.
  22292. * @return {Node<vec2>} The motion vector.
  22293. */
  22294. setup( /*builder*/ ) {
  22295. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  22296. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  22297. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22298. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  22299. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  22300. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  22301. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  22302. return velocity;
  22303. }
  22304. }
  22305. function getData( object ) {
  22306. let objectData = _objectData.get( object );
  22307. if ( objectData === undefined ) {
  22308. objectData = {};
  22309. _objectData.set( object, objectData );
  22310. }
  22311. return objectData;
  22312. }
  22313. function getPreviousMatrix( object, index = 0 ) {
  22314. const objectData = getData( object );
  22315. let matrix = objectData[ index ];
  22316. if ( matrix === undefined ) {
  22317. objectData[ index ] = matrix = new Matrix4();
  22318. }
  22319. return matrix;
  22320. }
  22321. /**
  22322. * TSL object that represents the velocity of a render pass.
  22323. *
  22324. * @tsl
  22325. * @type {VelocityNode}
  22326. */
  22327. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  22328. /**
  22329. * Represents a "Color Burn" blend mode.
  22330. *
  22331. * It's designed to darken the base layer's colors based on the color of the blend layer.
  22332. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  22333. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  22334. *
  22335. * @tsl
  22336. * @function
  22337. * @param {Node<vec3>} base - The base color.
  22338. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  22339. * @return {Node<vec3>} The result.
  22340. */
  22341. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22342. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  22343. } ).setLayout( {
  22344. name: 'blendBurn',
  22345. type: 'vec3',
  22346. inputs: [
  22347. { name: 'base', type: 'vec3' },
  22348. { name: 'blend', type: 'vec3' }
  22349. ]
  22350. } );
  22351. /**
  22352. * Represents a "Color Dodge" blend mode.
  22353. *
  22354. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  22355. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  22356. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  22357. *
  22358. * @tsl
  22359. * @function
  22360. * @param {Node<vec3>} base - The base color.
  22361. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  22362. * @return {Node<vec3>} The result.
  22363. */
  22364. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22365. return min$1( base.div( blend.oneMinus() ), 1.0 );
  22366. } ).setLayout( {
  22367. name: 'blendDodge',
  22368. type: 'vec3',
  22369. inputs: [
  22370. { name: 'base', type: 'vec3' },
  22371. { name: 'blend', type: 'vec3' }
  22372. ]
  22373. } );
  22374. /**
  22375. * Represents a "Screen" blend mode.
  22376. *
  22377. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  22378. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  22379. * effects.
  22380. *
  22381. * @tsl
  22382. * @function
  22383. * @param {Node<vec3>} base - The base color.
  22384. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  22385. * @return {Node<vec3>} The result.
  22386. */
  22387. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22388. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  22389. } ).setLayout( {
  22390. name: 'blendScreen',
  22391. type: 'vec3',
  22392. inputs: [
  22393. { name: 'base', type: 'vec3' },
  22394. { name: 'blend', type: 'vec3' }
  22395. ]
  22396. } );
  22397. /**
  22398. * Represents a "Overlay" blend mode.
  22399. *
  22400. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  22401. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  22402. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  22403. *
  22404. * @tsl
  22405. * @function
  22406. * @param {Node<vec3>} base - The base color.
  22407. * @param {Node<vec3>} blend - The blend color
  22408. * @return {Node<vec3>} The result.
  22409. */
  22410. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22411. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  22412. } ).setLayout( {
  22413. name: 'blendOverlay',
  22414. type: 'vec3',
  22415. inputs: [
  22416. { name: 'base', type: 'vec3' },
  22417. { name: 'blend', type: 'vec3' }
  22418. ]
  22419. } );
  22420. /**
  22421. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  22422. * It assumes both input colors have non-preumiltiplied alpha.
  22423. *
  22424. * @tsl
  22425. * @function
  22426. * @param {Node<vec4>} base - The base color.
  22427. * @param {Node<vec4>} blend - The blend color
  22428. * @return {Node<vec4>} The result.
  22429. */
  22430. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22431. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  22432. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  22433. } ).setLayout( {
  22434. name: 'blendColor',
  22435. type: 'vec4',
  22436. inputs: [
  22437. { name: 'base', type: 'vec4' },
  22438. { name: 'blend', type: 'vec4' }
  22439. ]
  22440. } );
  22441. // Deprecated
  22442. /**
  22443. * @tsl
  22444. * @function
  22445. * @deprecated since r171. Use {@link blendBurn} instead.
  22446. *
  22447. * @param {...any} params
  22448. * @returns {Function}
  22449. */
  22450. const burn = ( ...params ) => { // @deprecated, r171
  22451. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  22452. return blendBurn( params );
  22453. };
  22454. /**
  22455. * @tsl
  22456. * @function
  22457. * @deprecated since r171. Use {@link blendDodge} instead.
  22458. *
  22459. * @param {...any} params
  22460. * @returns {Function}
  22461. */
  22462. const dodge = ( ...params ) => { // @deprecated, r171
  22463. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  22464. return blendDodge( params );
  22465. };
  22466. /**
  22467. * @tsl
  22468. * @function
  22469. * @deprecated since r171. Use {@link blendScreen} instead.
  22470. *
  22471. * @param {...any} params
  22472. * @returns {Function}
  22473. */
  22474. const screen = ( ...params ) => { // @deprecated, r171
  22475. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  22476. return blendScreen( params );
  22477. };
  22478. /**
  22479. * @tsl
  22480. * @function
  22481. * @deprecated since r171. Use {@link blendOverlay} instead.
  22482. *
  22483. * @param {...any} params
  22484. * @returns {Function}
  22485. */
  22486. const overlay = ( ...params ) => { // @deprecated, r171
  22487. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  22488. return blendOverlay( params );
  22489. };
  22490. /**
  22491. * Computes a grayscale value for the given RGB color value.
  22492. *
  22493. * @tsl
  22494. * @function
  22495. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  22496. * @return {Node<vec3>} The grayscale color.
  22497. */
  22498. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22499. return luminance( color.rgb );
  22500. } );
  22501. /**
  22502. * Super-saturates or desaturates the given RGB color.
  22503. *
  22504. * @tsl
  22505. * @function
  22506. * @param {Node<vec3>} color - The input color.
  22507. * @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.
  22508. * @return {Node<vec3>} The saturated color.
  22509. */
  22510. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22511. return adjustment.mix( luminance( color.rgb ), color.rgb );
  22512. } );
  22513. /**
  22514. * Selectively enhance the intensity of less saturated RGB colors. Can result
  22515. * in a more natural and visually appealing image with enhanced color depth
  22516. * compared to {@link ColorAdjustment#saturation}.
  22517. *
  22518. * @tsl
  22519. * @function
  22520. * @param {Node<vec3>} color - The input color.
  22521. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  22522. * @return {Node<vec3>} The updated color.
  22523. */
  22524. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22525. const average = add( color.r, color.g, color.b ).div( 3.0 );
  22526. const mx = color.r.max( color.g.max( color.b ) );
  22527. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  22528. return mix( color.rgb, mx, amt );
  22529. } );
  22530. /**
  22531. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  22532. *
  22533. * @tsl
  22534. * @function
  22535. * @param {Node<vec3>} color - The input color.
  22536. * @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.
  22537. * @return {Node<vec3>} The updated color.
  22538. */
  22539. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22540. const k = vec3( 0.57735, 0.57735, 0.57735 );
  22541. const cosAngle = adjustment.cos();
  22542. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  22543. } );
  22544. /**
  22545. * Computes the luminance for the given RGB color value.
  22546. *
  22547. * @tsl
  22548. * @function
  22549. * @param {Node<vec3>} color - The color value to compute the luminance for.
  22550. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  22551. * @return {Node<vec3>} The luminance.
  22552. */
  22553. const luminance = (
  22554. color,
  22555. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  22556. ) => dot( color, luminanceCoefficients );
  22557. /**
  22558. * Color Decision List (CDL) v1.2
  22559. *
  22560. * Compact representation of color grading information, defined by slope, offset, power, and
  22561. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  22562. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  22563. *
  22564. * @tsl
  22565. * @function
  22566. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  22567. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  22568. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  22569. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  22570. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  22571. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  22572. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  22573. *
  22574. * References:
  22575. * - ASC CDL v1.2
  22576. * - {@link https://blender.stackexchange.com/a/55239/43930}
  22577. * - {@link https://docs.acescentral.com/specifications/acescc/}
  22578. */
  22579. const cdl = /*@__PURE__*/ Fn( ( [
  22580. color,
  22581. slope = vec3( 1 ),
  22582. offset = vec3( 0 ),
  22583. power = vec3( 1 ),
  22584. saturation = float( 1 ),
  22585. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  22586. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  22587. ] ) => {
  22588. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  22589. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  22590. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  22591. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  22592. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  22593. const pv = v.pow( power ).toVar();
  22594. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  22595. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  22596. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  22597. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  22598. return vec4( v.rgb, color.a );
  22599. } );
  22600. /**
  22601. * Represents a posterize effect which reduces the number of colors
  22602. * in an image, resulting in a more blocky and stylized appearance.
  22603. *
  22604. * @augments TempNode
  22605. */
  22606. class PosterizeNode extends TempNode {
  22607. static get type() {
  22608. return 'PosterizeNode';
  22609. }
  22610. /**
  22611. * Constructs a new posterize node.
  22612. *
  22613. * @param {Node} sourceNode - The input color.
  22614. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22615. */
  22616. constructor( sourceNode, stepsNode ) {
  22617. super();
  22618. /**
  22619. * The input color.
  22620. *
  22621. * @type {Node}
  22622. */
  22623. this.sourceNode = sourceNode;
  22624. /**
  22625. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22626. *
  22627. * @type {Node}
  22628. */
  22629. this.stepsNode = stepsNode;
  22630. }
  22631. setup() {
  22632. const { sourceNode, stepsNode } = this;
  22633. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  22634. }
  22635. }
  22636. /**
  22637. * TSL function for creating a posterize node.
  22638. *
  22639. * @tsl
  22640. * @function
  22641. * @param {Node} sourceNode - The input color.
  22642. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22643. * @returns {PosterizeNode}
  22644. */
  22645. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  22646. const _size = /*@__PURE__*/ new Vector2();
  22647. /**
  22648. * Represents the texture of a pass node.
  22649. *
  22650. * @augments TextureNode
  22651. */
  22652. class PassTextureNode extends TextureNode {
  22653. static get type() {
  22654. return 'PassTextureNode';
  22655. }
  22656. /**
  22657. * Constructs a new pass texture node.
  22658. *
  22659. * @param {PassNode} passNode - The pass node.
  22660. * @param {Texture} texture - The output texture.
  22661. */
  22662. constructor( passNode, texture ) {
  22663. super( texture );
  22664. /**
  22665. * A reference to the pass node.
  22666. *
  22667. * @type {PassNode}
  22668. */
  22669. this.passNode = passNode;
  22670. this.setUpdateMatrix( false );
  22671. }
  22672. setup( builder ) {
  22673. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22674. return super.setup( builder );
  22675. }
  22676. clone() {
  22677. return new this.constructor( this.passNode, this.value );
  22678. }
  22679. }
  22680. /**
  22681. * An extension of `PassTextureNode` which allows to manage more than one
  22682. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22683. *
  22684. * @augments PassTextureNode
  22685. */
  22686. class PassMultipleTextureNode extends PassTextureNode {
  22687. static get type() {
  22688. return 'PassMultipleTextureNode';
  22689. }
  22690. /**
  22691. * Constructs a new pass texture node.
  22692. *
  22693. * @param {PassNode} passNode - The pass node.
  22694. * @param {string} textureName - The output texture name.
  22695. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22696. */
  22697. constructor( passNode, textureName, previousTexture = false ) {
  22698. // null is passed to the super call since this class does not
  22699. // use an external texture for rendering pass data into. Instead
  22700. // the texture is managed by the pass node itself
  22701. super( passNode, null );
  22702. /**
  22703. * The output texture name.
  22704. *
  22705. * @type {string}
  22706. */
  22707. this.textureName = textureName;
  22708. /**
  22709. * Whether previous frame data should be used or not.
  22710. *
  22711. * @type {boolean}
  22712. */
  22713. this.previousTexture = previousTexture;
  22714. }
  22715. /**
  22716. * Updates the texture reference of this node.
  22717. */
  22718. updateTexture() {
  22719. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22720. }
  22721. setup( builder ) {
  22722. this.updateTexture();
  22723. return super.setup( builder );
  22724. }
  22725. clone() {
  22726. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22727. }
  22728. }
  22729. /**
  22730. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22731. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22732. * via MRT for further processing.
  22733. *
  22734. * ```js
  22735. * const postProcessing = new PostProcessing( renderer );
  22736. *
  22737. * const scenePass = pass( scene, camera );
  22738. *
  22739. * postProcessing.outputNode = scenePass;
  22740. * ```
  22741. *
  22742. * @augments TempNode
  22743. */
  22744. class PassNode extends TempNode {
  22745. static get type() {
  22746. return 'PassNode';
  22747. }
  22748. /**
  22749. * Constructs a new pass node.
  22750. *
  22751. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22752. * @param {Scene} scene - A reference to the scene.
  22753. * @param {Camera} camera - A reference to the camera.
  22754. * @param {Object} options - Options for the internal render target.
  22755. */
  22756. constructor( scope, scene, camera, options = {} ) {
  22757. super( 'vec4' );
  22758. /**
  22759. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22760. *
  22761. * @type {('color'|'depth')}
  22762. */
  22763. this.scope = scope;
  22764. /**
  22765. * A reference to the scene.
  22766. *
  22767. * @type {Scene}
  22768. */
  22769. this.scene = scene;
  22770. /**
  22771. * A reference to the camera.
  22772. *
  22773. * @type {Camera}
  22774. */
  22775. this.camera = camera;
  22776. /**
  22777. * Options for the internal render target.
  22778. *
  22779. * @type {Object}
  22780. */
  22781. this.options = options;
  22782. /**
  22783. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22784. *
  22785. * @private
  22786. * @type {number}
  22787. * @default 1
  22788. */
  22789. this._pixelRatio = 1;
  22790. /**
  22791. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22792. * @private
  22793. * @type {number}
  22794. * @default 1
  22795. */
  22796. this._width = 1;
  22797. /**
  22798. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22799. * @private
  22800. * @type {number}
  22801. * @default 1
  22802. */
  22803. this._height = 1;
  22804. const depthTexture = new DepthTexture();
  22805. depthTexture.isRenderTargetTexture = true;
  22806. //depthTexture.type = FloatType;
  22807. depthTexture.name = 'depth';
  22808. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22809. renderTarget.texture.name = 'output';
  22810. renderTarget.depthTexture = depthTexture;
  22811. /**
  22812. * The pass's render target.
  22813. *
  22814. * @type {RenderTarget}
  22815. */
  22816. this.renderTarget = renderTarget;
  22817. /**
  22818. * A dictionary holding the internal result textures.
  22819. *
  22820. * @private
  22821. * @type {Object<string, Texture>}
  22822. */
  22823. this._textures = {
  22824. output: renderTarget.texture,
  22825. depth: depthTexture
  22826. };
  22827. /**
  22828. * A dictionary holding the internal texture nodes.
  22829. *
  22830. * @private
  22831. * @type {Object<string, TextureNode>}
  22832. */
  22833. this._textureNodes = {};
  22834. /**
  22835. * A dictionary holding the internal depth nodes.
  22836. *
  22837. * @private
  22838. * @type {Object}
  22839. */
  22840. this._linearDepthNodes = {};
  22841. /**
  22842. * A dictionary holding the internal viewZ nodes.
  22843. *
  22844. * @private
  22845. * @type {Object}
  22846. */
  22847. this._viewZNodes = {};
  22848. /**
  22849. * A dictionary holding the texture data of the previous frame.
  22850. * Used for computing velocity/motion vectors.
  22851. *
  22852. * @private
  22853. * @type {Object<string, Texture>}
  22854. */
  22855. this._previousTextures = {};
  22856. /**
  22857. * A dictionary holding the texture nodes of the previous frame.
  22858. * Used for computing velocity/motion vectors.
  22859. *
  22860. * @private
  22861. * @type {Object<string, TextureNode>}
  22862. */
  22863. this._previousTextureNodes = {};
  22864. /**
  22865. * The `near` property of the camera as a uniform.
  22866. *
  22867. * @private
  22868. * @type {UniformNode}
  22869. */
  22870. this._cameraNear = uniform( 0 );
  22871. /**
  22872. * The `far` property of the camera as a uniform.
  22873. *
  22874. * @private
  22875. * @type {UniformNode}
  22876. */
  22877. this._cameraFar = uniform( 0 );
  22878. /**
  22879. * A MRT node configuring the MRT settings.
  22880. *
  22881. * @private
  22882. * @type {?MRTNode}
  22883. * @default null
  22884. */
  22885. this._mrt = null;
  22886. /**
  22887. * This flag can be used for type testing.
  22888. *
  22889. * @type {boolean}
  22890. * @readonly
  22891. * @default true
  22892. */
  22893. this.isPassNode = true;
  22894. /**
  22895. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22896. * scene once per frame in its {@link PassNode#updateBefore} method.
  22897. *
  22898. * @type {string}
  22899. * @default 'frame'
  22900. */
  22901. this.updateBeforeType = NodeUpdateType.FRAME;
  22902. }
  22903. /**
  22904. * Sets the given MRT node to setup MRT for this pass.
  22905. *
  22906. * @param {MRTNode} mrt - The MRT object.
  22907. * @return {PassNode} A reference to this pass.
  22908. */
  22909. setMRT( mrt ) {
  22910. this._mrt = mrt;
  22911. return this;
  22912. }
  22913. /**
  22914. * Returns the current MRT node.
  22915. *
  22916. * @return {MRTNode} The current MRT node.
  22917. */
  22918. getMRT() {
  22919. return this._mrt;
  22920. }
  22921. /**
  22922. * The method is overwritten so it always returns `true`.
  22923. *
  22924. * @return {boolean} Whether this node is global or not.
  22925. */
  22926. isGlobal() {
  22927. return true;
  22928. }
  22929. /**
  22930. * Returns the texture for the given output name.
  22931. *
  22932. * @param {string} name - The output name to get the texture for.
  22933. * @return {Texture} The texture.
  22934. */
  22935. getTexture( name ) {
  22936. let texture = this._textures[ name ];
  22937. if ( texture === undefined ) {
  22938. const refTexture = this.renderTarget.texture;
  22939. texture = refTexture.clone();
  22940. texture.name = name;
  22941. this._textures[ name ] = texture;
  22942. this.renderTarget.textures.push( texture );
  22943. }
  22944. return texture;
  22945. }
  22946. /**
  22947. * Returns the texture holding the data of the previous frame for the given output name.
  22948. *
  22949. * @param {string} name - The output name to get the texture for.
  22950. * @return {Texture} The texture holding the data of the previous frame.
  22951. */
  22952. getPreviousTexture( name ) {
  22953. let texture = this._previousTextures[ name ];
  22954. if ( texture === undefined ) {
  22955. texture = this.getTexture( name ).clone();
  22956. this._previousTextures[ name ] = texture;
  22957. }
  22958. return texture;
  22959. }
  22960. /**
  22961. * Switches current and previous textures for the given output name.
  22962. *
  22963. * @param {string} name - The output name.
  22964. */
  22965. toggleTexture( name ) {
  22966. const prevTexture = this._previousTextures[ name ];
  22967. if ( prevTexture !== undefined ) {
  22968. const texture = this._textures[ name ];
  22969. const index = this.renderTarget.textures.indexOf( texture );
  22970. this.renderTarget.textures[ index ] = prevTexture;
  22971. this._textures[ name ] = prevTexture;
  22972. this._previousTextures[ name ] = texture;
  22973. this._textureNodes[ name ].updateTexture();
  22974. this._previousTextureNodes[ name ].updateTexture();
  22975. }
  22976. }
  22977. /**
  22978. * Returns the texture node for the given output name.
  22979. *
  22980. * @param {string} [name='output'] - The output name to get the texture node for.
  22981. * @return {TextureNode} The texture node.
  22982. */
  22983. getTextureNode( name = 'output' ) {
  22984. let textureNode = this._textureNodes[ name ];
  22985. if ( textureNode === undefined ) {
  22986. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22987. textureNode.updateTexture();
  22988. this._textureNodes[ name ] = textureNode;
  22989. }
  22990. return textureNode;
  22991. }
  22992. /**
  22993. * Returns the previous texture node for the given output name.
  22994. *
  22995. * @param {string} [name='output'] - The output name to get the previous texture node for.
  22996. * @return {TextureNode} The previous texture node.
  22997. */
  22998. getPreviousTextureNode( name = 'output' ) {
  22999. let textureNode = this._previousTextureNodes[ name ];
  23000. if ( textureNode === undefined ) {
  23001. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  23002. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  23003. textureNode.updateTexture();
  23004. this._previousTextureNodes[ name ] = textureNode;
  23005. }
  23006. return textureNode;
  23007. }
  23008. /**
  23009. * Returns a viewZ node of this pass.
  23010. *
  23011. * @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.
  23012. * @return {Node} The viewZ node.
  23013. */
  23014. getViewZNode( name = 'depth' ) {
  23015. let viewZNode = this._viewZNodes[ name ];
  23016. if ( viewZNode === undefined ) {
  23017. const cameraNear = this._cameraNear;
  23018. const cameraFar = this._cameraFar;
  23019. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  23020. }
  23021. return viewZNode;
  23022. }
  23023. /**
  23024. * Returns a linear depth node of this pass.
  23025. *
  23026. * @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.
  23027. * @return {Node} The linear depth node.
  23028. */
  23029. getLinearDepthNode( name = 'depth' ) {
  23030. let linearDepthNode = this._linearDepthNodes[ name ];
  23031. if ( linearDepthNode === undefined ) {
  23032. const cameraNear = this._cameraNear;
  23033. const cameraFar = this._cameraFar;
  23034. const viewZNode = this.getViewZNode( name );
  23035. // TODO: just if ( builder.camera.isPerspectiveCamera )
  23036. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  23037. }
  23038. return linearDepthNode;
  23039. }
  23040. setup( { renderer } ) {
  23041. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  23042. // TODO: Disable MSAA for WebGL backend for now
  23043. if ( renderer.backend.isWebGLBackend === true ) {
  23044. this.renderTarget.samples = 0;
  23045. }
  23046. this.renderTarget.texture.type = renderer.getColorBufferType();
  23047. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  23048. }
  23049. updateBefore( frame ) {
  23050. const { renderer } = frame;
  23051. const { scene } = this;
  23052. let camera;
  23053. let pixelRatio;
  23054. const outputRenderTarget = renderer.getOutputRenderTarget();
  23055. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  23056. pixelRatio = 1;
  23057. camera = renderer.xr.getCamera();
  23058. renderer.xr.updateCamera( camera );
  23059. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  23060. } else {
  23061. camera = this.camera;
  23062. pixelRatio = renderer.getPixelRatio();
  23063. renderer.getSize( _size );
  23064. }
  23065. this._pixelRatio = pixelRatio;
  23066. this.setSize( _size.width, _size.height );
  23067. const currentRenderTarget = renderer.getRenderTarget();
  23068. const currentMRT = renderer.getMRT();
  23069. this._cameraNear.value = camera.near;
  23070. this._cameraFar.value = camera.far;
  23071. for ( const name in this._previousTextures ) {
  23072. this.toggleTexture( name );
  23073. }
  23074. renderer.setRenderTarget( this.renderTarget );
  23075. renderer.setMRT( this._mrt );
  23076. renderer.render( scene, camera );
  23077. renderer.setRenderTarget( currentRenderTarget );
  23078. renderer.setMRT( currentMRT );
  23079. }
  23080. /**
  23081. * Sets the size of the pass's render target. Honors the pixel ratio.
  23082. *
  23083. * @param {number} width - The width to set.
  23084. * @param {number} height - The height to set.
  23085. */
  23086. setSize( width, height ) {
  23087. this._width = width;
  23088. this._height = height;
  23089. const effectiveWidth = this._width * this._pixelRatio;
  23090. const effectiveHeight = this._height * this._pixelRatio;
  23091. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23092. }
  23093. /**
  23094. * Sets the pixel ratio the pass's render target and updates the size.
  23095. *
  23096. * @param {number} pixelRatio - The pixel ratio to set.
  23097. */
  23098. setPixelRatio( pixelRatio ) {
  23099. this._pixelRatio = pixelRatio;
  23100. this.setSize( this._width, this._height );
  23101. }
  23102. /**
  23103. * Frees internal resources. Should be called when the node is no longer in use.
  23104. */
  23105. dispose() {
  23106. this.renderTarget.dispose();
  23107. }
  23108. }
  23109. PassNode.COLOR = 'color';
  23110. PassNode.DEPTH = 'depth';
  23111. /**
  23112. * TSL function for creating a pass node.
  23113. *
  23114. * @tsl
  23115. * @function
  23116. * @param {Scene} scene - A reference to the scene.
  23117. * @param {Camera} camera - A reference to the camera.
  23118. * @param {Object} options - Options for the internal render target.
  23119. * @returns {PassNode}
  23120. */
  23121. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  23122. /**
  23123. * TSL function for creating a pass texture node.
  23124. *
  23125. * @tsl
  23126. * @function
  23127. * @param {PassNode} pass - The pass node.
  23128. * @param {Texture} texture - The output texture.
  23129. * @returns {PassTextureNode}
  23130. */
  23131. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  23132. /**
  23133. * TSL function for creating a depth pass node.
  23134. *
  23135. * @tsl
  23136. * @function
  23137. * @param {Scene} scene - A reference to the scene.
  23138. * @param {Camera} camera - A reference to the camera.
  23139. * @param {Object} options - Options for the internal render target.
  23140. * @returns {PassNode}
  23141. */
  23142. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  23143. /**
  23144. * Represents a render pass for producing a toon outline effect on compatible objects.
  23145. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  23146. * will receive the outline.
  23147. *
  23148. * ```js
  23149. * const postProcessing = new PostProcessing( renderer );
  23150. *
  23151. * const scenePass = toonOutlinePass( scene, camera );
  23152. *
  23153. * postProcessing.outputNode = scenePass;
  23154. * ```
  23155. * @augments PassNode
  23156. */
  23157. class ToonOutlinePassNode extends PassNode {
  23158. static get type() {
  23159. return 'ToonOutlinePassNode';
  23160. }
  23161. /**
  23162. * Constructs a new outline pass node.
  23163. *
  23164. * @param {Scene} scene - A reference to the scene.
  23165. * @param {Camera} camera - A reference to the camera.
  23166. * @param {Node} colorNode - Defines the outline's color.
  23167. * @param {Node} thicknessNode - Defines the outline's thickness.
  23168. * @param {Node} alphaNode - Defines the outline's alpha.
  23169. */
  23170. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  23171. super( PassNode.COLOR, scene, camera );
  23172. /**
  23173. * Defines the outline's color.
  23174. *
  23175. * @type {Node}
  23176. */
  23177. this.colorNode = colorNode;
  23178. /**
  23179. * Defines the outline's thickness.
  23180. *
  23181. * @type {Node}
  23182. */
  23183. this.thicknessNode = thicknessNode;
  23184. /**
  23185. * Defines the outline's alpha.
  23186. *
  23187. * @type {Node}
  23188. */
  23189. this.alphaNode = alphaNode;
  23190. /**
  23191. * An internal material cache.
  23192. *
  23193. * @private
  23194. * @type {WeakMap<Material, NodeMaterial>}
  23195. */
  23196. this._materialCache = new WeakMap();
  23197. }
  23198. updateBefore( frame ) {
  23199. const { renderer } = frame;
  23200. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  23201. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  23202. // only render outline for supported materials
  23203. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  23204. if ( material.wireframe === false ) {
  23205. const outlineMaterial = this._getOutlineMaterial( material );
  23206. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  23207. }
  23208. }
  23209. // default
  23210. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  23211. } );
  23212. super.updateBefore( frame );
  23213. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  23214. }
  23215. /**
  23216. * Creates the material used for outline rendering.
  23217. *
  23218. * @private
  23219. * @return {NodeMaterial} The outline material.
  23220. */
  23221. _createMaterial() {
  23222. const material = new NodeMaterial();
  23223. material.isMeshToonOutlineMaterial = true;
  23224. material.name = 'Toon_Outline';
  23225. material.side = BackSide;
  23226. // vertex node
  23227. const outlineNormal = normalLocal.negate();
  23228. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  23229. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  23230. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  23231. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  23232. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  23233. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  23234. // color node
  23235. material.colorNode = vec4( this.colorNode, this.alphaNode );
  23236. return material;
  23237. }
  23238. /**
  23239. * For the given toon material, this method returns a corresponding
  23240. * outline material.
  23241. *
  23242. * @private
  23243. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  23244. * @return {NodeMaterial} The outline material.
  23245. */
  23246. _getOutlineMaterial( originalMaterial ) {
  23247. let outlineMaterial = this._materialCache.get( originalMaterial );
  23248. if ( outlineMaterial === undefined ) {
  23249. outlineMaterial = this._createMaterial();
  23250. this._materialCache.set( originalMaterial, outlineMaterial );
  23251. }
  23252. return outlineMaterial;
  23253. }
  23254. }
  23255. /**
  23256. * TSL function for creating a toon outline pass node.
  23257. *
  23258. * @tsl
  23259. * @function
  23260. * @param {Scene} scene - A reference to the scene.
  23261. * @param {Camera} camera - A reference to the camera.
  23262. * @param {Color} color - Defines the outline's color.
  23263. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  23264. * @param {number} [alpha=1] - Defines the outline's alpha.
  23265. * @returns {ToonOutlinePassNode}
  23266. */
  23267. 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 ) ) );
  23268. /**
  23269. * Linear tone mapping, exposure only.
  23270. *
  23271. * @tsl
  23272. * @function
  23273. * @param {Node<vec3>} color - The color that should be tone mapped.
  23274. * @param {Node<float>} exposure - The exposure.
  23275. * @return {Node<vec3>} The tone mapped color.
  23276. */
  23277. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23278. return color.mul( exposure ).clamp();
  23279. } ).setLayout( {
  23280. name: 'linearToneMapping',
  23281. type: 'vec3',
  23282. inputs: [
  23283. { name: 'color', type: 'vec3' },
  23284. { name: 'exposure', type: 'float' }
  23285. ]
  23286. } );
  23287. /**
  23288. * Reinhard tone mapping.
  23289. *
  23290. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  23291. *
  23292. * @tsl
  23293. * @function
  23294. * @param {Node<vec3>} color - The color that should be tone mapped.
  23295. * @param {Node<float>} exposure - The exposure.
  23296. * @return {Node<vec3>} The tone mapped color.
  23297. */
  23298. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23299. color = color.mul( exposure );
  23300. return color.div( color.add( 1.0 ) ).clamp();
  23301. } ).setLayout( {
  23302. name: 'reinhardToneMapping',
  23303. type: 'vec3',
  23304. inputs: [
  23305. { name: 'color', type: 'vec3' },
  23306. { name: 'exposure', type: 'float' }
  23307. ]
  23308. } );
  23309. /**
  23310. * Cineon tone mapping.
  23311. *
  23312. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  23313. *
  23314. * @tsl
  23315. * @function
  23316. * @param {Node<vec3>} color - The color that should be tone mapped.
  23317. * @param {Node<float>} exposure - The exposure.
  23318. * @return {Node<vec3>} The tone mapped color.
  23319. */
  23320. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23321. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  23322. color = color.mul( exposure );
  23323. color = color.sub( 0.004 ).max( 0.0 );
  23324. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  23325. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  23326. return a.div( b ).pow( 2.2 );
  23327. } ).setLayout( {
  23328. name: 'cineonToneMapping',
  23329. type: 'vec3',
  23330. inputs: [
  23331. { name: 'color', type: 'vec3' },
  23332. { name: 'exposure', type: 'float' }
  23333. ]
  23334. } );
  23335. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  23336. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23337. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  23338. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  23339. return a.div( b );
  23340. } );
  23341. /**
  23342. * ACESFilmic tone mapping.
  23343. *
  23344. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  23345. *
  23346. * @tsl
  23347. * @function
  23348. * @param {Node<vec3>} color - The color that should be tone mapped.
  23349. * @param {Node<float>} exposure - The exposure.
  23350. * @return {Node<vec3>} The tone mapped color.
  23351. */
  23352. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23353. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  23354. const ACESInputMat = mat3(
  23355. 0.59719, 0.35458, 0.04823,
  23356. 0.07600, 0.90834, 0.01566,
  23357. 0.02840, 0.13383, 0.83777
  23358. );
  23359. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  23360. const ACESOutputMat = mat3(
  23361. 1.60475, -0.53108, -0.07367,
  23362. -0.10208, 1.10813, -605e-5,
  23363. -327e-5, -0.07276, 1.07602
  23364. );
  23365. color = color.mul( exposure ).div( 0.6 );
  23366. color = ACESInputMat.mul( color );
  23367. // Apply RRT and ODT
  23368. color = RRTAndODTFit( color );
  23369. color = ACESOutputMat.mul( color );
  23370. // Clamp to [0, 1]
  23371. return color.clamp();
  23372. } ).setLayout( {
  23373. name: 'acesFilmicToneMapping',
  23374. type: 'vec3',
  23375. inputs: [
  23376. { name: 'color', type: 'vec3' },
  23377. { name: 'exposure', type: 'float' }
  23378. ]
  23379. } );
  23380. 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 ) );
  23381. 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 ) );
  23382. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  23383. const x = vec3( x_immutable ).toVar();
  23384. const x2 = vec3( x.mul( x ) ).toVar();
  23385. const x4 = vec3( x2.mul( x2 ) ).toVar();
  23386. 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 ) ) ) );
  23387. } );
  23388. /**
  23389. * AgX tone mapping.
  23390. *
  23391. * @tsl
  23392. * @function
  23393. * @param {Node<vec3>} color - The color that should be tone mapped.
  23394. * @param {Node<float>} exposure - The exposure.
  23395. * @return {Node<vec3>} The tone mapped color.
  23396. */
  23397. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23398. const colortone = vec3( color ).toVar();
  23399. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  23400. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  23401. const AgxMinEv = float( -12.47393 );
  23402. const AgxMaxEv = float( 4.026069 );
  23403. colortone.mulAssign( exposure );
  23404. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  23405. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  23406. colortone.assign( max$1( colortone, 1e-10 ) );
  23407. colortone.assign( log2( colortone ) );
  23408. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  23409. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  23410. colortone.assign( agxDefaultContrastApprox( colortone ) );
  23411. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  23412. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  23413. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  23414. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  23415. return colortone;
  23416. } ).setLayout( {
  23417. name: 'agxToneMapping',
  23418. type: 'vec3',
  23419. inputs: [
  23420. { name: 'color', type: 'vec3' },
  23421. { name: 'exposure', type: 'float' }
  23422. ]
  23423. } );
  23424. /**
  23425. * Neutral tone mapping.
  23426. *
  23427. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  23428. *
  23429. * @tsl
  23430. * @function
  23431. * @param {Node<vec3>} color - The color that should be tone mapped.
  23432. * @param {Node<float>} exposure - The exposure.
  23433. * @return {Node<vec3>} The tone mapped color.
  23434. */
  23435. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23436. const StartCompression = float( 0.8 - 0.04 );
  23437. const Desaturation = float( 0.15 );
  23438. color = color.mul( exposure );
  23439. const x = min$1( color.r, min$1( color.g, color.b ) );
  23440. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  23441. color.subAssign( offset );
  23442. const peak = max$1( color.r, max$1( color.g, color.b ) );
  23443. If( peak.lessThan( StartCompression ), () => {
  23444. return color;
  23445. } );
  23446. const d = sub( 1, StartCompression );
  23447. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  23448. color.mulAssign( newPeak.div( peak ) );
  23449. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  23450. return mix( color, vec3( newPeak ), g );
  23451. } ).setLayout( {
  23452. name: 'neutralToneMapping',
  23453. type: 'vec3',
  23454. inputs: [
  23455. { name: 'color', type: 'vec3' },
  23456. { name: 'exposure', type: 'float' }
  23457. ]
  23458. } );
  23459. /**
  23460. * This class represents native code sections. It is the base
  23461. * class for modules like {@link FunctionNode} which allows to implement
  23462. * functions with native shader languages.
  23463. *
  23464. * @augments Node
  23465. */
  23466. class CodeNode extends Node {
  23467. static get type() {
  23468. return 'CodeNode';
  23469. }
  23470. /**
  23471. * Constructs a new code node.
  23472. *
  23473. * @param {string} [code=''] - The native code.
  23474. * @param {Array<Node>} [includes=[]] - An array of includes.
  23475. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23476. */
  23477. constructor( code = '', includes = [], language = '' ) {
  23478. super( 'code' );
  23479. /**
  23480. * This flag can be used for type testing.
  23481. *
  23482. * @type {boolean}
  23483. * @readonly
  23484. * @default true
  23485. */
  23486. this.isCodeNode = true;
  23487. /**
  23488. * The native code.
  23489. *
  23490. * @type {string}
  23491. * @default ''
  23492. */
  23493. this.code = code;
  23494. /**
  23495. * An array of includes
  23496. *
  23497. * @type {Array<Node>}
  23498. * @default []
  23499. */
  23500. this.includes = includes;
  23501. /**
  23502. * The used language.
  23503. *
  23504. * @type {('js'|'wgsl'|'glsl')}
  23505. * @default ''
  23506. */
  23507. this.language = language;
  23508. }
  23509. /**
  23510. * The method is overwritten so it always returns `true`.
  23511. *
  23512. * @return {boolean} Whether this node is global or not.
  23513. */
  23514. isGlobal() {
  23515. return true;
  23516. }
  23517. /**
  23518. * Sets the includes of this code node.
  23519. *
  23520. * @param {Array<Node>} includes - The includes to set.
  23521. * @return {CodeNode} A reference to this node.
  23522. */
  23523. setIncludes( includes ) {
  23524. this.includes = includes;
  23525. return this;
  23526. }
  23527. /**
  23528. * Returns the includes of this code node.
  23529. *
  23530. * @param {NodeBuilder} builder - The current node builder.
  23531. * @return {Array<Node>} The includes.
  23532. */
  23533. getIncludes( /*builder*/ ) {
  23534. return this.includes;
  23535. }
  23536. generate( builder ) {
  23537. const includes = this.getIncludes( builder );
  23538. for ( const include of includes ) {
  23539. include.build( builder );
  23540. }
  23541. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23542. nodeCode.code = this.code;
  23543. return nodeCode.code;
  23544. }
  23545. serialize( data ) {
  23546. super.serialize( data );
  23547. data.code = this.code;
  23548. data.language = this.language;
  23549. }
  23550. deserialize( data ) {
  23551. super.deserialize( data );
  23552. this.code = data.code;
  23553. this.language = data.language;
  23554. }
  23555. }
  23556. /**
  23557. * TSL function for creating a code node.
  23558. *
  23559. * @tsl
  23560. * @function
  23561. * @param {string} [code=''] - The native code.
  23562. * @param {Array<Node>} [includes=[]] - An array of includes.
  23563. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23564. * @returns {CodeNode}
  23565. */
  23566. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  23567. /**
  23568. * TSL function for creating a JS code node.
  23569. *
  23570. * @tsl
  23571. * @function
  23572. * @param {string} src - The native code.
  23573. * @param {Array<Node>} includes - An array of includes.
  23574. * @returns {CodeNode}
  23575. */
  23576. const js = ( src, includes ) => code( src, includes, 'js' );
  23577. /**
  23578. * TSL function for creating a WGSL code node.
  23579. *
  23580. * @tsl
  23581. * @function
  23582. * @param {string} src - The native code.
  23583. * @param {Array<Node>} includes - An array of includes.
  23584. * @returns {CodeNode}
  23585. */
  23586. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23587. /**
  23588. * TSL function for creating a GLSL code node.
  23589. *
  23590. * @tsl
  23591. * @function
  23592. * @param {string} src - The native code.
  23593. * @param {Array<Node>} includes - An array of includes.
  23594. * @returns {CodeNode}
  23595. */
  23596. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23597. /**
  23598. * This class represents a native shader function. It can be used to implement
  23599. * certain aspects of a node material with native shader code. There are two predefined
  23600. * TSL functions for easier usage.
  23601. *
  23602. * - `wgslFn`: Creates a WGSL function node.
  23603. * - `glslFn`: Creates a GLSL function node.
  23604. *
  23605. * A basic example with one include looks like so:
  23606. *
  23607. * ```js
  23608. * const desaturateWGSLFn = wgslFn( `
  23609. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  23610. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  23611. * return vec3<f32>( dot( lum, color ) );
  23612. * }`
  23613. *);
  23614. * const someWGSLFn = wgslFn( `
  23615. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  23616. * return desaturate( color );
  23617. * }
  23618. * `, [ desaturateWGSLFn ] );
  23619. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  23620. *```
  23621. * @augments CodeNode
  23622. */
  23623. class FunctionNode extends CodeNode {
  23624. static get type() {
  23625. return 'FunctionNode';
  23626. }
  23627. /**
  23628. * Constructs a new function node.
  23629. *
  23630. * @param {string} [code=''] - The native code.
  23631. * @param {Array<Node>} [includes=[]] - An array of includes.
  23632. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23633. */
  23634. constructor( code = '', includes = [], language = '' ) {
  23635. super( code, includes, language );
  23636. }
  23637. getNodeType( builder ) {
  23638. return this.getNodeFunction( builder ).type;
  23639. }
  23640. /**
  23641. * Returns the inputs of this function node.
  23642. *
  23643. * @param {NodeBuilder} builder - The current node builder.
  23644. * @return {Array<NodeFunctionInput>} The inputs.
  23645. */
  23646. getInputs( builder ) {
  23647. return this.getNodeFunction( builder ).inputs;
  23648. }
  23649. /**
  23650. * Returns the node function for this function node.
  23651. *
  23652. * @param {NodeBuilder} builder - The current node builder.
  23653. * @return {NodeFunction} The node function.
  23654. */
  23655. getNodeFunction( builder ) {
  23656. const nodeData = builder.getDataFromNode( this );
  23657. let nodeFunction = nodeData.nodeFunction;
  23658. if ( nodeFunction === undefined ) {
  23659. nodeFunction = builder.parser.parseFunction( this.code );
  23660. nodeData.nodeFunction = nodeFunction;
  23661. }
  23662. return nodeFunction;
  23663. }
  23664. generate( builder, output ) {
  23665. super.generate( builder );
  23666. const nodeFunction = this.getNodeFunction( builder );
  23667. const name = nodeFunction.name;
  23668. const type = nodeFunction.type;
  23669. const nodeCode = builder.getCodeFromNode( this, type );
  23670. if ( name !== '' ) {
  23671. // use a custom property name
  23672. nodeCode.name = name;
  23673. }
  23674. const propertyName = builder.getPropertyName( nodeCode );
  23675. const code = this.getNodeFunction( builder ).getCode( propertyName );
  23676. nodeCode.code = code + '\n';
  23677. if ( output === 'property' ) {
  23678. return propertyName;
  23679. } else {
  23680. return builder.format( `${ propertyName }()`, type, output );
  23681. }
  23682. }
  23683. }
  23684. const nativeFn = ( code, includes = [], language = '' ) => {
  23685. for ( let i = 0; i < includes.length; i ++ ) {
  23686. const include = includes[ i ];
  23687. // TSL Function: glslFn, wgslFn
  23688. if ( typeof include === 'function' ) {
  23689. includes[ i ] = include.functionNode;
  23690. }
  23691. }
  23692. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23693. const fn = ( ...params ) => functionNode.call( ...params );
  23694. fn.functionNode = functionNode;
  23695. return fn;
  23696. };
  23697. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23698. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23699. /**
  23700. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23701. *
  23702. * @augments Node
  23703. */
  23704. class ScriptableValueNode extends Node {
  23705. static get type() {
  23706. return 'ScriptableValueNode';
  23707. }
  23708. /**
  23709. * Constructs a new scriptable node.
  23710. *
  23711. * @param {any} [value=null] - The value.
  23712. */
  23713. constructor( value = null ) {
  23714. super();
  23715. /**
  23716. * A reference to the value.
  23717. *
  23718. * @private
  23719. * @default null
  23720. */
  23721. this._value = value;
  23722. /**
  23723. * Depending on the type of `_value`, this property might cache parsed data.
  23724. *
  23725. * @private
  23726. * @default null
  23727. */
  23728. this._cache = null;
  23729. /**
  23730. * If this node represents an input, this property represents the input type.
  23731. *
  23732. * @type {?string}
  23733. * @default null
  23734. */
  23735. this.inputType = null;
  23736. /**
  23737. * If this node represents an output, this property represents the output type.
  23738. *
  23739. * @type {?string}
  23740. * @default null
  23741. */
  23742. this.outputType = null;
  23743. /**
  23744. * An event dispatcher for managing events.
  23745. *
  23746. * @type {EventDispatcher}
  23747. */
  23748. this.events = new EventDispatcher();
  23749. /**
  23750. * This flag can be used for type testing.
  23751. *
  23752. * @type {boolean}
  23753. * @readonly
  23754. * @default true
  23755. */
  23756. this.isScriptableValueNode = true;
  23757. }
  23758. /**
  23759. * Whether this node represents an output or not.
  23760. *
  23761. * @type {boolean}
  23762. * @readonly
  23763. * @default true
  23764. */
  23765. get isScriptableOutputNode() {
  23766. return this.outputType !== null;
  23767. }
  23768. set value( val ) {
  23769. if ( this._value === val ) return;
  23770. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23771. URL.revokeObjectURL( this._cache );
  23772. this._cache = null;
  23773. }
  23774. this._value = val;
  23775. this.events.dispatchEvent( { type: 'change' } );
  23776. this.refresh();
  23777. }
  23778. /**
  23779. * The node's value.
  23780. *
  23781. * @type {any}
  23782. */
  23783. get value() {
  23784. return this._value;
  23785. }
  23786. /**
  23787. * Dispatches the `refresh` event.
  23788. */
  23789. refresh() {
  23790. this.events.dispatchEvent( { type: 'refresh' } );
  23791. }
  23792. /**
  23793. * The `value` property usually represents a node or even binary data in form of array buffers.
  23794. * In this case, this method tries to return the actual value behind the complex type.
  23795. *
  23796. * @return {any} The value.
  23797. */
  23798. getValue() {
  23799. const value = this.value;
  23800. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23801. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23802. } else if ( value && value.value !== null && value.value !== undefined && (
  23803. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23804. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23805. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23806. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23807. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23808. ( this.inputType === 'Color' && value.value.isColor ) ||
  23809. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23810. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23811. ) ) {
  23812. return value.value;
  23813. }
  23814. return this._cache || value;
  23815. }
  23816. /**
  23817. * Overwritten since the node type is inferred from the value.
  23818. *
  23819. * @param {NodeBuilder} builder - The current node builder.
  23820. * @return {string} The node type.
  23821. */
  23822. getNodeType( builder ) {
  23823. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23824. }
  23825. setup() {
  23826. return this.value && this.value.isNode ? this.value : float();
  23827. }
  23828. serialize( data ) {
  23829. super.serialize( data );
  23830. if ( this.value !== null ) {
  23831. if ( this.inputType === 'ArrayBuffer' ) {
  23832. data.value = arrayBufferToBase64( this.value );
  23833. } else {
  23834. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23835. }
  23836. } else {
  23837. data.value = null;
  23838. }
  23839. data.inputType = this.inputType;
  23840. data.outputType = this.outputType;
  23841. }
  23842. deserialize( data ) {
  23843. super.deserialize( data );
  23844. let value = null;
  23845. if ( data.value !== null ) {
  23846. if ( data.inputType === 'ArrayBuffer' ) {
  23847. value = base64ToArrayBuffer( data.value );
  23848. } else if ( data.inputType === 'Texture' ) {
  23849. value = data.meta.textures[ data.value ];
  23850. } else {
  23851. value = data.meta.nodes[ data.value ] || null;
  23852. }
  23853. }
  23854. this.value = value;
  23855. this.inputType = data.inputType;
  23856. this.outputType = data.outputType;
  23857. }
  23858. }
  23859. /**
  23860. * TSL function for creating a scriptable value node.
  23861. *
  23862. * @tsl
  23863. * @function
  23864. * @param {any} [value=null] - The value.
  23865. * @returns {ScriptableValueNode}
  23866. */
  23867. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23868. /**
  23869. * A Map-like data structure for managing resources of scriptable nodes.
  23870. *
  23871. * @augments Map
  23872. */
  23873. class Resources extends Map {
  23874. get( key, callback = null, ...params ) {
  23875. if ( this.has( key ) ) return super.get( key );
  23876. if ( callback !== null ) {
  23877. const value = callback( ...params );
  23878. this.set( key, value );
  23879. return value;
  23880. }
  23881. }
  23882. }
  23883. class Parameters {
  23884. constructor( scriptableNode ) {
  23885. this.scriptableNode = scriptableNode;
  23886. }
  23887. get parameters() {
  23888. return this.scriptableNode.parameters;
  23889. }
  23890. get layout() {
  23891. return this.scriptableNode.getLayout();
  23892. }
  23893. getInputLayout( id ) {
  23894. return this.scriptableNode.getInputLayout( id );
  23895. }
  23896. get( name ) {
  23897. const param = this.parameters[ name ];
  23898. const value = param ? param.getValue() : null;
  23899. return value;
  23900. }
  23901. }
  23902. /**
  23903. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23904. *
  23905. * @type {Resources}
  23906. */
  23907. const ScriptableNodeResources = new Resources();
  23908. /**
  23909. * This type of node allows to implement nodes with custom scripts. The script
  23910. * section is represented as an instance of `CodeNode` written with JavaScript.
  23911. * The script itself must adhere to a specific structure.
  23912. *
  23913. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23914. * - layout: The layout object defines the script's interface (inputs and outputs).
  23915. *
  23916. * ```js
  23917. * ScriptableNodeResources.set( 'TSL', TSL );
  23918. *
  23919. * const scriptableNode = scriptable( js( `
  23920. * layout = {
  23921. * outputType: 'node',
  23922. * elements: [
  23923. * { name: 'source', inputType: 'node' },
  23924. * ]
  23925. * };
  23926. *
  23927. * const { mul, oscSine } = TSL;
  23928. *
  23929. * function main() {
  23930. * const source = parameters.get( 'source' ) || float();
  23931. * return mul( source, oscSine() ) );
  23932. * }
  23933. *
  23934. * ` ) );
  23935. *
  23936. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23937. *
  23938. * const material = new THREE.MeshBasicNodeMaterial();
  23939. * material.colorNode = scriptableNode;
  23940. * ```
  23941. *
  23942. * @augments Node
  23943. */
  23944. class ScriptableNode extends Node {
  23945. static get type() {
  23946. return 'ScriptableNode';
  23947. }
  23948. /**
  23949. * Constructs a new scriptable node.
  23950. *
  23951. * @param {?CodeNode} [codeNode=null] - The code node.
  23952. * @param {Object} [parameters={}] - The parameters definition.
  23953. */
  23954. constructor( codeNode = null, parameters = {} ) {
  23955. super();
  23956. /**
  23957. * The code node.
  23958. *
  23959. * @type {?CodeNode}
  23960. * @default null
  23961. */
  23962. this.codeNode = codeNode;
  23963. /**
  23964. * The parameters definition.
  23965. *
  23966. * @type {Object}
  23967. * @default {}
  23968. */
  23969. this.parameters = parameters;
  23970. this._local = new Resources();
  23971. this._output = scriptableValue();
  23972. this._outputs = {};
  23973. this._source = this.source;
  23974. this._method = null;
  23975. this._object = null;
  23976. this._value = null;
  23977. this._needsOutputUpdate = true;
  23978. this.onRefresh = this.onRefresh.bind( this );
  23979. /**
  23980. * This flag can be used for type testing.
  23981. *
  23982. * @type {boolean}
  23983. * @readonly
  23984. * @default true
  23985. */
  23986. this.isScriptableNode = true;
  23987. }
  23988. /**
  23989. * The source code of the scriptable node.
  23990. *
  23991. * @type {string}
  23992. */
  23993. get source() {
  23994. return this.codeNode ? this.codeNode.code : '';
  23995. }
  23996. /**
  23997. * Sets the reference of a local script variable.
  23998. *
  23999. * @param {string} name - The variable name.
  24000. * @param {Object} value - The reference to set.
  24001. * @return {Resources} The resource map
  24002. */
  24003. setLocal( name, value ) {
  24004. return this._local.set( name, value );
  24005. }
  24006. /**
  24007. * Gets the value of a local script variable.
  24008. *
  24009. * @param {string} name - The variable name.
  24010. * @return {Object} The value.
  24011. */
  24012. getLocal( name ) {
  24013. return this._local.get( name );
  24014. }
  24015. /**
  24016. * Event listener for the `refresh` event.
  24017. */
  24018. onRefresh() {
  24019. this._refresh();
  24020. }
  24021. /**
  24022. * Returns an input from the layout with the given id/name.
  24023. *
  24024. * @param {string} id - The id/name of the input.
  24025. * @return {Object} The element entry.
  24026. */
  24027. getInputLayout( id ) {
  24028. for ( const element of this.getLayout() ) {
  24029. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  24030. return element;
  24031. }
  24032. }
  24033. }
  24034. /**
  24035. * Returns an output from the layout with the given id/name.
  24036. *
  24037. * @param {string} id - The id/name of the output.
  24038. * @return {Object} The element entry.
  24039. */
  24040. getOutputLayout( id ) {
  24041. for ( const element of this.getLayout() ) {
  24042. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  24043. return element;
  24044. }
  24045. }
  24046. }
  24047. /**
  24048. * Defines a script output for the given name and value.
  24049. *
  24050. * @param {string} name - The name of the output.
  24051. * @param {Node} value - The node value.
  24052. * @return {ScriptableNode} A reference to this node.
  24053. */
  24054. setOutput( name, value ) {
  24055. const outputs = this._outputs;
  24056. if ( outputs[ name ] === undefined ) {
  24057. outputs[ name ] = scriptableValue( value );
  24058. } else {
  24059. outputs[ name ].value = value;
  24060. }
  24061. return this;
  24062. }
  24063. /**
  24064. * Returns a script output for the given name.
  24065. *
  24066. * @param {string} name - The name of the output.
  24067. * @return {ScriptableValueNode} The node value.
  24068. */
  24069. getOutput( name ) {
  24070. return this._outputs[ name ];
  24071. }
  24072. /**
  24073. * Returns a parameter for the given name
  24074. *
  24075. * @param {string} name - The name of the parameter.
  24076. * @return {ScriptableValueNode} The node value.
  24077. */
  24078. getParameter( name ) {
  24079. return this.parameters[ name ];
  24080. }
  24081. /**
  24082. * Sets a value for the given parameter name.
  24083. *
  24084. * @param {string} name - The parameter name.
  24085. * @param {any} value - The parameter value.
  24086. * @return {ScriptableNode} A reference to this node.
  24087. */
  24088. setParameter( name, value ) {
  24089. const parameters = this.parameters;
  24090. if ( value && value.isScriptableNode ) {
  24091. this.deleteParameter( name );
  24092. parameters[ name ] = value;
  24093. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  24094. } else if ( value && value.isScriptableValueNode ) {
  24095. this.deleteParameter( name );
  24096. parameters[ name ] = value;
  24097. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24098. } else if ( parameters[ name ] === undefined ) {
  24099. parameters[ name ] = scriptableValue( value );
  24100. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24101. } else {
  24102. parameters[ name ].value = value;
  24103. }
  24104. return this;
  24105. }
  24106. /**
  24107. * Returns the value of this node which is the value of
  24108. * the default output.
  24109. *
  24110. * @return {Node} The value.
  24111. */
  24112. getValue() {
  24113. return this.getDefaultOutput().getValue();
  24114. }
  24115. /**
  24116. * Deletes a parameter from the script.
  24117. *
  24118. * @param {string} name - The parameter to remove.
  24119. * @return {ScriptableNode} A reference to this node.
  24120. */
  24121. deleteParameter( name ) {
  24122. let valueNode = this.parameters[ name ];
  24123. if ( valueNode ) {
  24124. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  24125. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  24126. }
  24127. return this;
  24128. }
  24129. /**
  24130. * Deletes all parameters from the script.
  24131. *
  24132. * @return {ScriptableNode} A reference to this node.
  24133. */
  24134. clearParameters() {
  24135. for ( const name of Object.keys( this.parameters ) ) {
  24136. this.deleteParameter( name );
  24137. }
  24138. this.needsUpdate = true;
  24139. return this;
  24140. }
  24141. /**
  24142. * Calls a function from the script.
  24143. *
  24144. * @param {string} name - The function name.
  24145. * @param {...any} params - A list of parameters.
  24146. * @return {any} The result of the function call.
  24147. */
  24148. call( name, ...params ) {
  24149. const object = this.getObject();
  24150. const method = object[ name ];
  24151. if ( typeof method === 'function' ) {
  24152. return method( ...params );
  24153. }
  24154. }
  24155. /**
  24156. * Asynchronously calls a function from the script.
  24157. *
  24158. * @param {string} name - The function name.
  24159. * @param {...any} params - A list of parameters.
  24160. * @return {Promise<any>} The result of the function call.
  24161. */
  24162. async callAsync( name, ...params ) {
  24163. const object = this.getObject();
  24164. const method = object[ name ];
  24165. if ( typeof method === 'function' ) {
  24166. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  24167. }
  24168. }
  24169. /**
  24170. * Overwritten since the node types is inferred from the script's output.
  24171. *
  24172. * @param {NodeBuilder} builder - The current node builder
  24173. * @return {string} The node type.
  24174. */
  24175. getNodeType( builder ) {
  24176. return this.getDefaultOutputNode().getNodeType( builder );
  24177. }
  24178. /**
  24179. * Refreshes the script node.
  24180. *
  24181. * @param {?string} [output=null] - An optional output.
  24182. */
  24183. refresh( output = null ) {
  24184. if ( output !== null ) {
  24185. this.getOutput( output ).refresh();
  24186. } else {
  24187. this._refresh();
  24188. }
  24189. }
  24190. /**
  24191. * Returns an object representation of the script.
  24192. *
  24193. * @return {Object} The result object.
  24194. */
  24195. getObject() {
  24196. if ( this.needsUpdate ) this.dispose();
  24197. if ( this._object !== null ) return this._object;
  24198. //
  24199. const refresh = () => this.refresh();
  24200. const setOutput = ( id, value ) => this.setOutput( id, value );
  24201. const parameters = new Parameters( this );
  24202. const THREE = ScriptableNodeResources.get( 'THREE' );
  24203. const TSL = ScriptableNodeResources.get( 'TSL' );
  24204. const method = this.getMethod();
  24205. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  24206. this._object = method( ...params );
  24207. const layout = this._object.layout;
  24208. if ( layout ) {
  24209. if ( layout.cache === false ) {
  24210. this._local.clear();
  24211. }
  24212. // default output
  24213. this._output.outputType = layout.outputType || null;
  24214. if ( Array.isArray( layout.elements ) ) {
  24215. for ( const element of layout.elements ) {
  24216. const id = element.id || element.name;
  24217. if ( element.inputType ) {
  24218. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  24219. this.getParameter( id ).inputType = element.inputType;
  24220. }
  24221. if ( element.outputType ) {
  24222. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  24223. this.getOutput( id ).outputType = element.outputType;
  24224. }
  24225. }
  24226. }
  24227. }
  24228. return this._object;
  24229. }
  24230. deserialize( data ) {
  24231. super.deserialize( data );
  24232. for ( const name in this.parameters ) {
  24233. let valueNode = this.parameters[ name ];
  24234. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  24235. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  24236. }
  24237. }
  24238. /**
  24239. * Returns the layout of the script.
  24240. *
  24241. * @return {Object} The script's layout.
  24242. */
  24243. getLayout() {
  24244. return this.getObject().layout;
  24245. }
  24246. /**
  24247. * Returns default node output of the script.
  24248. *
  24249. * @return {Node} The default node output.
  24250. */
  24251. getDefaultOutputNode() {
  24252. const output = this.getDefaultOutput().value;
  24253. if ( output && output.isNode ) {
  24254. return output;
  24255. }
  24256. return float();
  24257. }
  24258. /**
  24259. * Returns default output of the script.
  24260. *
  24261. * @return {ScriptableValueNode} The default output.
  24262. */
  24263. getDefaultOutput() {
  24264. return this._exec()._output;
  24265. }
  24266. /**
  24267. * Returns a function created from the node's script.
  24268. *
  24269. * @return {Function} The function representing the node's code.
  24270. */
  24271. getMethod() {
  24272. if ( this.needsUpdate ) this.dispose();
  24273. if ( this._method !== null ) return this._method;
  24274. //
  24275. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  24276. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  24277. const properties = interfaceProps.join( ', ' );
  24278. const declarations = 'var ' + properties + '; var output = {};\n';
  24279. const returns = '\nreturn { ...output, ' + properties + ' };';
  24280. const code = declarations + this.codeNode.code + returns;
  24281. //
  24282. this._method = new Function( ...parametersProps, code );
  24283. return this._method;
  24284. }
  24285. /**
  24286. * Frees all internal resources.
  24287. */
  24288. dispose() {
  24289. if ( this._method === null ) return;
  24290. if ( this._object && typeof this._object.dispose === 'function' ) {
  24291. this._object.dispose();
  24292. }
  24293. this._method = null;
  24294. this._object = null;
  24295. this._source = null;
  24296. this._value = null;
  24297. this._needsOutputUpdate = true;
  24298. this._output.value = null;
  24299. this._outputs = {};
  24300. }
  24301. setup() {
  24302. return this.getDefaultOutputNode();
  24303. }
  24304. getCacheKey( force ) {
  24305. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  24306. for ( const param in this.parameters ) {
  24307. values.push( this.parameters[ param ].getCacheKey( force ) );
  24308. }
  24309. return hashArray( values );
  24310. }
  24311. set needsUpdate( value ) {
  24312. if ( value === true ) this.dispose();
  24313. }
  24314. get needsUpdate() {
  24315. return this.source !== this._source;
  24316. }
  24317. /**
  24318. * Executes the `main` function of the script.
  24319. *
  24320. * @private
  24321. * @return {ScriptableNode} A reference to this node.
  24322. */
  24323. _exec() {
  24324. if ( this.codeNode === null ) return this;
  24325. if ( this._needsOutputUpdate === true ) {
  24326. this._value = this.call( 'main' );
  24327. this._needsOutputUpdate = false;
  24328. }
  24329. this._output.value = this._value;
  24330. return this;
  24331. }
  24332. /**
  24333. * Executes the refresh.
  24334. *
  24335. * @private
  24336. */
  24337. _refresh() {
  24338. this.needsUpdate = true;
  24339. this._exec();
  24340. this._output.refresh();
  24341. }
  24342. }
  24343. /**
  24344. * TSL function for creating a scriptable node.
  24345. *
  24346. * @tsl
  24347. * @function
  24348. * @param {?CodeNode} [codeNode=null] - The code node.
  24349. * @param {Object} [parameters={}] - The parameters definition.
  24350. * @returns {ScriptableNode}
  24351. */
  24352. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  24353. /**
  24354. * Returns a node that represents the `z` coordinate in view space
  24355. * for the current fragment. It's a different representation of the
  24356. * default depth value.
  24357. *
  24358. * This value can be part of a computation that defines how the fog
  24359. * density increases when moving away from the camera.
  24360. *
  24361. * @param {NodeBuilder} builder - The current node builder.
  24362. * @return {Node} The viewZ node.
  24363. */
  24364. function getViewZNode( builder ) {
  24365. let viewZ;
  24366. const getViewZ = builder.context.getViewZ;
  24367. if ( getViewZ !== undefined ) {
  24368. viewZ = getViewZ( this );
  24369. }
  24370. return ( viewZ || positionView.z ).negate();
  24371. }
  24372. /**
  24373. * Constructs a new range factor node.
  24374. *
  24375. * @tsl
  24376. * @function
  24377. * @param {Node} near - Defines the near value.
  24378. * @param {Node} far - Defines the far value.
  24379. */
  24380. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  24381. const viewZ = getViewZNode( builder );
  24382. return smoothstep( near, far, viewZ );
  24383. } );
  24384. /**
  24385. * Represents an exponential squared fog. This type of fog gives
  24386. * a clear view near the camera and a faster than exponentially
  24387. * densening fog farther from the camera.
  24388. *
  24389. * @tsl
  24390. * @function
  24391. * @param {Node} density - Defines the fog density.
  24392. */
  24393. const densityFogFactor = Fn( ( [ density ], builder ) => {
  24394. const viewZ = getViewZNode( builder );
  24395. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  24396. } );
  24397. /**
  24398. * This class can be used to configure a fog for the scene.
  24399. * Nodes of this type are assigned to `Scene.fogNode`.
  24400. *
  24401. * @tsl
  24402. * @function
  24403. * @param {Node} color - Defines the color of the fog.
  24404. * @param {Node} factor - Defines how the fog is factored in the scene.
  24405. */
  24406. const fog = Fn( ( [ color, factor ] ) => {
  24407. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  24408. } );
  24409. // Deprecated
  24410. /**
  24411. * @tsl
  24412. * @function
  24413. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  24414. *
  24415. * @param {Node} color
  24416. * @param {Node} near
  24417. * @param {Node} far
  24418. * @returns {Function}
  24419. */
  24420. function rangeFog( color, near, far ) { // @deprecated, r171
  24421. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  24422. return fog( color, rangeFogFactor( near, far ) );
  24423. }
  24424. /**
  24425. * @tsl
  24426. * @function
  24427. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  24428. *
  24429. * @param {Node} color
  24430. * @param {Node} density
  24431. * @returns {Function}
  24432. */
  24433. function densityFog( color, density ) { // @deprecated, r171
  24434. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  24435. return fog( color, densityFogFactor( density ) );
  24436. }
  24437. let min = null;
  24438. let max = null;
  24439. /**
  24440. * `RangeNode` generates random instanced attribute data in a defined range.
  24441. * An exemplary use case for this utility node is to generate random per-instance
  24442. * colors:
  24443. * ```js
  24444. * const material = new MeshBasicNodeMaterial();
  24445. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  24446. * const mesh = new InstancedMesh( geometry, material, count );
  24447. * ```
  24448. * @augments Node
  24449. */
  24450. class RangeNode extends Node {
  24451. static get type() {
  24452. return 'RangeNode';
  24453. }
  24454. /**
  24455. * Constructs a new range node.
  24456. *
  24457. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  24458. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  24459. */
  24460. constructor( minNode = float(), maxNode = float() ) {
  24461. super();
  24462. /**
  24463. * A node defining the lower bound of the range.
  24464. *
  24465. * @type {Node<any>}
  24466. * @default float()
  24467. */
  24468. this.minNode = minNode;
  24469. /**
  24470. * A node defining the upper bound of the range.
  24471. *
  24472. * @type {Node<any>}
  24473. * @default float()
  24474. */
  24475. this.maxNode = maxNode;
  24476. }
  24477. /**
  24478. * Returns the vector length which is computed based on the range definition.
  24479. *
  24480. * @param {NodeBuilder} builder - The current node builder.
  24481. * @return {number} The vector length.
  24482. */
  24483. getVectorLength( builder ) {
  24484. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  24485. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  24486. return minLength > maxLength ? minLength : maxLength;
  24487. }
  24488. /**
  24489. * This method is overwritten since the node type is inferred from range definition.
  24490. *
  24491. * @param {NodeBuilder} builder - The current node builder.
  24492. * @return {string} The node type.
  24493. */
  24494. getNodeType( builder ) {
  24495. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  24496. }
  24497. setup( builder ) {
  24498. const object = builder.object;
  24499. let output = null;
  24500. if ( object.count > 1 ) {
  24501. const minValue = this.minNode.value;
  24502. const maxValue = this.maxNode.value;
  24503. const minLength = builder.getTypeLength( getValueType( minValue ) );
  24504. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  24505. min = min || new Vector4();
  24506. max = max || new Vector4();
  24507. min.setScalar( 0 );
  24508. max.setScalar( 0 );
  24509. if ( minLength === 1 ) min.setScalar( minValue );
  24510. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  24511. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  24512. if ( maxLength === 1 ) max.setScalar( maxValue );
  24513. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  24514. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  24515. const stride = 4;
  24516. const length = stride * object.count;
  24517. const array = new Float32Array( length );
  24518. for ( let i = 0; i < length; i ++ ) {
  24519. const index = i % stride;
  24520. const minElementValue = min.getComponent( index );
  24521. const maxElementValue = max.getComponent( index );
  24522. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  24523. }
  24524. const nodeType = this.getNodeType( builder );
  24525. if ( object.count <= 4096 ) {
  24526. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  24527. } else {
  24528. // TODO: Improve anonymous buffer attribute creation removing this part
  24529. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  24530. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  24531. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  24532. }
  24533. } else {
  24534. output = float( 0 );
  24535. }
  24536. return output;
  24537. }
  24538. }
  24539. /**
  24540. * TSL function for creating a range node.
  24541. *
  24542. * @tsl
  24543. * @function
  24544. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  24545. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  24546. * @returns {RangeNode}
  24547. */
  24548. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  24549. /**
  24550. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  24551. * about the currently running dispatch and/or the device it is running on.
  24552. *
  24553. * This node can only be used with a WebGPU backend.
  24554. *
  24555. * @augments Node
  24556. */
  24557. class ComputeBuiltinNode extends Node {
  24558. static get type() {
  24559. return 'ComputeBuiltinNode';
  24560. }
  24561. /**
  24562. * Constructs a new compute builtin node.
  24563. *
  24564. * @param {string} builtinName - The built-in name.
  24565. * @param {string} nodeType - The node type.
  24566. */
  24567. constructor( builtinName, nodeType ) {
  24568. super( nodeType );
  24569. /**
  24570. * The built-in name.
  24571. *
  24572. * @private
  24573. * @type {string}
  24574. */
  24575. this._builtinName = builtinName;
  24576. }
  24577. /**
  24578. * This method is overwritten since hash is derived from the built-in name.
  24579. *
  24580. * @param {NodeBuilder} builder - The current node builder.
  24581. * @return {string} The hash.
  24582. */
  24583. getHash( builder ) {
  24584. return this.getBuiltinName( builder );
  24585. }
  24586. /**
  24587. * This method is overwritten since the node type is simply derived from `nodeType`..
  24588. *
  24589. * @param {NodeBuilder} builder - The current node builder.
  24590. * @return {string} The node type.
  24591. */
  24592. getNodeType( /*builder*/ ) {
  24593. return this.nodeType;
  24594. }
  24595. /**
  24596. * Sets the builtin name.
  24597. *
  24598. * @param {string} builtinName - The built-in name.
  24599. * @return {ComputeBuiltinNode} A reference to this node.
  24600. */
  24601. setBuiltinName( builtinName ) {
  24602. this._builtinName = builtinName;
  24603. return this;
  24604. }
  24605. /**
  24606. * Returns the builtin name.
  24607. *
  24608. * @param {NodeBuilder} builder - The current node builder.
  24609. * @return {string} The builtin name.
  24610. */
  24611. getBuiltinName( /*builder*/ ) {
  24612. return this._builtinName;
  24613. }
  24614. /**
  24615. * Whether the current node builder has the builtin or not.
  24616. *
  24617. * @param {NodeBuilder} builder - The current node builder.
  24618. */
  24619. hasBuiltin( builder ) {
  24620. builder.hasBuiltin( this._builtinName );
  24621. }
  24622. generate( builder, output ) {
  24623. const builtinName = this.getBuiltinName( builder );
  24624. const nodeType = this.getNodeType( builder );
  24625. if ( builder.shaderStage === 'compute' ) {
  24626. return builder.format( builtinName, nodeType, output );
  24627. } else {
  24628. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  24629. return builder.generateConst( nodeType );
  24630. }
  24631. }
  24632. serialize( data ) {
  24633. super.serialize( data );
  24634. data.global = this.global;
  24635. data._builtinName = this._builtinName;
  24636. }
  24637. deserialize( data ) {
  24638. super.deserialize( data );
  24639. this.global = data.global;
  24640. this._builtinName = data._builtinName;
  24641. }
  24642. }
  24643. /**
  24644. * TSL function for creating a compute builtin node.
  24645. *
  24646. * @tsl
  24647. * @function
  24648. * @param {string} name - The built-in name.
  24649. * @param {string} nodeType - The node type.
  24650. * @returns {ComputeBuiltinNode}
  24651. */
  24652. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  24653. /**
  24654. * Represents the number of workgroups dispatched by the compute shader.
  24655. * ```js
  24656. * // Run 512 invocations/threads with a workgroup size of 128.
  24657. * const computeFn = Fn(() => {
  24658. *
  24659. * // numWorkgroups.x = 4
  24660. * storageBuffer.element(0).assign(numWorkgroups.x)
  24661. *
  24662. * })().compute(512, [128]);
  24663. *
  24664. * // Run 512 invocations/threads with the default workgroup size of 64.
  24665. * const computeFn = Fn(() => {
  24666. *
  24667. * // numWorkgroups.x = 8
  24668. * storageBuffer.element(0).assign(numWorkgroups.x)
  24669. *
  24670. * })().compute(512);
  24671. * ```
  24672. *
  24673. * @tsl
  24674. * @type {ComputeBuiltinNode<uvec3>}
  24675. */
  24676. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  24677. /**
  24678. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  24679. * ```js
  24680. * // Execute 12 compute threads with a workgroup size of 3.
  24681. * const computeFn = Fn( () => {
  24682. *
  24683. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  24684. *
  24685. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  24686. *
  24687. * } ).Else( () => {
  24688. *
  24689. * storageBuffer.element( instanceIndex ).assign( 0 );
  24690. *
  24691. * } );
  24692. *
  24693. * } )().compute( 12, [ 3 ] );
  24694. *
  24695. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24696. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24697. * ```
  24698. *
  24699. * @tsl
  24700. * @type {ComputeBuiltinNode<uvec3>}
  24701. */
  24702. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24703. /**
  24704. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  24705. *
  24706. * @tsl
  24707. * @type {ComputeBuiltinNode<uvec3>}
  24708. */
  24709. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24710. /**
  24711. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  24712. *
  24713. * @tsl
  24714. * @type {ComputeBuiltinNode<uvec3>}
  24715. */
  24716. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24717. /**
  24718. * A device dependent variable that exposes the size of the current invocation's subgroup.
  24719. *
  24720. * @tsl
  24721. * @type {ComputeBuiltinNode<uint>}
  24722. */
  24723. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24724. /**
  24725. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24726. *
  24727. * This node can only be used with a WebGPU backend.
  24728. *
  24729. * @augments Node
  24730. */
  24731. class BarrierNode extends Node {
  24732. /**
  24733. * Constructs a new barrier node.
  24734. *
  24735. * @param {string} scope - The scope defines the behavior of the node.
  24736. */
  24737. constructor( scope ) {
  24738. super();
  24739. this.scope = scope;
  24740. }
  24741. generate( builder ) {
  24742. const { scope } = this;
  24743. const { renderer } = builder;
  24744. if ( renderer.backend.isWebGLBackend === true ) {
  24745. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24746. } else {
  24747. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24748. }
  24749. }
  24750. }
  24751. /**
  24752. * TSL function for creating a barrier node.
  24753. *
  24754. * @tsl
  24755. * @function
  24756. * @param {string} scope - The scope defines the behavior of the node..
  24757. * @returns {BarrierNode}
  24758. */
  24759. const barrier = nodeProxy( BarrierNode );
  24760. /**
  24761. * TSL function for creating a workgroup barrier. All compute shader
  24762. * invocations must wait for each invocation within a workgroup to
  24763. * complete before the barrier can be surpassed.
  24764. *
  24765. * @tsl
  24766. * @function
  24767. * @returns {BarrierNode}
  24768. */
  24769. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24770. /**
  24771. * TSL function for creating a storage barrier. All invocations must
  24772. * wait for each access to variables within the 'storage' address space
  24773. * to complete before the barrier can be passed.
  24774. *
  24775. * @tsl
  24776. * @function
  24777. * @returns {BarrierNode}
  24778. */
  24779. const storageBarrier = () => barrier( 'storage' ).append();
  24780. /**
  24781. * TSL function for creating a texture barrier. All invocations must
  24782. * wait for each access to variables within the 'texture' address space
  24783. * to complete before the barrier can be passed.
  24784. *
  24785. * @tsl
  24786. * @function
  24787. * @returns {BarrierNode}
  24788. */
  24789. const textureBarrier = () => barrier( 'texture' ).append();
  24790. /**
  24791. * Represents an element of a 'workgroup' scoped buffer.
  24792. *
  24793. * @augments ArrayElementNode
  24794. */
  24795. class WorkgroupInfoElementNode extends ArrayElementNode {
  24796. /**
  24797. * Constructs a new workgroup info element node.
  24798. *
  24799. * @param {Node} workgroupInfoNode - The workgroup info node.
  24800. * @param {Node} indexNode - The index node that defines the element access.
  24801. */
  24802. constructor( workgroupInfoNode, indexNode ) {
  24803. super( workgroupInfoNode, indexNode );
  24804. /**
  24805. * This flag can be used for type testing.
  24806. *
  24807. * @type {boolean}
  24808. * @readonly
  24809. * @default true
  24810. */
  24811. this.isWorkgroupInfoElementNode = true;
  24812. }
  24813. generate( builder, output ) {
  24814. let snippet;
  24815. const isAssignContext = builder.context.assign;
  24816. snippet = super.generate( builder );
  24817. if ( isAssignContext !== true ) {
  24818. const type = this.getNodeType( builder );
  24819. snippet = builder.format( snippet, type, output );
  24820. }
  24821. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24822. return snippet;
  24823. }
  24824. }
  24825. /**
  24826. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24827. * context of a compute shader. Typically, workgroup scoped buffers are
  24828. * created to hold data that is transferred from a global storage scope into
  24829. * a local workgroup scope. For invocations within a workgroup, data
  24830. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24831. * than similar access operations on globally accessible storage buffers.
  24832. *
  24833. * This node can only be used with a WebGPU backend.
  24834. *
  24835. * @augments Node
  24836. */
  24837. class WorkgroupInfoNode extends Node {
  24838. /**
  24839. * Constructs a new buffer scoped to type scope.
  24840. *
  24841. * @param {string} scope - TODO.
  24842. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  24843. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  24844. */
  24845. constructor( scope, bufferType, bufferCount = 0 ) {
  24846. super( bufferType );
  24847. /**
  24848. * The buffer type.
  24849. *
  24850. * @type {string}
  24851. */
  24852. this.bufferType = bufferType;
  24853. /**
  24854. * The buffer count.
  24855. *
  24856. * @type {number}
  24857. * @default 0
  24858. */
  24859. this.bufferCount = bufferCount;
  24860. /**
  24861. * This flag can be used for type testing.
  24862. *
  24863. * @type {boolean}
  24864. * @readonly
  24865. * @default true
  24866. */
  24867. this.isWorkgroupInfoNode = true;
  24868. /**
  24869. * The data type of the array buffer.
  24870. *
  24871. * @type {string}
  24872. */
  24873. this.elementType = bufferType;
  24874. /**
  24875. * TODO.
  24876. *
  24877. * @type {string}
  24878. */
  24879. this.scope = scope;
  24880. }
  24881. /**
  24882. * Sets the name/label of this node.
  24883. *
  24884. * @param {string} name - The name to set.
  24885. * @return {WorkgroupInfoNode} A reference to this node.
  24886. */
  24887. label( name ) {
  24888. this.name = name;
  24889. return this;
  24890. }
  24891. /**
  24892. * Sets the scope of this node.
  24893. *
  24894. * @param {string} scope - The scope to set.
  24895. * @return {WorkgroupInfoNode} A reference to this node.
  24896. */
  24897. setScope( scope ) {
  24898. this.scope = scope;
  24899. return this;
  24900. }
  24901. /**
  24902. * The data type of the array buffer.
  24903. *
  24904. * @return {string} The element type.
  24905. */
  24906. getElementType() {
  24907. return this.elementType;
  24908. }
  24909. /**
  24910. * Overwrites the default implementation since the input type
  24911. * is inferred from the scope.
  24912. *
  24913. * @param {NodeBuilder} builder - The current node builder.
  24914. * @return {string} The input type.
  24915. */
  24916. getInputType( /*builder*/ ) {
  24917. return `${this.scope}Array`;
  24918. }
  24919. /**
  24920. * This method can be used to access elements via an index node.
  24921. *
  24922. * @param {IndexNode} indexNode - indexNode.
  24923. * @return {WorkgroupInfoElementNode} A reference to an element.
  24924. */
  24925. element( indexNode ) {
  24926. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24927. }
  24928. generate( builder ) {
  24929. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24930. }
  24931. }
  24932. /**
  24933. * TSL function for creating a workgroup info node.
  24934. * Creates a new 'workgroup' scoped array buffer.
  24935. *
  24936. * @tsl
  24937. * @function
  24938. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  24939. * @param {number} [count=0] - The number of elements in the buffer.
  24940. * @returns {WorkgroupInfoNode}
  24941. */
  24942. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24943. /**
  24944. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24945. * within a shader. In an atomic function, any modification to an atomic variable will
  24946. * occur as an indivisible step with a defined order relative to other modifications.
  24947. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24948. * atomic operations will not interfere with each other.
  24949. *
  24950. * This node can only be used with a WebGPU backend.
  24951. *
  24952. * @augments TempNode
  24953. */
  24954. class AtomicFunctionNode extends TempNode {
  24955. static get type() {
  24956. return 'AtomicFunctionNode';
  24957. }
  24958. /**
  24959. * Constructs a new atomic function node.
  24960. *
  24961. * @param {string} method - The signature of the atomic function to construct.
  24962. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24963. * @param {Node} valueNode - The value that mutates the atomic variable.
  24964. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24965. */
  24966. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24967. super( 'uint' );
  24968. /**
  24969. * The signature of the atomic function to construct.
  24970. *
  24971. * @type {string}
  24972. */
  24973. this.method = method;
  24974. /**
  24975. * An atomic variable or element of an atomic buffer.
  24976. *
  24977. * @type {Node}
  24978. */
  24979. this.pointerNode = pointerNode;
  24980. /**
  24981. * A value that modifies the atomic variable.
  24982. *
  24983. * @type {Node}
  24984. */
  24985. this.valueNode = valueNode;
  24986. /**
  24987. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24988. *
  24989. * @type {?Node}
  24990. * @default null
  24991. */
  24992. this.storeNode = storeNode;
  24993. }
  24994. /**
  24995. * Overwrites the default implementation to return the type of
  24996. * the pointer node.
  24997. *
  24998. * @param {NodeBuilder} builder - The current node builder.
  24999. * @return {string} The input type.
  25000. */
  25001. getInputType( builder ) {
  25002. return this.pointerNode.getNodeType( builder );
  25003. }
  25004. /**
  25005. * Overwritten since the node type is inferred from the input type.
  25006. *
  25007. * @param {NodeBuilder} builder - The current node builder.
  25008. * @return {string} The node type.
  25009. */
  25010. getNodeType( builder ) {
  25011. return this.getInputType( builder );
  25012. }
  25013. generate( builder ) {
  25014. const method = this.method;
  25015. const type = this.getNodeType( builder );
  25016. const inputType = this.getInputType( builder );
  25017. const a = this.pointerNode;
  25018. const b = this.valueNode;
  25019. const params = [];
  25020. params.push( `&${ a.build( builder, inputType ) }` );
  25021. if ( b !== null ) {
  25022. params.push( b.build( builder, inputType ) );
  25023. }
  25024. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  25025. if ( this.storeNode !== null ) {
  25026. const varSnippet = this.storeNode.build( builder, inputType );
  25027. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  25028. } else {
  25029. builder.addLineFlowCode( methodSnippet, this );
  25030. }
  25031. }
  25032. }
  25033. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  25034. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  25035. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  25036. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  25037. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  25038. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  25039. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  25040. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  25041. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  25042. /**
  25043. * TSL function for creating an atomic function node.
  25044. *
  25045. * @tsl
  25046. * @function
  25047. * @param {string} method - The signature of the atomic function to construct.
  25048. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25049. * @param {Node} valueNode - The value that mutates the atomic variable.
  25050. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25051. * @returns {AtomicFunctionNode}
  25052. */
  25053. const atomicNode = nodeProxy( AtomicFunctionNode );
  25054. /**
  25055. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  25056. *
  25057. * @tsl
  25058. * @function
  25059. * @param {string} method - The signature of the atomic function to construct.
  25060. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25061. * @param {Node} valueNode - The value that mutates the atomic variable.
  25062. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25063. * @returns {AtomicFunctionNode}
  25064. */
  25065. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  25066. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  25067. node.append();
  25068. return node;
  25069. };
  25070. /**
  25071. * Loads the value stored in the atomic variable.
  25072. *
  25073. * @tsl
  25074. * @function
  25075. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25076. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25077. * @returns {AtomicFunctionNode}
  25078. */
  25079. const atomicLoad = ( pointerNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null, storeNode );
  25080. /**
  25081. * Stores a value in the atomic variable.
  25082. *
  25083. * @tsl
  25084. * @function
  25085. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25086. * @param {Node} valueNode - The value that mutates the atomic variable.
  25087. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25088. * @returns {AtomicFunctionNode}
  25089. */
  25090. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  25091. /**
  25092. * Increments the value stored in the atomic variable.
  25093. *
  25094. * @tsl
  25095. * @function
  25096. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25097. * @param {Node} valueNode - The value that mutates the atomic variable.
  25098. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25099. * @returns {AtomicFunctionNode}
  25100. */
  25101. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  25102. /**
  25103. * Decrements the value stored in the atomic variable.
  25104. *
  25105. * @tsl
  25106. * @function
  25107. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25108. * @param {Node} valueNode - The value that mutates the atomic variable.
  25109. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25110. * @returns {AtomicFunctionNode}
  25111. */
  25112. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  25113. /**
  25114. * Stores in an atomic variable the maximum between its current value and a parameter.
  25115. *
  25116. * @tsl
  25117. * @function
  25118. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25119. * @param {Node} valueNode - The value that mutates the atomic variable.
  25120. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25121. * @returns {AtomicFunctionNode}
  25122. */
  25123. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  25124. /**
  25125. * Stores in an atomic variable the minimum between its current value and a parameter.
  25126. *
  25127. * @tsl
  25128. * @function
  25129. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25130. * @param {Node} valueNode - The value that mutates the atomic variable.
  25131. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25132. * @returns {AtomicFunctionNode}
  25133. */
  25134. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  25135. /**
  25136. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  25137. *
  25138. * @tsl
  25139. * @function
  25140. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25141. * @param {Node} valueNode - The value that mutates the atomic variable.
  25142. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25143. * @returns {AtomicFunctionNode}
  25144. */
  25145. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  25146. /**
  25147. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  25148. *
  25149. * @tsl
  25150. * @function
  25151. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25152. * @param {Node} valueNode - The value that mutates the atomic variable.
  25153. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25154. * @returns {AtomicFunctionNode}
  25155. */
  25156. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  25157. /**
  25158. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  25159. *
  25160. * @tsl
  25161. * @function
  25162. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25163. * @param {Node} valueNode - The value that mutates the atomic variable.
  25164. * @param {?Node} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  25165. * @returns {AtomicFunctionNode}
  25166. */
  25167. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  25168. let uniformsLib;
  25169. function getLightData( light ) {
  25170. uniformsLib = uniformsLib || new WeakMap();
  25171. let uniforms = uniformsLib.get( light );
  25172. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  25173. return uniforms;
  25174. }
  25175. /**
  25176. * TSL function for getting a shadow matrix uniform node for the given light.
  25177. *
  25178. * @tsl
  25179. * @function
  25180. * @param {Light} light -The light source.
  25181. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  25182. */
  25183. function lightShadowMatrix( light ) {
  25184. const data = getLightData( light );
  25185. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  25186. if ( light.castShadow !== true ) {
  25187. light.shadow.updateMatrices( light );
  25188. }
  25189. return light.shadow.matrix;
  25190. } ) );
  25191. }
  25192. /**
  25193. * TSL function for getting projected uv coordinates for the given light.
  25194. * Relevant when using maps with spot lights.
  25195. *
  25196. * @tsl
  25197. * @function
  25198. * @param {Light} light -The light source.
  25199. * @returns {Node<vec3>} The projected uvs.
  25200. */
  25201. function lightProjectionUV( light ) {
  25202. const data = getLightData( light );
  25203. if ( data.projectionUV === undefined ) {
  25204. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  25205. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  25206. }
  25207. return data.projectionUV;
  25208. }
  25209. /**
  25210. * TSL function for getting the position in world space for the given light.
  25211. *
  25212. * @tsl
  25213. * @function
  25214. * @param {Light} light -The light source.
  25215. * @returns {UniformNode<vec3>} The light's position in world space.
  25216. */
  25217. function lightPosition( light ) {
  25218. const data = getLightData( light );
  25219. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  25220. }
  25221. /**
  25222. * TSL function for getting the light target position in world space for the given light.
  25223. *
  25224. * @tsl
  25225. * @function
  25226. * @param {Light} light -The light source.
  25227. * @returns {UniformNode<vec3>} The light target position in world space.
  25228. */
  25229. function lightTargetPosition( light ) {
  25230. const data = getLightData( light );
  25231. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  25232. }
  25233. /**
  25234. * TSL function for getting the position in view space for the given light.
  25235. *
  25236. * @tsl
  25237. * @function
  25238. * @param {Light} light -The light source.
  25239. * @returns {UniformNode<vec3>} The light's position in view space.
  25240. */
  25241. function lightViewPosition( light ) {
  25242. const data = getLightData( light );
  25243. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  25244. self.value = self.value || new Vector3();
  25245. self.value.setFromMatrixPosition( light.matrixWorld );
  25246. self.value.applyMatrix4( camera.matrixWorldInverse );
  25247. } ) );
  25248. }
  25249. /**
  25250. * TSL function for getting the light target direction for the given light.
  25251. *
  25252. * @tsl
  25253. * @function
  25254. * @param {Light} light -The light source.
  25255. * @returns {Node<vec3>} The light's target direction.
  25256. */
  25257. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  25258. const sortLights = ( lights ) => {
  25259. return lights.sort( ( a, b ) => a.id - b.id );
  25260. };
  25261. const getLightNodeById = ( id, lightNodes ) => {
  25262. for ( const lightNode of lightNodes ) {
  25263. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  25264. return lightNode;
  25265. }
  25266. }
  25267. return null;
  25268. };
  25269. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  25270. /**
  25271. * This node represents the scene's lighting and manages the lighting model's life cycle
  25272. * for the current build 3D object. It is responsible for computing the total outgoing
  25273. * light in a given lighting context.
  25274. *
  25275. * @augments Node
  25276. */
  25277. class LightsNode extends Node {
  25278. static get type() {
  25279. return 'LightsNode';
  25280. }
  25281. /**
  25282. * Constructs a new lights node.
  25283. */
  25284. constructor() {
  25285. super( 'vec3' );
  25286. /**
  25287. * A node representing the total diffuse light.
  25288. *
  25289. * @type {Node<vec3>}
  25290. */
  25291. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  25292. /**
  25293. * A node representing the total specular light.
  25294. *
  25295. * @type {Node<vec3>}
  25296. */
  25297. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  25298. /**
  25299. * A node representing the outgoing light.
  25300. *
  25301. * @type {Node<vec3>}
  25302. */
  25303. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  25304. /**
  25305. * An array representing the lights in the scene.
  25306. *
  25307. * @private
  25308. * @type {Array<Light>}
  25309. */
  25310. this._lights = [];
  25311. /**
  25312. * For each light in the scene, this node will create a
  25313. * corresponding light node.
  25314. *
  25315. * @private
  25316. * @type {?Array<LightingNode>}
  25317. * @default null
  25318. */
  25319. this._lightNodes = null;
  25320. /**
  25321. * A hash for identifying the current light nodes setup.
  25322. *
  25323. * @private
  25324. * @type {?string}
  25325. * @default null
  25326. */
  25327. this._lightNodesHash = null;
  25328. /**
  25329. * `LightsNode` sets this property to `true` by default.
  25330. *
  25331. * @type {boolean}
  25332. * @default true
  25333. */
  25334. this.global = true;
  25335. }
  25336. /**
  25337. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25338. * light IDs into the cache key.
  25339. *
  25340. * @return {number} The custom cache key.
  25341. */
  25342. customCacheKey() {
  25343. const lightIDs = [];
  25344. const lights = this._lights;
  25345. for ( let i = 0; i < lights.length; i ++ ) {
  25346. lightIDs.push( lights[ i ].id );
  25347. }
  25348. return hashArray( lightIDs );
  25349. }
  25350. /**
  25351. * Computes a hash value for identifying the current light nodes setup.
  25352. *
  25353. * @param {NodeBuilder} builder - A reference to the current node builder.
  25354. * @return {string} The computed hash.
  25355. */
  25356. getHash( builder ) {
  25357. if ( this._lightNodesHash === null ) {
  25358. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25359. const hash = [];
  25360. for ( const lightNode of this._lightNodes ) {
  25361. hash.push( lightNode.getSelf().getHash() );
  25362. }
  25363. this._lightNodesHash = 'lights-' + hash.join( ',' );
  25364. }
  25365. return this._lightNodesHash;
  25366. }
  25367. analyze( builder ) {
  25368. const properties = builder.getDataFromNode( this );
  25369. for ( const node of properties.nodes ) {
  25370. node.build( builder );
  25371. }
  25372. }
  25373. /**
  25374. * Creates lighting nodes for each scene light. This makes it possible to further
  25375. * process lights in the node system.
  25376. *
  25377. * @param {NodeBuilder} builder - A reference to the current node builder.
  25378. */
  25379. setupLightsNode( builder ) {
  25380. const lightNodes = [];
  25381. const previousLightNodes = this._lightNodes;
  25382. const lights = sortLights( this._lights );
  25383. const nodeLibrary = builder.renderer.library;
  25384. for ( const light of lights ) {
  25385. if ( light.isNode ) {
  25386. lightNodes.push( nodeObject( light ) );
  25387. } else {
  25388. let lightNode = null;
  25389. if ( previousLightNodes !== null ) {
  25390. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  25391. }
  25392. if ( lightNode === null ) {
  25393. // find the corresponding node type for a given light
  25394. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  25395. if ( lightNodeClass === null ) {
  25396. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  25397. continue;
  25398. }
  25399. let lightNode = null;
  25400. if ( ! _lightsNodeRef.has( light ) ) {
  25401. lightNode = nodeObject( new lightNodeClass( light ) );
  25402. _lightsNodeRef.set( light, lightNode );
  25403. } else {
  25404. lightNode = _lightsNodeRef.get( light );
  25405. }
  25406. lightNodes.push( lightNode );
  25407. }
  25408. }
  25409. }
  25410. this._lightNodes = lightNodes;
  25411. }
  25412. /**
  25413. * Setups the internal lights by building all respective
  25414. * light nodes.
  25415. *
  25416. * @param {NodeBuilder} builder - A reference to the current node builder.
  25417. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  25418. */
  25419. setupLights( builder, lightNodes ) {
  25420. for ( const lightNode of lightNodes ) {
  25421. lightNode.build( builder );
  25422. }
  25423. }
  25424. /**
  25425. * The implementation makes sure that for each light in the scene
  25426. * there is a corresponding light node. By building the light nodes
  25427. * and evaluating the lighting model the outgoing light is computed.
  25428. *
  25429. * @param {NodeBuilder} builder - A reference to the current node builder.
  25430. * @return {Node<vec3>} A node representing the outgoing light.
  25431. */
  25432. setup( builder ) {
  25433. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25434. const context = builder.context;
  25435. const lightingModel = context.lightingModel;
  25436. let outgoingLightNode = this.outgoingLightNode;
  25437. if ( lightingModel ) {
  25438. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  25439. context.outgoingLight = outgoingLightNode;
  25440. const stack = builder.addStack();
  25441. //
  25442. const properties = builder.getDataFromNode( this );
  25443. properties.nodes = stack.nodes;
  25444. //
  25445. lightingModel.start( context, stack, builder );
  25446. // lights
  25447. this.setupLights( builder, _lightNodes );
  25448. //
  25449. lightingModel.indirect( context, stack, builder );
  25450. //
  25451. const { backdrop, backdropAlpha } = context;
  25452. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  25453. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  25454. if ( backdrop !== null ) {
  25455. if ( backdropAlpha !== null ) {
  25456. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  25457. } else {
  25458. totalDiffuse = vec3( backdrop );
  25459. }
  25460. context.material.transparent = true;
  25461. }
  25462. totalDiffuseNode.assign( totalDiffuse );
  25463. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  25464. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  25465. //
  25466. lightingModel.finish( context, stack, builder );
  25467. //
  25468. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  25469. }
  25470. return outgoingLightNode;
  25471. }
  25472. /**
  25473. * Configures this node with an array of lights.
  25474. *
  25475. * @param {Array<Light>} lights - An array of lights.
  25476. * @return {LightsNode} A reference to this node.
  25477. */
  25478. setLights( lights ) {
  25479. this._lights = lights;
  25480. this._lightNodes = null;
  25481. this._lightNodesHash = null;
  25482. return this;
  25483. }
  25484. /**
  25485. * Returns an array of the scene's lights.
  25486. *
  25487. * @return {Array<Light>} The scene's lights.
  25488. */
  25489. getLights() {
  25490. return this._lights;
  25491. }
  25492. /**
  25493. * Whether the scene has lights or not.
  25494. *
  25495. * @type {boolean}
  25496. */
  25497. get hasLights() {
  25498. return this._lights.length > 0;
  25499. }
  25500. }
  25501. /**
  25502. * TSL function for creating an instance of `LightsNode` and configuring
  25503. * it with the given array of lights.
  25504. *
  25505. * @tsl
  25506. * @function
  25507. * @param {Array<Light>} lights - An array of lights.
  25508. * @return {LightsNode} The created lights node.
  25509. */
  25510. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  25511. /**
  25512. * Base class for all shadow nodes.
  25513. *
  25514. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  25515. * Lighting nodes might share the same shadow node type or use specific ones depending on
  25516. * their requirements.
  25517. *
  25518. * @augments Node
  25519. */
  25520. class ShadowBaseNode extends Node {
  25521. static get type() {
  25522. return 'ShadowBaseNode';
  25523. }
  25524. /**
  25525. * Constructs a new shadow base node.
  25526. *
  25527. * @param {Light} light - The shadow casting light.
  25528. */
  25529. constructor( light ) {
  25530. super();
  25531. /**
  25532. * The shadow casting light.
  25533. *
  25534. * @type {Light}
  25535. */
  25536. this.light = light;
  25537. /**
  25538. * Overwritten since shadows are updated by default per render.
  25539. *
  25540. * @type {string}
  25541. * @default 'render'
  25542. */
  25543. this.updateBeforeType = NodeUpdateType.RENDER;
  25544. /**
  25545. * This flag can be used for type testing.
  25546. *
  25547. * @type {boolean}
  25548. * @readonly
  25549. * @default true
  25550. */
  25551. this.isShadowBaseNode = true;
  25552. }
  25553. /**
  25554. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  25555. *
  25556. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  25557. */
  25558. setupShadowPosition( { material } ) {
  25559. // Use assign inside an Fn()
  25560. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  25561. }
  25562. /**
  25563. * Can be called when the shadow isn't required anymore. That can happen when
  25564. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  25565. * to `false`.
  25566. */
  25567. dispose() {
  25568. this.updateBeforeType = NodeUpdateType.NONE;
  25569. }
  25570. }
  25571. /**
  25572. * TSL object that represents the vertex position in world space during the shadow pass.
  25573. *
  25574. * @tsl
  25575. * @type {Node<vec3>}
  25576. */
  25577. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  25578. /**
  25579. * Saves the state of the given renderer and stores it into the given state object.
  25580. *
  25581. * If not state object is provided, the function creates one.
  25582. *
  25583. * @function
  25584. * @param {Renderer} renderer - The renderer.
  25585. * @param {Object} [state={}] - The state.
  25586. * @return {Object} The state.
  25587. */
  25588. function saveRendererState( renderer, state = {} ) {
  25589. state.toneMapping = renderer.toneMapping;
  25590. state.toneMappingExposure = renderer.toneMappingExposure;
  25591. state.outputColorSpace = renderer.outputColorSpace;
  25592. state.renderTarget = renderer.getRenderTarget();
  25593. state.activeCubeFace = renderer.getActiveCubeFace();
  25594. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  25595. state.renderObjectFunction = renderer.getRenderObjectFunction();
  25596. state.pixelRatio = renderer.getPixelRatio();
  25597. state.mrt = renderer.getMRT();
  25598. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25599. state.clearAlpha = renderer.getClearAlpha();
  25600. state.autoClear = renderer.autoClear;
  25601. state.scissorTest = renderer.getScissorTest();
  25602. return state;
  25603. }
  25604. /**
  25605. * Saves the state of the given renderer and stores it into the given state object.
  25606. * Besides, the function also resets the state of the renderer to its default values.
  25607. *
  25608. * If not state object is provided, the function creates one.
  25609. *
  25610. * @function
  25611. * @param {Renderer} renderer - The renderer.
  25612. * @param {Object} [state={}] - The state.
  25613. * @return {Object} The state.
  25614. */
  25615. function resetRendererState( renderer, state ) {
  25616. state = saveRendererState( renderer, state );
  25617. renderer.setMRT( null );
  25618. renderer.setRenderObjectFunction( null );
  25619. renderer.setClearColor( 0x000000, 1 );
  25620. renderer.autoClear = true;
  25621. return state;
  25622. }
  25623. /**
  25624. * Restores the state of the given renderer from the given state object.
  25625. *
  25626. * @function
  25627. * @param {Renderer} renderer - The renderer.
  25628. * @param {Object} state - The state to restore.
  25629. */
  25630. function restoreRendererState( renderer, state ) {
  25631. renderer.toneMapping = state.toneMapping;
  25632. renderer.toneMappingExposure = state.toneMappingExposure;
  25633. renderer.outputColorSpace = state.outputColorSpace;
  25634. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25635. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25636. renderer.setPixelRatio( state.pixelRatio );
  25637. renderer.setMRT( state.mrt );
  25638. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25639. renderer.autoClear = state.autoClear;
  25640. renderer.setScissorTest( state.scissorTest );
  25641. }
  25642. /**
  25643. * Saves the state of the given scene and stores it into the given state object.
  25644. *
  25645. * If not state object is provided, the function creates one.
  25646. *
  25647. * @function
  25648. * @param {Scene} scene - The scene.
  25649. * @param {Object} [state={}] - The state.
  25650. * @return {Object} The state.
  25651. */
  25652. function saveSceneState( scene, state = {} ) {
  25653. state.background = scene.background;
  25654. state.backgroundNode = scene.backgroundNode;
  25655. state.overrideMaterial = scene.overrideMaterial;
  25656. return state;
  25657. }
  25658. /**
  25659. * Saves the state of the given scene and stores it into the given state object.
  25660. * Besides, the function also resets the state of the scene to its default values.
  25661. *
  25662. * If not state object is provided, the function creates one.
  25663. *
  25664. * @function
  25665. * @param {Scene} scene - The scene.
  25666. * @param {Object} [state={}] - The state.
  25667. * @return {Object} The state.
  25668. */
  25669. function resetSceneState( scene, state ) {
  25670. state = saveSceneState( scene, state );
  25671. scene.background = null;
  25672. scene.backgroundNode = null;
  25673. scene.overrideMaterial = null;
  25674. return state;
  25675. }
  25676. /**
  25677. * Restores the state of the given scene from the given state object.
  25678. *
  25679. * @function
  25680. * @param {Scene} scene - The scene.
  25681. * @param {Object} state - The state to restore.
  25682. */
  25683. function restoreSceneState( scene, state ) {
  25684. scene.background = state.background;
  25685. scene.backgroundNode = state.backgroundNode;
  25686. scene.overrideMaterial = state.overrideMaterial;
  25687. }
  25688. /**
  25689. * Saves the state of the given renderer and scene and stores it into the given state object.
  25690. *
  25691. * If not state object is provided, the function creates one.
  25692. *
  25693. * @function
  25694. * @param {Renderer} renderer - The renderer.
  25695. * @param {Scene} scene - The scene.
  25696. * @param {Object} [state={}] - The state.
  25697. * @return {Object} The state.
  25698. */
  25699. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25700. state = saveRendererState( renderer, state );
  25701. state = saveSceneState( scene, state );
  25702. return state;
  25703. }
  25704. /**
  25705. * Saves the state of the given renderer and scene and stores it into the given state object.
  25706. * Besides, the function also resets the state of the renderer and scene to its default values.
  25707. *
  25708. * If not state object is provided, the function creates one.
  25709. *
  25710. * @function
  25711. * @param {Renderer} renderer - The renderer.
  25712. * @param {Scene} scene - The scene.
  25713. * @param {Object} [state={}] - The state.
  25714. * @return {Object} The state.
  25715. */
  25716. function resetRendererAndSceneState( renderer, scene, state ) {
  25717. state = resetRendererState( renderer, state );
  25718. state = resetSceneState( scene, state );
  25719. return state;
  25720. }
  25721. /**
  25722. * Restores the state of the given renderer and scene from the given state object.
  25723. *
  25724. * @function
  25725. * @param {Renderer} renderer - The renderer.
  25726. * @param {Scene} scene - The scene.
  25727. * @param {Object} state - The state to restore.
  25728. */
  25729. function restoreRendererAndSceneState( renderer, scene, state ) {
  25730. restoreRendererState( renderer, state );
  25731. restoreSceneState( scene, state );
  25732. }
  25733. var RendererUtils = /*#__PURE__*/Object.freeze({
  25734. __proto__: null,
  25735. resetRendererAndSceneState: resetRendererAndSceneState,
  25736. resetRendererState: resetRendererState,
  25737. resetSceneState: resetSceneState,
  25738. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25739. restoreRendererState: restoreRendererState,
  25740. restoreSceneState: restoreSceneState,
  25741. saveRendererAndSceneState: saveRendererAndSceneState,
  25742. saveRendererState: saveRendererState,
  25743. saveSceneState: saveSceneState
  25744. });
  25745. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25746. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25747. let dist = positionWorld.sub( position ).length();
  25748. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25749. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25750. return dist;
  25751. } );
  25752. const linearShadowDistance = ( light ) => {
  25753. const camera = light.shadow.camera;
  25754. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25755. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25756. const referencePosition = objectPosition( light );
  25757. return linearDistance( referencePosition, nearDistance, farDistance );
  25758. };
  25759. const getShadowMaterial = ( light ) => {
  25760. let material = shadowMaterialLib.get( light );
  25761. if ( material === undefined ) {
  25762. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25763. material = new NodeMaterial();
  25764. material.colorNode = vec4( 0, 0, 0, 1 );
  25765. material.depthNode = depthNode;
  25766. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25767. material.name = 'ShadowMaterial';
  25768. material.fog = false;
  25769. shadowMaterialLib.set( light, material );
  25770. }
  25771. return material;
  25772. };
  25773. /**
  25774. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25775. * with a binary `[0,1]` result.
  25776. *
  25777. * @method
  25778. * @param {Object} inputs - The input parameter object.
  25779. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25780. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25781. * @return {Node<float>} The filtering result.
  25782. */
  25783. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25784. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25785. } );
  25786. /**
  25787. * A shadow filtering function performing PCF filtering.
  25788. *
  25789. * @method
  25790. * @param {Object} inputs - The input parameter object.
  25791. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25792. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25793. * @param {LightShadow} inputs.shadow - The light shadow.
  25794. * @return {Node<float>} The filtering result.
  25795. */
  25796. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25797. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25798. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25799. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25800. const texelSize = vec2( 1 ).div( mapSize );
  25801. const dx0 = texelSize.x.negate().mul( radius );
  25802. const dy0 = texelSize.y.negate().mul( radius );
  25803. const dx1 = texelSize.x.mul( radius );
  25804. const dy1 = texelSize.y.mul( radius );
  25805. const dx2 = dx0.div( 2 );
  25806. const dy2 = dy0.div( 2 );
  25807. const dx3 = dx1.div( 2 );
  25808. const dy3 = dy1.div( 2 );
  25809. return add(
  25810. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25811. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25812. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25813. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25814. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25815. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25816. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25817. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25818. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25819. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25820. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25821. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25822. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25823. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25824. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25825. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25826. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25827. ).mul( 1 / 17 );
  25828. } );
  25829. /**
  25830. * A shadow filtering function performing PCF soft filtering.
  25831. *
  25832. * @method
  25833. * @param {Object} inputs - The input parameter object.
  25834. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25835. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25836. * @param {LightShadow} inputs.shadow - The light shadow.
  25837. * @return {Node<float>} The filtering result.
  25838. */
  25839. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25840. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25841. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25842. const texelSize = vec2( 1 ).div( mapSize );
  25843. const dx = texelSize.x;
  25844. const dy = texelSize.y;
  25845. const uv = shadowCoord.xy;
  25846. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25847. uv.subAssign( f.mul( texelSize ) );
  25848. return add(
  25849. depthCompare( uv, shadowCoord.z ),
  25850. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25851. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25852. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25853. mix(
  25854. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25855. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25856. f.x
  25857. ),
  25858. mix(
  25859. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25860. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25861. f.x
  25862. ),
  25863. mix(
  25864. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25865. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25866. f.y
  25867. ),
  25868. mix(
  25869. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25870. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25871. f.y
  25872. ),
  25873. mix(
  25874. mix(
  25875. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25876. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25877. f.x
  25878. ),
  25879. mix(
  25880. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25881. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25882. f.x
  25883. ),
  25884. f.y
  25885. )
  25886. ).mul( 1 / 9 );
  25887. } );
  25888. /**
  25889. * A shadow filtering function performing VSM filtering.
  25890. *
  25891. * @method
  25892. * @param {Object} inputs - The input parameter object.
  25893. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25894. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25895. * @return {Node<float>} The filtering result.
  25896. */
  25897. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25898. const occlusion = float( 1 ).toVar();
  25899. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25900. const hardShadow = step( shadowCoord.z, distribution.x );
  25901. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25902. const distance = shadowCoord.z.sub( distribution.x );
  25903. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25904. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25905. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25906. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25907. } );
  25908. return occlusion;
  25909. } );
  25910. /**
  25911. * Represents the shader code for the first VSM render pass.
  25912. *
  25913. * @method
  25914. * @param {Object} inputs - The input parameter object.
  25915. * @param {Node<float>} inputs.samples - The number of samples
  25916. * @param {Node<float>} inputs.radius - The radius.
  25917. * @param {Node<float>} inputs.size - The size.
  25918. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25919. * @return {Node<vec2>} The VSM output.
  25920. */
  25921. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25922. const mean = float( 0 ).toVar();
  25923. const squaredMean = float( 0 ).toVar();
  25924. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25925. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25926. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25927. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25928. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25929. mean.addAssign( depth );
  25930. squaredMean.addAssign( depth.mul( depth ) );
  25931. } );
  25932. mean.divAssign( samples );
  25933. squaredMean.divAssign( samples );
  25934. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25935. return vec2( mean, std_dev );
  25936. } );
  25937. /**
  25938. * Represents the shader code for the second VSM render pass.
  25939. *
  25940. * @method
  25941. * @param {Object} inputs - The input parameter object.
  25942. * @param {Node<float>} inputs.samples - The number of samples
  25943. * @param {Node<float>} inputs.radius - The radius.
  25944. * @param {Node<float>} inputs.size - The size.
  25945. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25946. * @return {Node<vec2>} The VSM output.
  25947. */
  25948. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25949. const mean = float( 0 ).toVar();
  25950. const squaredMean = float( 0 ).toVar();
  25951. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25952. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25953. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25954. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25955. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25956. mean.addAssign( distribution.x );
  25957. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25958. } );
  25959. mean.divAssign( samples );
  25960. squaredMean.divAssign( samples );
  25961. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25962. return vec2( mean, std_dev );
  25963. } );
  25964. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25965. //
  25966. let _rendererState;
  25967. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25968. /**
  25969. * Represents the default shadow implementation for lighting nodes.
  25970. *
  25971. * @augments ShadowBaseNode
  25972. */
  25973. class ShadowNode extends ShadowBaseNode {
  25974. static get type() {
  25975. return 'ShadowNode';
  25976. }
  25977. /**
  25978. * Constructs a new shadow node.
  25979. *
  25980. * @param {Light} light - The shadow casting light.
  25981. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  25982. */
  25983. constructor( light, shadow = null ) {
  25984. super( light );
  25985. /**
  25986. * The light shadow which defines the properties light's
  25987. * shadow.
  25988. *
  25989. * @type {?LightShadow}
  25990. * @default null
  25991. */
  25992. this.shadow = shadow || light.shadow;
  25993. /**
  25994. * A reference to the shadow map which is a render target.
  25995. *
  25996. * @type {?RenderTarget}
  25997. * @default null
  25998. */
  25999. this.shadowMap = null;
  26000. /**
  26001. * Only relevant for VSM shadows. Render target for the
  26002. * first VSM render pass.
  26003. *
  26004. * @type {?RenderTarget}
  26005. * @default null
  26006. */
  26007. this.vsmShadowMapVertical = null;
  26008. /**
  26009. * Only relevant for VSM shadows. Render target for the
  26010. * second VSM render pass.
  26011. *
  26012. * @type {?RenderTarget}
  26013. * @default null
  26014. */
  26015. this.vsmShadowMapHorizontal = null;
  26016. /**
  26017. * Only relevant for VSM shadows. Node material which
  26018. * is used to render the first VSM pass.
  26019. *
  26020. * @type {?NodeMaterial}
  26021. * @default null
  26022. */
  26023. this.vsmMaterialVertical = null;
  26024. /**
  26025. * Only relevant for VSM shadows. Node material which
  26026. * is used to render the second VSM pass.
  26027. *
  26028. * @type {?NodeMaterial}
  26029. * @default null
  26030. */
  26031. this.vsmMaterialHorizontal = null;
  26032. /**
  26033. * A reference to the output node which defines the
  26034. * final result of this shadow node.
  26035. *
  26036. * @type {?Node}
  26037. * @private
  26038. * @default null
  26039. */
  26040. this._node = null;
  26041. /**
  26042. * This flag can be used for type testing.
  26043. *
  26044. * @type {boolean}
  26045. * @readonly
  26046. * @default true
  26047. */
  26048. this.isShadowNode = true;
  26049. }
  26050. /**
  26051. * Setups the shadow filtering.
  26052. *
  26053. * @param {NodeBuilder} builder - A reference to the current node builder.
  26054. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26055. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26056. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26057. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26058. * @param {LightShadow} inputs.shadow - The light shadow.
  26059. * @return {Node<float>} The result node of the shadow filtering.
  26060. */
  26061. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  26062. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  26063. .and( shadowCoord.x.lessThanEqual( 1 ) )
  26064. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  26065. .and( shadowCoord.y.lessThanEqual( 1 ) )
  26066. .and( shadowCoord.z.lessThanEqual( 1 ) );
  26067. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  26068. return frustumTest.select( shadowNode, float( 1 ) );
  26069. }
  26070. /**
  26071. * Setups the shadow coordinates.
  26072. *
  26073. * @param {NodeBuilder} builder - A reference to the current node builder.
  26074. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26075. * @return {Node<vec3>} The shadow coordinates.
  26076. */
  26077. setupShadowCoord( builder, shadowPosition ) {
  26078. const { shadow } = this;
  26079. const { renderer } = builder;
  26080. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  26081. let shadowCoord = shadowPosition;
  26082. let coordZ;
  26083. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  26084. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  26085. coordZ = shadowCoord.z;
  26086. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26087. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  26088. }
  26089. } else {
  26090. const w = shadowCoord.w;
  26091. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  26092. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  26093. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  26094. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  26095. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  26096. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  26097. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  26098. }
  26099. shadowCoord = vec3(
  26100. shadowCoord.x,
  26101. shadowCoord.y.oneMinus(), // follow webgpu standards
  26102. coordZ.add( bias )
  26103. );
  26104. return shadowCoord;
  26105. }
  26106. /**
  26107. * Returns the shadow filtering function for the given shadow type.
  26108. *
  26109. * @param {number} type - The shadow type.
  26110. * @return {Function} The filtering function.
  26111. */
  26112. getShadowFilterFn( type ) {
  26113. return _shadowFilterLib[ type ];
  26114. }
  26115. /**
  26116. * Setups the shadow output node.
  26117. *
  26118. * @param {NodeBuilder} builder - A reference to the current node builder.
  26119. * @return {Node<vec3>} The shadow output node.
  26120. */
  26121. setupShadow( builder ) {
  26122. const { renderer } = builder;
  26123. const { light, shadow } = this;
  26124. const shadowMapType = renderer.shadowMap.type;
  26125. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  26126. depthTexture.compareFunction = LessCompare;
  26127. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  26128. shadowMap.depthTexture = depthTexture;
  26129. shadow.camera.updateProjectionMatrix();
  26130. // VSM
  26131. if ( shadowMapType === VSMShadowMap ) {
  26132. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  26133. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  26134. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  26135. const shadowPassVertical = texture( depthTexture );
  26136. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  26137. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  26138. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  26139. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  26140. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  26141. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  26142. material.name = 'VSMVertical';
  26143. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  26144. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  26145. material.name = 'VSMHorizontal';
  26146. }
  26147. //
  26148. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  26149. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  26150. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  26151. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  26152. //
  26153. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  26154. if ( filterFn === null ) {
  26155. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  26156. }
  26157. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  26158. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  26159. const shadowColor = texture( shadowMap.texture, shadowCoord );
  26160. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  26161. this.shadowMap = shadowMap;
  26162. this.shadow.map = shadowMap;
  26163. return shadowOutput;
  26164. }
  26165. /**
  26166. * The implementation performs the setup of the output node. An output is only
  26167. * produces if shadow mapping is globally enabled in the renderer.
  26168. *
  26169. * @param {NodeBuilder} builder - A reference to the current node builder.
  26170. * @return {ShaderCallNodeInternal} The output node.
  26171. */
  26172. setup( builder ) {
  26173. if ( builder.renderer.shadowMap.enabled === false ) return;
  26174. return Fn( () => {
  26175. let node = this._node;
  26176. this.setupShadowPosition( builder );
  26177. if ( node === null ) {
  26178. this._node = node = this.setupShadow( builder );
  26179. }
  26180. if ( builder.material.shadowNode ) { // @deprecated, r171
  26181. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  26182. }
  26183. if ( builder.material.receivedShadowNode ) {
  26184. node = builder.material.receivedShadowNode( node );
  26185. }
  26186. return node;
  26187. } )();
  26188. }
  26189. /**
  26190. * Renders the shadow. The logic of this function could be included
  26191. * into {@link ShadowNode#updateShadow} however more specialized shadow
  26192. * nodes might require a custom shadow map rendering. By having a
  26193. * dedicated method, it's easier to overwrite the default behavior.
  26194. *
  26195. * @param {NodeFrame} frame - A reference to the current node frame.
  26196. */
  26197. renderShadow( frame ) {
  26198. const { shadow, shadowMap, light } = this;
  26199. const { renderer, scene } = frame;
  26200. shadow.updateMatrices( light );
  26201. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  26202. renderer.render( scene, shadow.camera );
  26203. }
  26204. /**
  26205. * Updates the shadow.
  26206. *
  26207. * @param {NodeFrame} frame - A reference to the current node frame.
  26208. */
  26209. updateShadow( frame ) {
  26210. const { shadowMap, light, shadow } = this;
  26211. const { renderer, scene, camera } = frame;
  26212. const shadowType = renderer.shadowMap.type;
  26213. const depthVersion = shadowMap.depthTexture.version;
  26214. this._depthVersionCached = depthVersion;
  26215. shadow.camera.layers.mask = camera.layers.mask;
  26216. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26217. const currentMRT = renderer.getMRT();
  26218. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  26219. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  26220. scene.overrideMaterial = getShadowMaterial( light );
  26221. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  26222. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  26223. if ( useVelocity ) {
  26224. getDataFromObject( object ).useVelocity = true;
  26225. }
  26226. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  26227. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  26228. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  26229. }
  26230. } );
  26231. renderer.setRenderTarget( shadowMap );
  26232. this.renderShadow( frame );
  26233. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26234. // vsm blur pass
  26235. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  26236. this.vsmPass( renderer );
  26237. }
  26238. restoreRendererAndSceneState( renderer, scene, _rendererState );
  26239. }
  26240. /**
  26241. * For VSM additional render passes are required.
  26242. *
  26243. * @param {Renderer} renderer - A reference to the current renderer.
  26244. */
  26245. vsmPass( renderer ) {
  26246. const { shadow } = this;
  26247. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  26248. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  26249. renderer.setRenderTarget( this.vsmShadowMapVertical );
  26250. _quadMesh.material = this.vsmMaterialVertical;
  26251. _quadMesh.render( renderer );
  26252. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  26253. _quadMesh.material = this.vsmMaterialHorizontal;
  26254. _quadMesh.render( renderer );
  26255. }
  26256. /**
  26257. * Frees the internal resources of this shadow node.
  26258. */
  26259. dispose() {
  26260. this.shadowMap.dispose();
  26261. this.shadowMap = null;
  26262. if ( this.vsmShadowMapVertical !== null ) {
  26263. this.vsmShadowMapVertical.dispose();
  26264. this.vsmShadowMapVertical = null;
  26265. this.vsmMaterialVertical.dispose();
  26266. this.vsmMaterialVertical = null;
  26267. }
  26268. if ( this.vsmShadowMapHorizontal !== null ) {
  26269. this.vsmShadowMapHorizontal.dispose();
  26270. this.vsmShadowMapHorizontal = null;
  26271. this.vsmMaterialHorizontal.dispose();
  26272. this.vsmMaterialHorizontal = null;
  26273. }
  26274. super.dispose();
  26275. }
  26276. /**
  26277. * The implementation performs the update of the shadow map if necessary.
  26278. *
  26279. * @param {NodeFrame} frame - A reference to the current node frame.
  26280. */
  26281. updateBefore( frame ) {
  26282. const { shadow } = this;
  26283. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  26284. if ( needsUpdate ) {
  26285. this.updateShadow( frame );
  26286. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  26287. shadow.needsUpdate = false;
  26288. }
  26289. }
  26290. }
  26291. }
  26292. /**
  26293. * TSL function for creating an instance of `ShadowNode`.
  26294. *
  26295. * @tsl
  26296. * @function
  26297. * @param {Light} light - The shadow casting light.
  26298. * @param {LightShadow} shadow - The light shadow.
  26299. * @return {ShadowNode} The created shadow node.
  26300. */
  26301. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  26302. /**
  26303. * Base class for analytic light nodes.
  26304. *
  26305. * @augments LightingNode
  26306. */
  26307. class AnalyticLightNode extends LightingNode {
  26308. static get type() {
  26309. return 'AnalyticLightNode';
  26310. }
  26311. /**
  26312. * Constructs a new analytic light node.
  26313. *
  26314. * @param {?Light} [light=null] - The light source.
  26315. */
  26316. constructor( light = null ) {
  26317. super();
  26318. /**
  26319. * The light source.
  26320. *
  26321. * @type {?Light}
  26322. * @default null
  26323. */
  26324. this.light = light;
  26325. /**
  26326. * The light's color value.
  26327. *
  26328. * @type {Color}
  26329. */
  26330. this.color = new Color();
  26331. /**
  26332. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  26333. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  26334. *
  26335. * @type {Node}
  26336. */
  26337. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  26338. /**
  26339. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  26340. * The final color node is represented by a different node when using shadows.
  26341. *
  26342. * @type {?Node}
  26343. * @default null
  26344. */
  26345. this.baseColorNode = null;
  26346. /**
  26347. * Represents the light's shadow.
  26348. *
  26349. * @type {?ShadowNode}
  26350. * @default null
  26351. */
  26352. this.shadowNode = null;
  26353. /**
  26354. * Represents the light's shadow color.
  26355. *
  26356. * @type {?Node}
  26357. * @default null
  26358. */
  26359. this.shadowColorNode = null;
  26360. /**
  26361. * This flag can be used for type testing.
  26362. *
  26363. * @type {boolean}
  26364. * @readonly
  26365. * @default true
  26366. */
  26367. this.isAnalyticLightNode = true;
  26368. /**
  26369. * Overwritten since analytic light nodes are updated
  26370. * once per frame.
  26371. *
  26372. * @type {string}
  26373. * @default 'frame'
  26374. */
  26375. this.updateType = NodeUpdateType.FRAME;
  26376. }
  26377. /**
  26378. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  26379. * `light.id` and `light.castShadow` into the cache key.
  26380. *
  26381. * @return {number} The custom cache key.
  26382. */
  26383. customCacheKey() {
  26384. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  26385. }
  26386. getHash() {
  26387. return this.light.uuid;
  26388. }
  26389. /**
  26390. * Setups the shadow node for this light. The method exists so concrete light classes
  26391. * can setup different types of shadow nodes.
  26392. *
  26393. * @return {ShadowNode} The created shadow node.
  26394. */
  26395. setupShadowNode() {
  26396. return shadow( this.light );
  26397. }
  26398. /**
  26399. * Setups the shadow for this light. This method is only executed if the light
  26400. * cast shadows and the current build object receives shadows. It incorporates
  26401. * shadows into the lighting computation.
  26402. *
  26403. * @param {NodeBuilder} builder - The current node builder.
  26404. */
  26405. setupShadow( builder ) {
  26406. const { renderer } = builder;
  26407. if ( renderer.shadowMap.enabled === false ) return;
  26408. let shadowColorNode = this.shadowColorNode;
  26409. if ( shadowColorNode === null ) {
  26410. const customShadowNode = this.light.shadow.shadowNode;
  26411. let shadowNode;
  26412. if ( customShadowNode !== undefined ) {
  26413. shadowNode = nodeObject( customShadowNode );
  26414. } else {
  26415. shadowNode = this.setupShadowNode( builder );
  26416. }
  26417. this.shadowNode = shadowNode;
  26418. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  26419. this.baseColorNode = this.colorNode;
  26420. }
  26421. //
  26422. this.colorNode = shadowColorNode;
  26423. }
  26424. /**
  26425. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  26426. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  26427. * invocate the respective interface methods.
  26428. *
  26429. * @param {NodeBuilder} builder - The current node builder.
  26430. */
  26431. setup( builder ) {
  26432. this.colorNode = this.baseColorNode || this.colorNode;
  26433. if ( this.light.castShadow ) {
  26434. if ( builder.object.receiveShadow ) {
  26435. this.setupShadow( builder );
  26436. }
  26437. } else if ( this.shadowNode !== null ) {
  26438. this.shadowNode.dispose();
  26439. this.shadowNode = null;
  26440. this.shadowColorNode = null;
  26441. }
  26442. }
  26443. /**
  26444. * The update method is used to update light uniforms per frame.
  26445. * Potentially overwritten in concrete light nodes to update light
  26446. * specific uniforms.
  26447. *
  26448. * @param {NodeFrame} frame - A reference to the current node frame.
  26449. */
  26450. update( /*frame*/ ) {
  26451. const { light } = this;
  26452. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26453. }
  26454. }
  26455. /**
  26456. * Represents a `discard` shader operation in TSL.
  26457. *
  26458. * @method
  26459. * @param {Object} inputs - The input parameter object.
  26460. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  26461. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  26462. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  26463. * @return {Node<float>} The distance falloff.
  26464. */
  26465. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  26466. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  26467. // based upon Frostbite 3 Moving to Physically-based Rendering
  26468. // page 32, equation 26: E[window1]
  26469. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  26470. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  26471. return cutoffDistance.greaterThan( 0 ).select(
  26472. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  26473. distanceFalloff
  26474. );
  26475. } ); // validated
  26476. const _clearColor$2 = /*@__PURE__*/ new Color();
  26477. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  26478. // vector suitable for 2D texture mapping. This code uses the following layout for the
  26479. // 2D texture:
  26480. //
  26481. // xzXZ
  26482. // y Y
  26483. //
  26484. // Y - Positive y direction
  26485. // y - Negative y direction
  26486. // X - Positive x direction
  26487. // x - Negative x direction
  26488. // Z - Positive z direction
  26489. // z - Negative z direction
  26490. //
  26491. // Source and test bed:
  26492. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  26493. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  26494. const v = pos.toVar();
  26495. // Number of texels to avoid at the edge of each square
  26496. const absV = abs( v );
  26497. // Intersect unit cube
  26498. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  26499. absV.mulAssign( scaleToCube );
  26500. // Apply scale to avoid seams
  26501. // two texels less per square (one texel will do for NEAREST)
  26502. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  26503. // Unwrap
  26504. // space: -1 ... 1 range for each square
  26505. //
  26506. // #X## dim := ( 4 , 2 )
  26507. // # # center := ( 1 , 1 )
  26508. const planar = vec2( v.xy ).toVar();
  26509. const almostATexel = texelSizeY.mul( 1.5 );
  26510. const almostOne = almostATexel.oneMinus();
  26511. If( absV.z.greaterThanEqual( almostOne ), () => {
  26512. If( v.z.greaterThan( 0.0 ), () => {
  26513. planar.x.assign( sub( 4.0, v.x ) );
  26514. } );
  26515. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  26516. const signX = sign( v.x );
  26517. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  26518. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  26519. const signY = sign( v.y );
  26520. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  26521. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  26522. } );
  26523. // Transform to UV space
  26524. // scale := 0.5 / dim
  26525. // translate := ( center + 0.5 ) / dim
  26526. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  26527. } ).setLayout( {
  26528. name: 'cubeToUV',
  26529. type: 'vec2',
  26530. inputs: [
  26531. { name: 'pos', type: 'vec3' },
  26532. { name: 'texelSizeY', type: 'float' }
  26533. ]
  26534. } );
  26535. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  26536. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  26537. } );
  26538. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  26539. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  26540. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  26541. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  26542. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  26543. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  26544. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  26545. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  26546. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  26547. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  26548. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  26549. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  26550. .mul( 1.0 / 9.0 );
  26551. } );
  26552. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  26553. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  26554. // the vector from the light to the world-space position of the fragment.
  26555. const lightToPosition = shadowCoord.xyz.toVar();
  26556. const lightToPositionLength = lightToPosition.length();
  26557. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  26558. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  26559. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  26560. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  26561. const result = float( 1.0 ).toVar();
  26562. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  26563. // dp = normalized distance from light to fragment position
  26564. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  26565. dp.addAssign( bias );
  26566. // bd3D = base direction 3D
  26567. const bd3D = lightToPosition.normalize();
  26568. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  26569. // percentage-closer filtering
  26570. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  26571. } );
  26572. return result;
  26573. } );
  26574. const _viewport = /*@__PURE__*/ new Vector4();
  26575. const _viewportSize = /*@__PURE__*/ new Vector2();
  26576. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  26577. /**
  26578. * Represents the shadow implementation for point light nodes.
  26579. *
  26580. * @augments ShadowNode
  26581. */
  26582. class PointShadowNode extends ShadowNode {
  26583. static get type() {
  26584. return 'PointShadowNode';
  26585. }
  26586. /**
  26587. * Constructs a new point shadow node.
  26588. *
  26589. * @param {PointLight} light - The shadow casting point light.
  26590. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  26591. */
  26592. constructor( light, shadow = null ) {
  26593. super( light, shadow );
  26594. }
  26595. /**
  26596. * Overwrites the default implementation to return point light shadow specific
  26597. * filtering functions.
  26598. *
  26599. * @param {number} type - The shadow type.
  26600. * @return {Function} The filtering function.
  26601. */
  26602. getShadowFilterFn( type ) {
  26603. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  26604. }
  26605. /**
  26606. * Overwrites the default implementation so the unaltered shadow position is used.
  26607. *
  26608. * @param {NodeBuilder} builder - A reference to the current node builder.
  26609. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26610. * @return {Node<vec3>} The shadow coordinates.
  26611. */
  26612. setupShadowCoord( builder, shadowPosition ) {
  26613. return shadowPosition;
  26614. }
  26615. /**
  26616. * Overwrites the default implementation to only use point light specific
  26617. * shadow filter functions.
  26618. *
  26619. * @param {NodeBuilder} builder - A reference to the current node builder.
  26620. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26621. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26622. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  26623. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26624. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26625. * @param {LightShadow} inputs.shadow - The light shadow.
  26626. * @return {Node<float>} The result node of the shadow filtering.
  26627. */
  26628. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  26629. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  26630. }
  26631. /**
  26632. * Overwrites the default implementation with point light specific
  26633. * rendering code.
  26634. *
  26635. * @param {NodeFrame} frame - A reference to the current node frame.
  26636. */
  26637. renderShadow( frame ) {
  26638. const { shadow, shadowMap, light } = this;
  26639. const { renderer, scene } = frame;
  26640. const shadowFrameExtents = shadow.getFrameExtents();
  26641. _shadowMapSize.copy( shadow.mapSize );
  26642. _shadowMapSize.multiply( shadowFrameExtents );
  26643. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  26644. _viewportSize.copy( shadow.mapSize );
  26645. //
  26646. const previousAutoClear = renderer.autoClear;
  26647. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  26648. const previousClearAlpha = renderer.getClearAlpha();
  26649. renderer.autoClear = false;
  26650. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  26651. renderer.clear();
  26652. const viewportCount = shadow.getViewportCount();
  26653. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  26654. const viewport = shadow.getViewport( vp );
  26655. const x = _viewportSize.x * viewport.x;
  26656. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  26657. _viewport.set(
  26658. x,
  26659. y,
  26660. _viewportSize.x * viewport.z,
  26661. _viewportSize.y * viewport.w
  26662. );
  26663. shadowMap.viewport.copy( _viewport );
  26664. shadow.updateMatrices( light, vp );
  26665. renderer.render( scene, shadow.camera );
  26666. }
  26667. //
  26668. renderer.autoClear = previousAutoClear;
  26669. renderer.setClearColor( previousClearColor, previousClearAlpha );
  26670. }
  26671. }
  26672. /**
  26673. * TSL function for creating an instance of `PointShadowNode`.
  26674. *
  26675. * @tsl
  26676. * @function
  26677. * @param {PointLight} light - The shadow casting point light.
  26678. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  26679. * @return {PointShadowNode} The created point shadow node.
  26680. */
  26681. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  26682. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  26683. const lightingModel = builder.context.lightingModel;
  26684. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  26685. const lightDirection = lVector.normalize();
  26686. const lightDistance = lVector.length();
  26687. const lightAttenuation = getDistanceAttenuation( {
  26688. lightDistance,
  26689. cutoffDistance,
  26690. decayExponent
  26691. } );
  26692. const lightColor = color.mul( lightAttenuation );
  26693. const reflectedLight = builder.context.reflectedLight;
  26694. lightingModel.direct( {
  26695. lightDirection,
  26696. lightColor,
  26697. reflectedLight
  26698. }, builder.stack, builder );
  26699. } );
  26700. /**
  26701. * Module for representing point lights as nodes.
  26702. *
  26703. * @augments AnalyticLightNode
  26704. */
  26705. class PointLightNode extends AnalyticLightNode {
  26706. static get type() {
  26707. return 'PointLightNode';
  26708. }
  26709. /**
  26710. * Constructs a new point light node.
  26711. *
  26712. * @param {?PointLight} [light=null] - The point light source.
  26713. */
  26714. constructor( light = null ) {
  26715. super( light );
  26716. /**
  26717. * Uniform node representing the cutoff distance.
  26718. *
  26719. * @type {UniformNode<float>}
  26720. */
  26721. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26722. /**
  26723. * Uniform node representing the decay exponent.
  26724. *
  26725. * @type {UniformNode<float>}
  26726. */
  26727. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26728. }
  26729. /**
  26730. * Overwritten to updated point light specific uniforms.
  26731. *
  26732. * @param {NodeFrame} frame - A reference to the current node frame.
  26733. */
  26734. update( frame ) {
  26735. const { light } = this;
  26736. super.update( frame );
  26737. this.cutoffDistanceNode.value = light.distance;
  26738. this.decayExponentNode.value = light.decay;
  26739. }
  26740. /**
  26741. * Overwritten to setup point light specific shadow.
  26742. *
  26743. * @return {PointShadowNode}
  26744. */
  26745. setupShadowNode() {
  26746. return pointShadow( this.light );
  26747. }
  26748. setup( builder ) {
  26749. super.setup( builder );
  26750. directPointLight( {
  26751. color: this.colorNode,
  26752. lightViewPosition: lightViewPosition( this.light ),
  26753. cutoffDistance: this.cutoffDistanceNode,
  26754. decayExponent: this.decayExponentNode
  26755. } ).append();
  26756. }
  26757. }
  26758. /**
  26759. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26760. *
  26761. * @tsl
  26762. * @function
  26763. * @param {Node<vec2>} coord - The uv coordinates.
  26764. * @return {Node<float>} The result data.
  26765. */
  26766. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26767. const uv = coord.mul( 2.0 );
  26768. const cx = uv.x.floor();
  26769. const cy = uv.y.floor();
  26770. const result = cx.add( cy ).mod( 2.0 );
  26771. return result.sign();
  26772. } );
  26773. /**
  26774. * Generates a circle based on the uv coordinates.
  26775. *
  26776. * @tsl
  26777. * @function
  26778. * @param {Node<vec2>} coord - The uv to generate the circle.
  26779. * @return {Node<float>} The circle shape.
  26780. */
  26781. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26782. const alpha = float( 1 ).toVar();
  26783. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26784. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26785. const dlen = float( len2.fwidth() ).toVar();
  26786. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26787. } else {
  26788. len2.greaterThan( 1.0 ).discard();
  26789. }
  26790. return alpha;
  26791. } );
  26792. // Three.js Transpiler
  26793. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26794. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26795. const f = float( f_immutable ).toVar();
  26796. const t = float( t_immutable ).toVar();
  26797. const b = bool( b_immutable ).toVar();
  26798. return select( b, t, f );
  26799. } ).setLayout( {
  26800. name: 'mx_select',
  26801. type: 'float',
  26802. inputs: [
  26803. { name: 'b', type: 'bool' },
  26804. { name: 't', type: 'float' },
  26805. { name: 'f', type: 'float' }
  26806. ]
  26807. } );
  26808. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26809. const b = bool( b_immutable ).toVar();
  26810. const val = float( val_immutable ).toVar();
  26811. return select( b, val.negate(), val );
  26812. } ).setLayout( {
  26813. name: 'mx_negate_if',
  26814. type: 'float',
  26815. inputs: [
  26816. { name: 'val', type: 'float' },
  26817. { name: 'b', type: 'bool' }
  26818. ]
  26819. } );
  26820. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26821. const x = float( x_immutable ).toVar();
  26822. return int( floor( x ) );
  26823. } ).setLayout( {
  26824. name: 'mx_floor',
  26825. type: 'int',
  26826. inputs: [
  26827. { name: 'x', type: 'float' }
  26828. ]
  26829. } );
  26830. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26831. const x = float( x_immutable ).toVar();
  26832. i.assign( mx_floor( x ) );
  26833. return x.sub( float( i ) );
  26834. } );
  26835. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26836. const t = float( t_immutable ).toVar();
  26837. const s = float( s_immutable ).toVar();
  26838. const v3 = float( v3_immutable ).toVar();
  26839. const v2 = float( v2_immutable ).toVar();
  26840. const v1 = float( v1_immutable ).toVar();
  26841. const v0 = float( v0_immutable ).toVar();
  26842. const s1 = float( sub( 1.0, s ) ).toVar();
  26843. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26844. } ).setLayout( {
  26845. name: 'mx_bilerp_0',
  26846. type: 'float',
  26847. inputs: [
  26848. { name: 'v0', type: 'float' },
  26849. { name: 'v1', type: 'float' },
  26850. { name: 'v2', type: 'float' },
  26851. { name: 'v3', type: 'float' },
  26852. { name: 's', type: 'float' },
  26853. { name: 't', type: 'float' }
  26854. ]
  26855. } );
  26856. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26857. const t = float( t_immutable ).toVar();
  26858. const s = float( s_immutable ).toVar();
  26859. const v3 = vec3( v3_immutable ).toVar();
  26860. const v2 = vec3( v2_immutable ).toVar();
  26861. const v1 = vec3( v1_immutable ).toVar();
  26862. const v0 = vec3( v0_immutable ).toVar();
  26863. const s1 = float( sub( 1.0, s ) ).toVar();
  26864. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26865. } ).setLayout( {
  26866. name: 'mx_bilerp_1',
  26867. type: 'vec3',
  26868. inputs: [
  26869. { name: 'v0', type: 'vec3' },
  26870. { name: 'v1', type: 'vec3' },
  26871. { name: 'v2', type: 'vec3' },
  26872. { name: 'v3', type: 'vec3' },
  26873. { name: 's', type: 'float' },
  26874. { name: 't', type: 'float' }
  26875. ]
  26876. } );
  26877. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26878. 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 ] ) => {
  26879. const r = float( r_immutable ).toVar();
  26880. const t = float( t_immutable ).toVar();
  26881. const s = float( s_immutable ).toVar();
  26882. const v7 = float( v7_immutable ).toVar();
  26883. const v6 = float( v6_immutable ).toVar();
  26884. const v5 = float( v5_immutable ).toVar();
  26885. const v4 = float( v4_immutable ).toVar();
  26886. const v3 = float( v3_immutable ).toVar();
  26887. const v2 = float( v2_immutable ).toVar();
  26888. const v1 = float( v1_immutable ).toVar();
  26889. const v0 = float( v0_immutable ).toVar();
  26890. const s1 = float( sub( 1.0, s ) ).toVar();
  26891. const t1 = float( sub( 1.0, t ) ).toVar();
  26892. const r1 = float( sub( 1.0, r ) ).toVar();
  26893. 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 ) ) ) ) ) );
  26894. } ).setLayout( {
  26895. name: 'mx_trilerp_0',
  26896. type: 'float',
  26897. inputs: [
  26898. { name: 'v0', type: 'float' },
  26899. { name: 'v1', type: 'float' },
  26900. { name: 'v2', type: 'float' },
  26901. { name: 'v3', type: 'float' },
  26902. { name: 'v4', type: 'float' },
  26903. { name: 'v5', type: 'float' },
  26904. { name: 'v6', type: 'float' },
  26905. { name: 'v7', type: 'float' },
  26906. { name: 's', type: 'float' },
  26907. { name: 't', type: 'float' },
  26908. { name: 'r', type: 'float' }
  26909. ]
  26910. } );
  26911. 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 ] ) => {
  26912. const r = float( r_immutable ).toVar();
  26913. const t = float( t_immutable ).toVar();
  26914. const s = float( s_immutable ).toVar();
  26915. const v7 = vec3( v7_immutable ).toVar();
  26916. const v6 = vec3( v6_immutable ).toVar();
  26917. const v5 = vec3( v5_immutable ).toVar();
  26918. const v4 = vec3( v4_immutable ).toVar();
  26919. const v3 = vec3( v3_immutable ).toVar();
  26920. const v2 = vec3( v2_immutable ).toVar();
  26921. const v1 = vec3( v1_immutable ).toVar();
  26922. const v0 = vec3( v0_immutable ).toVar();
  26923. const s1 = float( sub( 1.0, s ) ).toVar();
  26924. const t1 = float( sub( 1.0, t ) ).toVar();
  26925. const r1 = float( sub( 1.0, r ) ).toVar();
  26926. 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 ) ) ) ) ) );
  26927. } ).setLayout( {
  26928. name: 'mx_trilerp_1',
  26929. type: 'vec3',
  26930. inputs: [
  26931. { name: 'v0', type: 'vec3' },
  26932. { name: 'v1', type: 'vec3' },
  26933. { name: 'v2', type: 'vec3' },
  26934. { name: 'v3', type: 'vec3' },
  26935. { name: 'v4', type: 'vec3' },
  26936. { name: 'v5', type: 'vec3' },
  26937. { name: 'v6', type: 'vec3' },
  26938. { name: 'v7', type: 'vec3' },
  26939. { name: 's', type: 'float' },
  26940. { name: 't', type: 'float' },
  26941. { name: 'r', type: 'float' }
  26942. ]
  26943. } );
  26944. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26945. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26946. const y = float( y_immutable ).toVar();
  26947. const x = float( x_immutable ).toVar();
  26948. const hash = uint( hash_immutable ).toVar();
  26949. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26950. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26951. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26952. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26953. } ).setLayout( {
  26954. name: 'mx_gradient_float_0',
  26955. type: 'float',
  26956. inputs: [
  26957. { name: 'hash', type: 'uint' },
  26958. { name: 'x', type: 'float' },
  26959. { name: 'y', type: 'float' }
  26960. ]
  26961. } );
  26962. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26963. const z = float( z_immutable ).toVar();
  26964. const y = float( y_immutable ).toVar();
  26965. const x = float( x_immutable ).toVar();
  26966. const hash = uint( hash_immutable ).toVar();
  26967. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26968. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26969. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26970. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26971. } ).setLayout( {
  26972. name: 'mx_gradient_float_1',
  26973. type: 'float',
  26974. inputs: [
  26975. { name: 'hash', type: 'uint' },
  26976. { name: 'x', type: 'float' },
  26977. { name: 'y', type: 'float' },
  26978. { name: 'z', type: 'float' }
  26979. ]
  26980. } );
  26981. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26982. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26983. const y = float( y_immutable ).toVar();
  26984. const x = float( x_immutable ).toVar();
  26985. const hash = uvec3( hash_immutable ).toVar();
  26986. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26987. } ).setLayout( {
  26988. name: 'mx_gradient_vec3_0',
  26989. type: 'vec3',
  26990. inputs: [
  26991. { name: 'hash', type: 'uvec3' },
  26992. { name: 'x', type: 'float' },
  26993. { name: 'y', type: 'float' }
  26994. ]
  26995. } );
  26996. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26997. const z = float( z_immutable ).toVar();
  26998. const y = float( y_immutable ).toVar();
  26999. const x = float( x_immutable ).toVar();
  27000. const hash = uvec3( hash_immutable ).toVar();
  27001. 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 ) );
  27002. } ).setLayout( {
  27003. name: 'mx_gradient_vec3_1',
  27004. type: 'vec3',
  27005. inputs: [
  27006. { name: 'hash', type: 'uvec3' },
  27007. { name: 'x', type: 'float' },
  27008. { name: 'y', type: 'float' },
  27009. { name: 'z', type: 'float' }
  27010. ]
  27011. } );
  27012. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  27013. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27014. const v = float( v_immutable ).toVar();
  27015. return mul( 0.6616, v );
  27016. } ).setLayout( {
  27017. name: 'mx_gradient_scale2d_0',
  27018. type: 'float',
  27019. inputs: [
  27020. { name: 'v', type: 'float' }
  27021. ]
  27022. } );
  27023. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27024. const v = float( v_immutable ).toVar();
  27025. return mul( 0.9820, v );
  27026. } ).setLayout( {
  27027. name: 'mx_gradient_scale3d_0',
  27028. type: 'float',
  27029. inputs: [
  27030. { name: 'v', type: 'float' }
  27031. ]
  27032. } );
  27033. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27034. const v = vec3( v_immutable ).toVar();
  27035. return mul( 0.6616, v );
  27036. } ).setLayout( {
  27037. name: 'mx_gradient_scale2d_1',
  27038. type: 'vec3',
  27039. inputs: [
  27040. { name: 'v', type: 'vec3' }
  27041. ]
  27042. } );
  27043. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  27044. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27045. const v = vec3( v_immutable ).toVar();
  27046. return mul( 0.9820, v );
  27047. } ).setLayout( {
  27048. name: 'mx_gradient_scale3d_1',
  27049. type: 'vec3',
  27050. inputs: [
  27051. { name: 'v', type: 'vec3' }
  27052. ]
  27053. } );
  27054. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  27055. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  27056. const k = int( k_immutable ).toVar();
  27057. const x = uint( x_immutable ).toVar();
  27058. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  27059. } ).setLayout( {
  27060. name: 'mx_rotl32',
  27061. type: 'uint',
  27062. inputs: [
  27063. { name: 'x', type: 'uint' },
  27064. { name: 'k', type: 'int' }
  27065. ]
  27066. } );
  27067. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  27068. a.subAssign( c );
  27069. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  27070. c.addAssign( b );
  27071. b.subAssign( a );
  27072. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  27073. a.addAssign( c );
  27074. c.subAssign( b );
  27075. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  27076. b.addAssign( a );
  27077. a.subAssign( c );
  27078. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  27079. c.addAssign( b );
  27080. b.subAssign( a );
  27081. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  27082. a.addAssign( c );
  27083. c.subAssign( b );
  27084. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  27085. b.addAssign( a );
  27086. } );
  27087. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  27088. const c = uint( c_immutable ).toVar();
  27089. const b = uint( b_immutable ).toVar();
  27090. const a = uint( a_immutable ).toVar();
  27091. c.bitXorAssign( b );
  27092. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  27093. a.bitXorAssign( c );
  27094. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  27095. b.bitXorAssign( a );
  27096. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  27097. c.bitXorAssign( b );
  27098. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  27099. a.bitXorAssign( c );
  27100. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  27101. b.bitXorAssign( a );
  27102. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  27103. c.bitXorAssign( b );
  27104. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  27105. return c;
  27106. } ).setLayout( {
  27107. name: 'mx_bjfinal',
  27108. type: 'uint',
  27109. inputs: [
  27110. { name: 'a', type: 'uint' },
  27111. { name: 'b', type: 'uint' },
  27112. { name: 'c', type: 'uint' }
  27113. ]
  27114. } );
  27115. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  27116. const bits = uint( bits_immutable ).toVar();
  27117. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  27118. } ).setLayout( {
  27119. name: 'mx_bits_to_01',
  27120. type: 'float',
  27121. inputs: [
  27122. { name: 'bits', type: 'uint' }
  27123. ]
  27124. } );
  27125. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  27126. const t = float( t_immutable ).toVar();
  27127. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  27128. } ).setLayout( {
  27129. name: 'mx_fade',
  27130. type: 'float',
  27131. inputs: [
  27132. { name: 't', type: 'float' }
  27133. ]
  27134. } );
  27135. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27136. const x = int( x_immutable ).toVar();
  27137. const len = uint( uint( 1 ) ).toVar();
  27138. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  27139. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  27140. } ).setLayout( {
  27141. name: 'mx_hash_int_0',
  27142. type: 'uint',
  27143. inputs: [
  27144. { name: 'x', type: 'int' }
  27145. ]
  27146. } );
  27147. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  27148. const y = int( y_immutable ).toVar();
  27149. const x = int( x_immutable ).toVar();
  27150. const len = uint( uint( 2 ) ).toVar();
  27151. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27152. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27153. a.addAssign( uint( x ) );
  27154. b.addAssign( uint( y ) );
  27155. return mx_bjfinal( a, b, c );
  27156. } ).setLayout( {
  27157. name: 'mx_hash_int_1',
  27158. type: 'uint',
  27159. inputs: [
  27160. { name: 'x', type: 'int' },
  27161. { name: 'y', type: 'int' }
  27162. ]
  27163. } );
  27164. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  27165. const z = int( z_immutable ).toVar();
  27166. const y = int( y_immutable ).toVar();
  27167. const x = int( x_immutable ).toVar();
  27168. const len = uint( uint( 3 ) ).toVar();
  27169. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27170. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27171. a.addAssign( uint( x ) );
  27172. b.addAssign( uint( y ) );
  27173. c.addAssign( uint( z ) );
  27174. return mx_bjfinal( a, b, c );
  27175. } ).setLayout( {
  27176. name: 'mx_hash_int_2',
  27177. type: 'uint',
  27178. inputs: [
  27179. { name: 'x', type: 'int' },
  27180. { name: 'y', type: 'int' },
  27181. { name: 'z', type: 'int' }
  27182. ]
  27183. } );
  27184. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  27185. const xx = int( xx_immutable ).toVar();
  27186. const z = int( z_immutable ).toVar();
  27187. const y = int( y_immutable ).toVar();
  27188. const x = int( x_immutable ).toVar();
  27189. const len = uint( uint( 4 ) ).toVar();
  27190. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27191. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27192. a.addAssign( uint( x ) );
  27193. b.addAssign( uint( y ) );
  27194. c.addAssign( uint( z ) );
  27195. mx_bjmix( a, b, c );
  27196. a.addAssign( uint( xx ) );
  27197. return mx_bjfinal( a, b, c );
  27198. } ).setLayout( {
  27199. name: 'mx_hash_int_3',
  27200. type: 'uint',
  27201. inputs: [
  27202. { name: 'x', type: 'int' },
  27203. { name: 'y', type: 'int' },
  27204. { name: 'z', type: 'int' },
  27205. { name: 'xx', type: 'int' }
  27206. ]
  27207. } );
  27208. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  27209. const yy = int( yy_immutable ).toVar();
  27210. const xx = int( xx_immutable ).toVar();
  27211. const z = int( z_immutable ).toVar();
  27212. const y = int( y_immutable ).toVar();
  27213. const x = int( x_immutable ).toVar();
  27214. const len = uint( uint( 5 ) ).toVar();
  27215. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  27216. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  27217. a.addAssign( uint( x ) );
  27218. b.addAssign( uint( y ) );
  27219. c.addAssign( uint( z ) );
  27220. mx_bjmix( a, b, c );
  27221. a.addAssign( uint( xx ) );
  27222. b.addAssign( uint( yy ) );
  27223. return mx_bjfinal( a, b, c );
  27224. } ).setLayout( {
  27225. name: 'mx_hash_int_4',
  27226. type: 'uint',
  27227. inputs: [
  27228. { name: 'x', type: 'int' },
  27229. { name: 'y', type: 'int' },
  27230. { name: 'z', type: 'int' },
  27231. { name: 'xx', type: 'int' },
  27232. { name: 'yy', type: 'int' }
  27233. ]
  27234. } );
  27235. 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 ] );
  27236. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  27237. const y = int( y_immutable ).toVar();
  27238. const x = int( x_immutable ).toVar();
  27239. const h = uint( mx_hash_int( x, y ) ).toVar();
  27240. const result = uvec3().toVar();
  27241. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  27242. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  27243. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  27244. return result;
  27245. } ).setLayout( {
  27246. name: 'mx_hash_vec3_0',
  27247. type: 'uvec3',
  27248. inputs: [
  27249. { name: 'x', type: 'int' },
  27250. { name: 'y', type: 'int' }
  27251. ]
  27252. } );
  27253. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  27254. const z = int( z_immutable ).toVar();
  27255. const y = int( y_immutable ).toVar();
  27256. const x = int( x_immutable ).toVar();
  27257. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  27258. const result = uvec3().toVar();
  27259. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  27260. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  27261. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  27262. return result;
  27263. } ).setLayout( {
  27264. name: 'mx_hash_vec3_1',
  27265. type: 'uvec3',
  27266. inputs: [
  27267. { name: 'x', type: 'int' },
  27268. { name: 'y', type: 'int' },
  27269. { name: 'z', type: 'int' }
  27270. ]
  27271. } );
  27272. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  27273. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27274. const p = vec2( p_immutable ).toVar();
  27275. const X = int().toVar(), Y = int().toVar();
  27276. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27277. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27278. const u = float( mx_fade( fx ) ).toVar();
  27279. const v = float( mx_fade( fy ) ).toVar();
  27280. 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();
  27281. return mx_gradient_scale2d( result );
  27282. } ).setLayout( {
  27283. name: 'mx_perlin_noise_float_0',
  27284. type: 'float',
  27285. inputs: [
  27286. { name: 'p', type: 'vec2' }
  27287. ]
  27288. } );
  27289. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27290. const p = vec3( p_immutable ).toVar();
  27291. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27292. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27293. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27294. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  27295. const u = float( mx_fade( fx ) ).toVar();
  27296. const v = float( mx_fade( fy ) ).toVar();
  27297. const w = float( mx_fade( fz ) ).toVar();
  27298. 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();
  27299. return mx_gradient_scale3d( result );
  27300. } ).setLayout( {
  27301. name: 'mx_perlin_noise_float_1',
  27302. type: 'float',
  27303. inputs: [
  27304. { name: 'p', type: 'vec3' }
  27305. ]
  27306. } );
  27307. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  27308. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27309. const p = vec2( p_immutable ).toVar();
  27310. const X = int().toVar(), Y = int().toVar();
  27311. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27312. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27313. const u = float( mx_fade( fx ) ).toVar();
  27314. const v = float( mx_fade( fy ) ).toVar();
  27315. 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();
  27316. return mx_gradient_scale2d( result );
  27317. } ).setLayout( {
  27318. name: 'mx_perlin_noise_vec3_0',
  27319. type: 'vec3',
  27320. inputs: [
  27321. { name: 'p', type: 'vec2' }
  27322. ]
  27323. } );
  27324. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27325. const p = vec3( p_immutable ).toVar();
  27326. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27327. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  27328. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  27329. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  27330. const u = float( mx_fade( fx ) ).toVar();
  27331. const v = float( mx_fade( fy ) ).toVar();
  27332. const w = float( mx_fade( fz ) ).toVar();
  27333. 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();
  27334. return mx_gradient_scale3d( result );
  27335. } ).setLayout( {
  27336. name: 'mx_perlin_noise_vec3_1',
  27337. type: 'vec3',
  27338. inputs: [
  27339. { name: 'p', type: 'vec3' }
  27340. ]
  27341. } );
  27342. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  27343. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27344. const p = float( p_immutable ).toVar();
  27345. const ix = int( mx_floor( p ) ).toVar();
  27346. return mx_bits_to_01( mx_hash_int( ix ) );
  27347. } ).setLayout( {
  27348. name: 'mx_cell_noise_float_0',
  27349. type: 'float',
  27350. inputs: [
  27351. { name: 'p', type: 'float' }
  27352. ]
  27353. } );
  27354. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27355. const p = vec2( p_immutable ).toVar();
  27356. const ix = int( mx_floor( p.x ) ).toVar();
  27357. const iy = int( mx_floor( p.y ) ).toVar();
  27358. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  27359. } ).setLayout( {
  27360. name: 'mx_cell_noise_float_1',
  27361. type: 'float',
  27362. inputs: [
  27363. { name: 'p', type: 'vec2' }
  27364. ]
  27365. } );
  27366. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27367. const p = vec3( p_immutable ).toVar();
  27368. const ix = int( mx_floor( p.x ) ).toVar();
  27369. const iy = int( mx_floor( p.y ) ).toVar();
  27370. const iz = int( mx_floor( p.z ) ).toVar();
  27371. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  27372. } ).setLayout( {
  27373. name: 'mx_cell_noise_float_2',
  27374. type: 'float',
  27375. inputs: [
  27376. { name: 'p', type: 'vec3' }
  27377. ]
  27378. } );
  27379. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27380. const p = vec4( p_immutable ).toVar();
  27381. const ix = int( mx_floor( p.x ) ).toVar();
  27382. const iy = int( mx_floor( p.y ) ).toVar();
  27383. const iz = int( mx_floor( p.z ) ).toVar();
  27384. const iw = int( mx_floor( p.w ) ).toVar();
  27385. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  27386. } ).setLayout( {
  27387. name: 'mx_cell_noise_float_3',
  27388. type: 'float',
  27389. inputs: [
  27390. { name: 'p', type: 'vec4' }
  27391. ]
  27392. } );
  27393. 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 ] );
  27394. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27395. const p = float( p_immutable ).toVar();
  27396. const ix = int( mx_floor( p ) ).toVar();
  27397. 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 ) ) ) );
  27398. } ).setLayout( {
  27399. name: 'mx_cell_noise_vec3_0',
  27400. type: 'vec3',
  27401. inputs: [
  27402. { name: 'p', type: 'float' }
  27403. ]
  27404. } );
  27405. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27406. const p = vec2( p_immutable ).toVar();
  27407. const ix = int( mx_floor( p.x ) ).toVar();
  27408. const iy = int( mx_floor( p.y ) ).toVar();
  27409. 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 ) ) ) );
  27410. } ).setLayout( {
  27411. name: 'mx_cell_noise_vec3_1',
  27412. type: 'vec3',
  27413. inputs: [
  27414. { name: 'p', type: 'vec2' }
  27415. ]
  27416. } );
  27417. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27418. const p = vec3( p_immutable ).toVar();
  27419. const ix = int( mx_floor( p.x ) ).toVar();
  27420. const iy = int( mx_floor( p.y ) ).toVar();
  27421. const iz = int( mx_floor( p.z ) ).toVar();
  27422. 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 ) ) ) );
  27423. } ).setLayout( {
  27424. name: 'mx_cell_noise_vec3_2',
  27425. type: 'vec3',
  27426. inputs: [
  27427. { name: 'p', type: 'vec3' }
  27428. ]
  27429. } );
  27430. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27431. const p = vec4( p_immutable ).toVar();
  27432. const ix = int( mx_floor( p.x ) ).toVar();
  27433. const iy = int( mx_floor( p.y ) ).toVar();
  27434. const iz = int( mx_floor( p.z ) ).toVar();
  27435. const iw = int( mx_floor( p.w ) ).toVar();
  27436. 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 ) ) ) );
  27437. } ).setLayout( {
  27438. name: 'mx_cell_noise_vec3_3',
  27439. type: 'vec3',
  27440. inputs: [
  27441. { name: 'p', type: 'vec4' }
  27442. ]
  27443. } );
  27444. 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 ] );
  27445. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27446. const diminish = float( diminish_immutable ).toVar();
  27447. const lacunarity = float( lacunarity_immutable ).toVar();
  27448. const octaves = int( octaves_immutable ).toVar();
  27449. const p = vec3( p_immutable ).toVar();
  27450. const result = float( 0.0 ).toVar();
  27451. const amplitude = float( 1.0 ).toVar();
  27452. Loop( octaves, () => {
  27453. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  27454. amplitude.mulAssign( diminish );
  27455. p.mulAssign( lacunarity );
  27456. } );
  27457. return result;
  27458. } ).setLayout( {
  27459. name: 'mx_fractal_noise_float',
  27460. type: 'float',
  27461. inputs: [
  27462. { name: 'p', type: 'vec3' },
  27463. { name: 'octaves', type: 'int' },
  27464. { name: 'lacunarity', type: 'float' },
  27465. { name: 'diminish', type: 'float' }
  27466. ]
  27467. } );
  27468. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27469. const diminish = float( diminish_immutable ).toVar();
  27470. const lacunarity = float( lacunarity_immutable ).toVar();
  27471. const octaves = int( octaves_immutable ).toVar();
  27472. const p = vec3( p_immutable ).toVar();
  27473. const result = vec3( 0.0 ).toVar();
  27474. const amplitude = float( 1.0 ).toVar();
  27475. Loop( octaves, () => {
  27476. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  27477. amplitude.mulAssign( diminish );
  27478. p.mulAssign( lacunarity );
  27479. } );
  27480. return result;
  27481. } ).setLayout( {
  27482. name: 'mx_fractal_noise_vec3',
  27483. type: 'vec3',
  27484. inputs: [
  27485. { name: 'p', type: 'vec3' },
  27486. { name: 'octaves', type: 'int' },
  27487. { name: 'lacunarity', type: 'float' },
  27488. { name: 'diminish', type: 'float' }
  27489. ]
  27490. } );
  27491. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27492. const diminish = float( diminish_immutable ).toVar();
  27493. const lacunarity = float( lacunarity_immutable ).toVar();
  27494. const octaves = int( octaves_immutable ).toVar();
  27495. const p = vec3( p_immutable ).toVar();
  27496. 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 ) );
  27497. } ).setLayout( {
  27498. name: 'mx_fractal_noise_vec2',
  27499. type: 'vec2',
  27500. inputs: [
  27501. { name: 'p', type: 'vec3' },
  27502. { name: 'octaves', type: 'int' },
  27503. { name: 'lacunarity', type: 'float' },
  27504. { name: 'diminish', type: 'float' }
  27505. ]
  27506. } );
  27507. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27508. const diminish = float( diminish_immutable ).toVar();
  27509. const lacunarity = float( lacunarity_immutable ).toVar();
  27510. const octaves = int( octaves_immutable ).toVar();
  27511. const p = vec3( p_immutable ).toVar();
  27512. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  27513. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  27514. return vec4( c, f );
  27515. } ).setLayout( {
  27516. name: 'mx_fractal_noise_vec4',
  27517. type: 'vec4',
  27518. inputs: [
  27519. { name: 'p', type: 'vec3' },
  27520. { name: 'octaves', type: 'int' },
  27521. { name: 'lacunarity', type: 'float' },
  27522. { name: 'diminish', type: 'float' }
  27523. ]
  27524. } );
  27525. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  27526. const metric = int( metric_immutable ).toVar();
  27527. const jitter = float( jitter_immutable ).toVar();
  27528. const yoff = int( yoff_immutable ).toVar();
  27529. const xoff = int( xoff_immutable ).toVar();
  27530. const y = int( y_immutable ).toVar();
  27531. const x = int( x_immutable ).toVar();
  27532. const p = vec2( p_immutable ).toVar();
  27533. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  27534. const off = vec2( tmp.x, tmp.y ).toVar();
  27535. off.subAssign( 0.5 );
  27536. off.mulAssign( jitter );
  27537. off.addAssign( 0.5 );
  27538. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  27539. const diff = vec2( cellpos.sub( p ) ).toVar();
  27540. If( metric.equal( int( 2 ) ), () => {
  27541. return abs( diff.x ).add( abs( diff.y ) );
  27542. } );
  27543. If( metric.equal( int( 3 ) ), () => {
  27544. return max$1( abs( diff.x ), abs( diff.y ) );
  27545. } );
  27546. return dot( diff, diff );
  27547. } ).setLayout( {
  27548. name: 'mx_worley_distance_0',
  27549. type: 'float',
  27550. inputs: [
  27551. { name: 'p', type: 'vec2' },
  27552. { name: 'x', type: 'int' },
  27553. { name: 'y', type: 'int' },
  27554. { name: 'xoff', type: 'int' },
  27555. { name: 'yoff', type: 'int' },
  27556. { name: 'jitter', type: 'float' },
  27557. { name: 'metric', type: 'int' }
  27558. ]
  27559. } );
  27560. 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 ] ) => {
  27561. const metric = int( metric_immutable ).toVar();
  27562. const jitter = float( jitter_immutable ).toVar();
  27563. const zoff = int( zoff_immutable ).toVar();
  27564. const yoff = int( yoff_immutable ).toVar();
  27565. const xoff = int( xoff_immutable ).toVar();
  27566. const z = int( z_immutable ).toVar();
  27567. const y = int( y_immutable ).toVar();
  27568. const x = int( x_immutable ).toVar();
  27569. const p = vec3( p_immutable ).toVar();
  27570. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  27571. off.subAssign( 0.5 );
  27572. off.mulAssign( jitter );
  27573. off.addAssign( 0.5 );
  27574. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  27575. const diff = vec3( cellpos.sub( p ) ).toVar();
  27576. If( metric.equal( int( 2 ) ), () => {
  27577. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  27578. } );
  27579. If( metric.equal( int( 3 ) ), () => {
  27580. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  27581. } );
  27582. return dot( diff, diff );
  27583. } ).setLayout( {
  27584. name: 'mx_worley_distance_1',
  27585. type: 'float',
  27586. inputs: [
  27587. { name: 'p', type: 'vec3' },
  27588. { name: 'x', type: 'int' },
  27589. { name: 'y', type: 'int' },
  27590. { name: 'z', type: 'int' },
  27591. { name: 'xoff', type: 'int' },
  27592. { name: 'yoff', type: 'int' },
  27593. { name: 'zoff', type: 'int' },
  27594. { name: 'jitter', type: 'float' },
  27595. { name: 'metric', type: 'int' }
  27596. ]
  27597. } );
  27598. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  27599. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27600. const metric = int( metric_immutable ).toVar();
  27601. const jitter = float( jitter_immutable ).toVar();
  27602. const p = vec2( p_immutable ).toVar();
  27603. const X = int().toVar(), Y = int().toVar();
  27604. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27605. const sqdist = float( 1e6 ).toVar();
  27606. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27607. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27608. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27609. sqdist.assign( min$1( sqdist, dist ) );
  27610. } );
  27611. } );
  27612. If( metric.equal( int( 0 ) ), () => {
  27613. sqdist.assign( sqrt( sqdist ) );
  27614. } );
  27615. return sqdist;
  27616. } ).setLayout( {
  27617. name: 'mx_worley_noise_float_0',
  27618. type: 'float',
  27619. inputs: [
  27620. { name: 'p', type: 'vec2' },
  27621. { name: 'jitter', type: 'float' },
  27622. { name: 'metric', type: 'int' }
  27623. ]
  27624. } );
  27625. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27626. const metric = int( metric_immutable ).toVar();
  27627. const jitter = float( jitter_immutable ).toVar();
  27628. const p = vec2( p_immutable ).toVar();
  27629. const X = int().toVar(), Y = int().toVar();
  27630. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27631. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27632. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27633. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27634. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27635. If( dist.lessThan( sqdist.x ), () => {
  27636. sqdist.y.assign( sqdist.x );
  27637. sqdist.x.assign( dist );
  27638. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27639. sqdist.y.assign( dist );
  27640. } );
  27641. } );
  27642. } );
  27643. If( metric.equal( int( 0 ) ), () => {
  27644. sqdist.assign( sqrt( sqdist ) );
  27645. } );
  27646. return sqdist;
  27647. } ).setLayout( {
  27648. name: 'mx_worley_noise_vec2_0',
  27649. type: 'vec2',
  27650. inputs: [
  27651. { name: 'p', type: 'vec2' },
  27652. { name: 'jitter', type: 'float' },
  27653. { name: 'metric', type: 'int' }
  27654. ]
  27655. } );
  27656. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27657. const metric = int( metric_immutable ).toVar();
  27658. const jitter = float( jitter_immutable ).toVar();
  27659. const p = vec2( p_immutable ).toVar();
  27660. const X = int().toVar(), Y = int().toVar();
  27661. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27662. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27663. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27664. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27665. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27666. If( dist.lessThan( sqdist.x ), () => {
  27667. sqdist.z.assign( sqdist.y );
  27668. sqdist.y.assign( sqdist.x );
  27669. sqdist.x.assign( dist );
  27670. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27671. sqdist.z.assign( sqdist.y );
  27672. sqdist.y.assign( dist );
  27673. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27674. sqdist.z.assign( dist );
  27675. } );
  27676. } );
  27677. } );
  27678. If( metric.equal( int( 0 ) ), () => {
  27679. sqdist.assign( sqrt( sqdist ) );
  27680. } );
  27681. return sqdist;
  27682. } ).setLayout( {
  27683. name: 'mx_worley_noise_vec3_0',
  27684. type: 'vec3',
  27685. inputs: [
  27686. { name: 'p', type: 'vec2' },
  27687. { name: 'jitter', type: 'float' },
  27688. { name: 'metric', type: 'int' }
  27689. ]
  27690. } );
  27691. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27692. const metric = int( metric_immutable ).toVar();
  27693. const jitter = float( jitter_immutable ).toVar();
  27694. const p = vec3( p_immutable ).toVar();
  27695. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27696. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27697. const sqdist = float( 1e6 ).toVar();
  27698. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27699. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27700. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27701. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27702. sqdist.assign( min$1( sqdist, dist ) );
  27703. } );
  27704. } );
  27705. } );
  27706. If( metric.equal( int( 0 ) ), () => {
  27707. sqdist.assign( sqrt( sqdist ) );
  27708. } );
  27709. return sqdist;
  27710. } ).setLayout( {
  27711. name: 'mx_worley_noise_float_1',
  27712. type: 'float',
  27713. inputs: [
  27714. { name: 'p', type: 'vec3' },
  27715. { name: 'jitter', type: 'float' },
  27716. { name: 'metric', type: 'int' }
  27717. ]
  27718. } );
  27719. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27720. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27721. const metric = int( metric_immutable ).toVar();
  27722. const jitter = float( jitter_immutable ).toVar();
  27723. const p = vec3( p_immutable ).toVar();
  27724. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27725. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27726. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27727. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27728. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27729. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27730. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27731. If( dist.lessThan( sqdist.x ), () => {
  27732. sqdist.y.assign( sqdist.x );
  27733. sqdist.x.assign( dist );
  27734. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27735. sqdist.y.assign( dist );
  27736. } );
  27737. } );
  27738. } );
  27739. } );
  27740. If( metric.equal( int( 0 ) ), () => {
  27741. sqdist.assign( sqrt( sqdist ) );
  27742. } );
  27743. return sqdist;
  27744. } ).setLayout( {
  27745. name: 'mx_worley_noise_vec2_1',
  27746. type: 'vec2',
  27747. inputs: [
  27748. { name: 'p', type: 'vec3' },
  27749. { name: 'jitter', type: 'float' },
  27750. { name: 'metric', type: 'int' }
  27751. ]
  27752. } );
  27753. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27754. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27755. const metric = int( metric_immutable ).toVar();
  27756. const jitter = float( jitter_immutable ).toVar();
  27757. const p = vec3( p_immutable ).toVar();
  27758. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27759. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27760. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27761. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27762. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27763. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27764. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27765. If( dist.lessThan( sqdist.x ), () => {
  27766. sqdist.z.assign( sqdist.y );
  27767. sqdist.y.assign( sqdist.x );
  27768. sqdist.x.assign( dist );
  27769. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27770. sqdist.z.assign( sqdist.y );
  27771. sqdist.y.assign( dist );
  27772. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27773. sqdist.z.assign( dist );
  27774. } );
  27775. } );
  27776. } );
  27777. } );
  27778. If( metric.equal( int( 0 ) ), () => {
  27779. sqdist.assign( sqrt( sqdist ) );
  27780. } );
  27781. return sqdist;
  27782. } ).setLayout( {
  27783. name: 'mx_worley_noise_vec3_1',
  27784. type: 'vec3',
  27785. inputs: [
  27786. { name: 'p', type: 'vec3' },
  27787. { name: 'jitter', type: 'float' },
  27788. { name: 'metric', type: 'int' }
  27789. ]
  27790. } );
  27791. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27792. // Three.js Transpiler
  27793. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27794. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27795. const s = hsv.y;
  27796. const v = hsv.z;
  27797. const result = vec3().toVar();
  27798. If( s.lessThan( 0.0001 ), () => {
  27799. result.assign( vec3( v, v, v ) );
  27800. } ).Else( () => {
  27801. let h = hsv.x;
  27802. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27803. const hi = int( trunc( h ) );
  27804. const f = h.sub( float( hi ) );
  27805. const p = v.mul( s.oneMinus() );
  27806. const q = v.mul( s.mul( f ).oneMinus() );
  27807. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27808. If( hi.equal( int( 0 ) ), () => {
  27809. result.assign( vec3( v, t, p ) );
  27810. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27811. result.assign( vec3( q, v, p ) );
  27812. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27813. result.assign( vec3( p, v, t ) );
  27814. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27815. result.assign( vec3( p, q, v ) );
  27816. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27817. result.assign( vec3( t, p, v ) );
  27818. } ).Else( () => {
  27819. result.assign( vec3( v, p, q ) );
  27820. } );
  27821. } );
  27822. return result;
  27823. } ).setLayout( {
  27824. name: 'mx_hsvtorgb',
  27825. type: 'vec3',
  27826. inputs: [
  27827. { name: 'hsv', type: 'vec3' }
  27828. ]
  27829. } );
  27830. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27831. const c = vec3( c_immutable ).toVar();
  27832. const r = float( c.x ).toVar();
  27833. const g = float( c.y ).toVar();
  27834. const b = float( c.z ).toVar();
  27835. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27836. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27837. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27838. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27839. v.assign( maxcomp );
  27840. If( maxcomp.greaterThan( 0.0 ), () => {
  27841. s.assign( delta.div( maxcomp ) );
  27842. } ).Else( () => {
  27843. s.assign( 0.0 );
  27844. } );
  27845. If( s.lessThanEqual( 0.0 ), () => {
  27846. h.assign( 0.0 );
  27847. } ).Else( () => {
  27848. If( r.greaterThanEqual( maxcomp ), () => {
  27849. h.assign( g.sub( b ).div( delta ) );
  27850. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27851. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27852. } ).Else( () => {
  27853. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27854. } );
  27855. h.mulAssign( 1.0 / 6.0 );
  27856. If( h.lessThan( 0.0 ), () => {
  27857. h.addAssign( 1.0 );
  27858. } );
  27859. } );
  27860. return vec3( h, s, v );
  27861. } ).setLayout( {
  27862. name: 'mx_rgbtohsv',
  27863. type: 'vec3',
  27864. inputs: [
  27865. { name: 'c', type: 'vec3' }
  27866. ]
  27867. } );
  27868. // Three.js Transpiler
  27869. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27870. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27871. const color = vec3( color_immutable ).toVar();
  27872. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27873. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27874. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27875. return mix( linSeg, powSeg, isAbove );
  27876. } ).setLayout( {
  27877. name: 'mx_srgb_texture_to_lin_rec709',
  27878. type: 'vec3',
  27879. inputs: [
  27880. { name: 'color', type: 'vec3' }
  27881. ]
  27882. } );
  27883. const mx_aastep = ( threshold, value ) => {
  27884. threshold = float( threshold );
  27885. value = float( value );
  27886. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27887. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27888. };
  27889. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27890. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27891. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27892. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27893. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27894. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27895. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27896. const mx_safepower = ( in1, in2 = 1 ) => {
  27897. in1 = float( in1 );
  27898. return in1.abs().pow( in2 ).mul( in1.sign() );
  27899. };
  27900. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27901. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27902. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27903. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27904. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27905. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27906. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27907. return noise_vec4.mul( amplitude ).add( pivot );
  27908. };
  27909. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27910. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27911. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27912. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27913. 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 );
  27914. 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 );
  27915. 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 );
  27916. 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 );
  27917. /**
  27918. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27919. *
  27920. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27921. *
  27922. * ```js
  27923. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27924. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27925. * ```
  27926. *
  27927. * @tsl
  27928. * @function
  27929. * @param {Node<vec3>} normal - The normal to correct.
  27930. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27931. * @param {Node<vec3>} cubePos - The cube position.
  27932. * @return {Node<vec3>} The parallax corrected normal.
  27933. */
  27934. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27935. const nDir = normalize( normal ).toVar( 'nDir' );
  27936. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27937. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27938. const rbminmax = vec3().toVar( 'rbminmax' );
  27939. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27940. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27941. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27942. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27943. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27944. return boxIntersection.sub( cubePos );
  27945. } );
  27946. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27947. // normal is assumed to have unit length
  27948. const x = normal.x, y = normal.y, z = normal.z;
  27949. // band 0
  27950. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27951. // band 1
  27952. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27953. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27954. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27955. // band 2
  27956. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27957. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27958. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27959. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27960. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27961. return result;
  27962. } );
  27963. // constants
  27964. var TSL = /*#__PURE__*/Object.freeze({
  27965. __proto__: null,
  27966. BRDF_GGX: BRDF_GGX,
  27967. BRDF_Lambert: BRDF_Lambert,
  27968. BasicShadowFilter: BasicShadowFilter,
  27969. Break: Break,
  27970. Const: Const,
  27971. Continue: Continue,
  27972. DFGApprox: DFGApprox,
  27973. D_GGX: D_GGX,
  27974. Discard: Discard,
  27975. EPSILON: EPSILON,
  27976. F_Schlick: F_Schlick,
  27977. Fn: Fn,
  27978. INFINITY: INFINITY,
  27979. If: If,
  27980. Loop: Loop,
  27981. NodeAccess: NodeAccess,
  27982. NodeShaderStage: NodeShaderStage,
  27983. NodeType: NodeType,
  27984. NodeUpdateType: NodeUpdateType,
  27985. PCFShadowFilter: PCFShadowFilter,
  27986. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27987. PI: PI,
  27988. PI2: PI2,
  27989. Return: Return,
  27990. Schlick_to_F0: Schlick_to_F0,
  27991. ScriptableNodeResources: ScriptableNodeResources,
  27992. ShaderNode: ShaderNode,
  27993. TBNViewMatrix: TBNViewMatrix,
  27994. VSMShadowFilter: VSMShadowFilter,
  27995. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27996. Var: Var,
  27997. abs: abs,
  27998. acesFilmicToneMapping: acesFilmicToneMapping,
  27999. acos: acos,
  28000. add: add,
  28001. addMethodChaining: addMethodChaining,
  28002. addNodeElement: addNodeElement,
  28003. agxToneMapping: agxToneMapping,
  28004. all: all,
  28005. alphaT: alphaT,
  28006. and: and,
  28007. anisotropy: anisotropy,
  28008. anisotropyB: anisotropyB,
  28009. anisotropyT: anisotropyT,
  28010. any: any,
  28011. append: append,
  28012. array: array,
  28013. arrayBuffer: arrayBuffer,
  28014. asin: asin,
  28015. assign: assign,
  28016. atan: atan,
  28017. atan2: atan2,
  28018. atomicAdd: atomicAdd,
  28019. atomicAnd: atomicAnd,
  28020. atomicFunc: atomicFunc,
  28021. atomicLoad: atomicLoad,
  28022. atomicMax: atomicMax,
  28023. atomicMin: atomicMin,
  28024. atomicOr: atomicOr,
  28025. atomicStore: atomicStore,
  28026. atomicSub: atomicSub,
  28027. atomicXor: atomicXor,
  28028. attenuationColor: attenuationColor,
  28029. attenuationDistance: attenuationDistance,
  28030. attribute: attribute,
  28031. attributeArray: attributeArray,
  28032. backgroundBlurriness: backgroundBlurriness,
  28033. backgroundIntensity: backgroundIntensity,
  28034. backgroundRotation: backgroundRotation,
  28035. batch: batch,
  28036. billboarding: billboarding,
  28037. bitAnd: bitAnd,
  28038. bitNot: bitNot,
  28039. bitOr: bitOr,
  28040. bitXor: bitXor,
  28041. bitangentGeometry: bitangentGeometry,
  28042. bitangentLocal: bitangentLocal,
  28043. bitangentView: bitangentView,
  28044. bitangentWorld: bitangentWorld,
  28045. bitcast: bitcast,
  28046. blendBurn: blendBurn,
  28047. blendColor: blendColor,
  28048. blendDodge: blendDodge,
  28049. blendOverlay: blendOverlay,
  28050. blendScreen: blendScreen,
  28051. blur: blur,
  28052. bool: bool,
  28053. buffer: buffer,
  28054. bufferAttribute: bufferAttribute,
  28055. bumpMap: bumpMap,
  28056. burn: burn,
  28057. bvec2: bvec2,
  28058. bvec3: bvec3,
  28059. bvec4: bvec4,
  28060. bypass: bypass,
  28061. cache: cache,
  28062. call: call,
  28063. cameraFar: cameraFar,
  28064. cameraIndex: cameraIndex,
  28065. cameraNear: cameraNear,
  28066. cameraNormalMatrix: cameraNormalMatrix,
  28067. cameraPosition: cameraPosition,
  28068. cameraProjectionMatrix: cameraProjectionMatrix,
  28069. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  28070. cameraViewMatrix: cameraViewMatrix,
  28071. cameraWorldMatrix: cameraWorldMatrix,
  28072. cbrt: cbrt,
  28073. cdl: cdl,
  28074. ceil: ceil,
  28075. checker: checker,
  28076. cineonToneMapping: cineonToneMapping,
  28077. clamp: clamp,
  28078. clearcoat: clearcoat,
  28079. clearcoatRoughness: clearcoatRoughness,
  28080. code: code,
  28081. color: color,
  28082. colorSpaceToWorking: colorSpaceToWorking,
  28083. colorToDirection: colorToDirection,
  28084. compute: compute,
  28085. cond: cond,
  28086. context: context,
  28087. convert: convert,
  28088. convertColorSpace: convertColorSpace,
  28089. convertToTexture: convertToTexture,
  28090. cos: cos,
  28091. cross: cross,
  28092. cubeTexture: cubeTexture,
  28093. dFdx: dFdx,
  28094. dFdy: dFdy,
  28095. dashSize: dashSize,
  28096. defaultBuildStages: defaultBuildStages,
  28097. defaultShaderStages: defaultShaderStages,
  28098. defined: defined,
  28099. degrees: degrees,
  28100. deltaTime: deltaTime,
  28101. densityFog: densityFog,
  28102. densityFogFactor: densityFogFactor,
  28103. depth: depth,
  28104. depthPass: depthPass,
  28105. difference: difference,
  28106. diffuseColor: diffuseColor,
  28107. directPointLight: directPointLight,
  28108. directionToColor: directionToColor,
  28109. dispersion: dispersion,
  28110. distance: distance,
  28111. div: div,
  28112. dodge: dodge,
  28113. dot: dot,
  28114. drawIndex: drawIndex,
  28115. dynamicBufferAttribute: dynamicBufferAttribute,
  28116. element: element,
  28117. emissive: emissive,
  28118. equal: equal,
  28119. equals: equals,
  28120. equirectUV: equirectUV,
  28121. exp: exp,
  28122. exp2: exp2,
  28123. expression: expression,
  28124. faceDirection: faceDirection,
  28125. faceForward: faceForward,
  28126. faceforward: faceforward,
  28127. float: float,
  28128. floor: floor,
  28129. fog: fog,
  28130. fract: fract,
  28131. frameGroup: frameGroup,
  28132. frameId: frameId,
  28133. frontFacing: frontFacing,
  28134. fwidth: fwidth,
  28135. gain: gain,
  28136. gapSize: gapSize,
  28137. getConstNodeType: getConstNodeType,
  28138. getCurrentStack: getCurrentStack,
  28139. getDirection: getDirection,
  28140. getDistanceAttenuation: getDistanceAttenuation,
  28141. getGeometryRoughness: getGeometryRoughness,
  28142. getNormalFromDepth: getNormalFromDepth,
  28143. getParallaxCorrectNormal: getParallaxCorrectNormal,
  28144. getRoughness: getRoughness,
  28145. getScreenPosition: getScreenPosition,
  28146. getShIrradianceAt: getShIrradianceAt,
  28147. getTextureIndex: getTextureIndex,
  28148. getViewPosition: getViewPosition,
  28149. globalId: globalId,
  28150. glsl: glsl,
  28151. glslFn: glslFn,
  28152. grayscale: grayscale,
  28153. greaterThan: greaterThan,
  28154. greaterThanEqual: greaterThanEqual,
  28155. hash: hash,
  28156. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  28157. highpModelViewMatrix: highpModelViewMatrix,
  28158. hue: hue,
  28159. instance: instance,
  28160. instanceIndex: instanceIndex,
  28161. instancedArray: instancedArray,
  28162. instancedBufferAttribute: instancedBufferAttribute,
  28163. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  28164. instancedMesh: instancedMesh,
  28165. int: int,
  28166. inverseSqrt: inverseSqrt,
  28167. inversesqrt: inversesqrt,
  28168. invocationLocalIndex: invocationLocalIndex,
  28169. invocationSubgroupIndex: invocationSubgroupIndex,
  28170. ior: ior,
  28171. iridescence: iridescence,
  28172. iridescenceIOR: iridescenceIOR,
  28173. iridescenceThickness: iridescenceThickness,
  28174. ivec2: ivec2,
  28175. ivec3: ivec3,
  28176. ivec4: ivec4,
  28177. js: js,
  28178. label: label,
  28179. length: length,
  28180. lengthSq: lengthSq,
  28181. lessThan: lessThan,
  28182. lessThanEqual: lessThanEqual,
  28183. lightPosition: lightPosition,
  28184. lightProjectionUV: lightProjectionUV,
  28185. lightShadowMatrix: lightShadowMatrix,
  28186. lightTargetDirection: lightTargetDirection,
  28187. lightTargetPosition: lightTargetPosition,
  28188. lightViewPosition: lightViewPosition,
  28189. lightingContext: lightingContext,
  28190. lights: lights,
  28191. linearDepth: linearDepth,
  28192. linearToneMapping: linearToneMapping,
  28193. localId: localId,
  28194. log: log,
  28195. log2: log2,
  28196. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  28197. loop: loop,
  28198. luminance: luminance,
  28199. mat2: mat2,
  28200. mat3: mat3,
  28201. mat4: mat4,
  28202. matcapUV: matcapUV,
  28203. materialAO: materialAO,
  28204. materialAlphaTest: materialAlphaTest,
  28205. materialAnisotropy: materialAnisotropy,
  28206. materialAnisotropyVector: materialAnisotropyVector,
  28207. materialAttenuationColor: materialAttenuationColor,
  28208. materialAttenuationDistance: materialAttenuationDistance,
  28209. materialClearcoat: materialClearcoat,
  28210. materialClearcoatNormal: materialClearcoatNormal,
  28211. materialClearcoatRoughness: materialClearcoatRoughness,
  28212. materialColor: materialColor,
  28213. materialDispersion: materialDispersion,
  28214. materialEmissive: materialEmissive,
  28215. materialIOR: materialIOR,
  28216. materialIridescence: materialIridescence,
  28217. materialIridescenceIOR: materialIridescenceIOR,
  28218. materialIridescenceThickness: materialIridescenceThickness,
  28219. materialLightMap: materialLightMap,
  28220. materialLineDashOffset: materialLineDashOffset,
  28221. materialLineDashSize: materialLineDashSize,
  28222. materialLineGapSize: materialLineGapSize,
  28223. materialLineScale: materialLineScale,
  28224. materialLineWidth: materialLineWidth,
  28225. materialMetalness: materialMetalness,
  28226. materialNormal: materialNormal,
  28227. materialOpacity: materialOpacity,
  28228. materialPointSize: materialPointSize,
  28229. materialReference: materialReference,
  28230. materialReflectivity: materialReflectivity,
  28231. materialRefractionRatio: materialRefractionRatio,
  28232. materialRotation: materialRotation,
  28233. materialRoughness: materialRoughness,
  28234. materialSheen: materialSheen,
  28235. materialSheenRoughness: materialSheenRoughness,
  28236. materialShininess: materialShininess,
  28237. materialSpecular: materialSpecular,
  28238. materialSpecularColor: materialSpecularColor,
  28239. materialSpecularIntensity: materialSpecularIntensity,
  28240. materialSpecularStrength: materialSpecularStrength,
  28241. materialThickness: materialThickness,
  28242. materialTransmission: materialTransmission,
  28243. max: max$1,
  28244. maxMipLevel: maxMipLevel,
  28245. mediumpModelViewMatrix: mediumpModelViewMatrix,
  28246. metalness: metalness,
  28247. min: min$1,
  28248. mix: mix,
  28249. mixElement: mixElement,
  28250. mod: mod,
  28251. modInt: modInt,
  28252. modelDirection: modelDirection,
  28253. modelNormalMatrix: modelNormalMatrix,
  28254. modelPosition: modelPosition,
  28255. modelScale: modelScale,
  28256. modelViewMatrix: modelViewMatrix,
  28257. modelViewPosition: modelViewPosition,
  28258. modelViewProjection: modelViewProjection,
  28259. modelWorldMatrix: modelWorldMatrix,
  28260. modelWorldMatrixInverse: modelWorldMatrixInverse,
  28261. morphReference: morphReference,
  28262. mrt: mrt,
  28263. mul: mul,
  28264. mx_aastep: mx_aastep,
  28265. mx_cell_noise_float: mx_cell_noise_float,
  28266. mx_contrast: mx_contrast,
  28267. mx_fractal_noise_float: mx_fractal_noise_float,
  28268. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  28269. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  28270. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  28271. mx_hsvtorgb: mx_hsvtorgb,
  28272. mx_noise_float: mx_noise_float,
  28273. mx_noise_vec3: mx_noise_vec3,
  28274. mx_noise_vec4: mx_noise_vec4,
  28275. mx_ramplr: mx_ramplr,
  28276. mx_ramptb: mx_ramptb,
  28277. mx_rgbtohsv: mx_rgbtohsv,
  28278. mx_safepower: mx_safepower,
  28279. mx_splitlr: mx_splitlr,
  28280. mx_splittb: mx_splittb,
  28281. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  28282. mx_transform_uv: mx_transform_uv,
  28283. mx_worley_noise_float: mx_worley_noise_float,
  28284. mx_worley_noise_vec2: mx_worley_noise_vec2,
  28285. mx_worley_noise_vec3: mx_worley_noise_vec3,
  28286. negate: negate,
  28287. neutralToneMapping: neutralToneMapping,
  28288. nodeArray: nodeArray,
  28289. nodeImmutable: nodeImmutable,
  28290. nodeObject: nodeObject,
  28291. nodeObjects: nodeObjects,
  28292. nodeProxy: nodeProxy,
  28293. normalFlat: normalFlat,
  28294. normalGeometry: normalGeometry,
  28295. normalLocal: normalLocal,
  28296. normalMap: normalMap,
  28297. normalView: normalView,
  28298. normalWorld: normalWorld,
  28299. normalize: normalize,
  28300. not: not,
  28301. notEqual: notEqual,
  28302. numWorkgroups: numWorkgroups,
  28303. objectDirection: objectDirection,
  28304. objectGroup: objectGroup,
  28305. objectPosition: objectPosition,
  28306. objectScale: objectScale,
  28307. objectViewPosition: objectViewPosition,
  28308. objectWorldMatrix: objectWorldMatrix,
  28309. oneMinus: oneMinus,
  28310. or: or,
  28311. orthographicDepthToViewZ: orthographicDepthToViewZ,
  28312. oscSawtooth: oscSawtooth,
  28313. oscSine: oscSine,
  28314. oscSquare: oscSquare,
  28315. oscTriangle: oscTriangle,
  28316. output: output,
  28317. outputStruct: outputStruct,
  28318. overlay: overlay,
  28319. overloadingFn: overloadingFn,
  28320. parabola: parabola,
  28321. parallaxDirection: parallaxDirection,
  28322. parallaxUV: parallaxUV,
  28323. parameter: parameter,
  28324. pass: pass,
  28325. passTexture: passTexture,
  28326. pcurve: pcurve,
  28327. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  28328. pmremTexture: pmremTexture,
  28329. pointUV: pointUV,
  28330. pointWidth: pointWidth,
  28331. positionGeometry: positionGeometry,
  28332. positionLocal: positionLocal,
  28333. positionPrevious: positionPrevious,
  28334. positionView: positionView,
  28335. positionViewDirection: positionViewDirection,
  28336. positionWorld: positionWorld,
  28337. positionWorldDirection: positionWorldDirection,
  28338. posterize: posterize,
  28339. pow: pow,
  28340. pow2: pow2,
  28341. pow3: pow3,
  28342. pow4: pow4,
  28343. property: property,
  28344. radians: radians,
  28345. rand: rand,
  28346. range: range,
  28347. rangeFog: rangeFog,
  28348. rangeFogFactor: rangeFogFactor,
  28349. reciprocal: reciprocal,
  28350. reference: reference,
  28351. referenceBuffer: referenceBuffer,
  28352. reflect: reflect,
  28353. reflectVector: reflectVector,
  28354. reflectView: reflectView,
  28355. reflector: reflector,
  28356. refract: refract,
  28357. refractVector: refractVector,
  28358. refractView: refractView,
  28359. reinhardToneMapping: reinhardToneMapping,
  28360. remainder: remainder,
  28361. remap: remap,
  28362. remapClamp: remapClamp,
  28363. renderGroup: renderGroup,
  28364. renderOutput: renderOutput,
  28365. rendererReference: rendererReference,
  28366. rotate: rotate,
  28367. rotateUV: rotateUV,
  28368. roughness: roughness,
  28369. round: round,
  28370. rtt: rtt,
  28371. sRGBTransferEOTF: sRGBTransferEOTF,
  28372. sRGBTransferOETF: sRGBTransferOETF,
  28373. sampler: sampler,
  28374. saturate: saturate,
  28375. saturation: saturation,
  28376. screen: screen,
  28377. screenCoordinate: screenCoordinate,
  28378. screenSize: screenSize,
  28379. screenUV: screenUV,
  28380. scriptable: scriptable,
  28381. scriptableValue: scriptableValue,
  28382. select: select,
  28383. setCurrentStack: setCurrentStack,
  28384. shaderStages: shaderStages,
  28385. shadow: shadow,
  28386. shadowPositionWorld: shadowPositionWorld,
  28387. shapeCircle: shapeCircle,
  28388. sharedUniformGroup: sharedUniformGroup,
  28389. sheen: sheen,
  28390. sheenRoughness: sheenRoughness,
  28391. shiftLeft: shiftLeft,
  28392. shiftRight: shiftRight,
  28393. shininess: shininess,
  28394. sign: sign,
  28395. sin: sin,
  28396. sinc: sinc,
  28397. skinning: skinning,
  28398. skinningReference: skinningReference,
  28399. smoothstep: smoothstep,
  28400. smoothstepElement: smoothstepElement,
  28401. specularColor: specularColor,
  28402. specularF90: specularF90,
  28403. spherizeUV: spherizeUV,
  28404. split: split,
  28405. spritesheetUV: spritesheetUV,
  28406. sqrt: sqrt,
  28407. stack: stack,
  28408. step: step,
  28409. storage: storage,
  28410. storageBarrier: storageBarrier,
  28411. storageObject: storageObject,
  28412. storageTexture: storageTexture,
  28413. string: string,
  28414. struct: struct,
  28415. sub: sub,
  28416. subgroupIndex: subgroupIndex,
  28417. subgroupSize: subgroupSize,
  28418. tan: tan,
  28419. tangentGeometry: tangentGeometry,
  28420. tangentLocal: tangentLocal,
  28421. tangentView: tangentView,
  28422. tangentWorld: tangentWorld,
  28423. temp: temp,
  28424. texture: texture,
  28425. texture3D: texture3D,
  28426. textureBarrier: textureBarrier,
  28427. textureBicubic: textureBicubic,
  28428. textureCubeUV: textureCubeUV,
  28429. textureLoad: textureLoad,
  28430. textureSize: textureSize,
  28431. textureStore: textureStore,
  28432. thickness: thickness,
  28433. time: time,
  28434. timerDelta: timerDelta,
  28435. timerGlobal: timerGlobal,
  28436. timerLocal: timerLocal,
  28437. toOutputColorSpace: toOutputColorSpace,
  28438. toWorkingColorSpace: toWorkingColorSpace,
  28439. toneMapping: toneMapping,
  28440. toneMappingExposure: toneMappingExposure,
  28441. toonOutlinePass: toonOutlinePass,
  28442. transformDirection: transformDirection,
  28443. transformNormal: transformNormal,
  28444. transformNormalToView: transformNormalToView,
  28445. transformedBentNormalView: transformedBentNormalView,
  28446. transformedBitangentView: transformedBitangentView,
  28447. transformedBitangentWorld: transformedBitangentWorld,
  28448. transformedClearcoatNormalView: transformedClearcoatNormalView,
  28449. transformedNormalView: transformedNormalView,
  28450. transformedNormalWorld: transformedNormalWorld,
  28451. transformedTangentView: transformedTangentView,
  28452. transformedTangentWorld: transformedTangentWorld,
  28453. transmission: transmission,
  28454. transpose: transpose,
  28455. triNoise3D: triNoise3D,
  28456. triplanarTexture: triplanarTexture,
  28457. triplanarTextures: triplanarTextures,
  28458. trunc: trunc,
  28459. tslFn: tslFn,
  28460. uint: uint,
  28461. uniform: uniform,
  28462. uniformArray: uniformArray,
  28463. uniformGroup: uniformGroup,
  28464. uniforms: uniforms,
  28465. userData: userData,
  28466. uv: uv,
  28467. uvec2: uvec2,
  28468. uvec3: uvec3,
  28469. uvec4: uvec4,
  28470. varying: varying,
  28471. varyingProperty: varyingProperty,
  28472. vec2: vec2,
  28473. vec3: vec3,
  28474. vec4: vec4,
  28475. vectorComponents: vectorComponents,
  28476. velocity: velocity,
  28477. vertexColor: vertexColor,
  28478. vertexIndex: vertexIndex,
  28479. vertexStage: vertexStage,
  28480. vibrance: vibrance,
  28481. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  28482. viewZToOrthographicDepth: viewZToOrthographicDepth,
  28483. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  28484. viewport: viewport,
  28485. viewportBottomLeft: viewportBottomLeft,
  28486. viewportCoordinate: viewportCoordinate,
  28487. viewportDepthTexture: viewportDepthTexture,
  28488. viewportLinearDepth: viewportLinearDepth,
  28489. viewportMipTexture: viewportMipTexture,
  28490. viewportResolution: viewportResolution,
  28491. viewportSafeUV: viewportSafeUV,
  28492. viewportSharedTexture: viewportSharedTexture,
  28493. viewportSize: viewportSize,
  28494. viewportTexture: viewportTexture,
  28495. viewportTopLeft: viewportTopLeft,
  28496. viewportUV: viewportUV,
  28497. wgsl: wgsl,
  28498. wgslFn: wgslFn,
  28499. workgroupArray: workgroupArray,
  28500. workgroupBarrier: workgroupBarrier,
  28501. workgroupId: workgroupId,
  28502. workingToColorSpace: workingToColorSpace,
  28503. xor: xor
  28504. });
  28505. const _clearColor$1 = /*@__PURE__*/ new Color4();
  28506. /**
  28507. * This renderer module manages the background.
  28508. *
  28509. * @private
  28510. * @augments DataMap
  28511. */
  28512. class Background extends DataMap {
  28513. /**
  28514. * Constructs a new background management component.
  28515. *
  28516. * @param {Renderer} renderer - The renderer.
  28517. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  28518. */
  28519. constructor( renderer, nodes ) {
  28520. super();
  28521. /**
  28522. * The renderer.
  28523. *
  28524. * @type {Renderer}
  28525. */
  28526. this.renderer = renderer;
  28527. /**
  28528. * Renderer component for managing nodes related logic.
  28529. *
  28530. * @type {Nodes}
  28531. */
  28532. this.nodes = nodes;
  28533. }
  28534. /**
  28535. * Updates the background for the given scene. Depending on how `Scene.background`
  28536. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  28537. * or add a mesh to the render list for rendering the background as a textured plane
  28538. * or skybox.
  28539. *
  28540. * @param {Scene} scene - The scene.
  28541. * @param {RenderList} renderList - The current render list.
  28542. * @param {RenderContext} renderContext - The current render context.
  28543. */
  28544. update( scene, renderList, renderContext ) {
  28545. const renderer = this.renderer;
  28546. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  28547. let forceClear = false;
  28548. if ( background === null ) {
  28549. // no background settings, use clear color configuration from the renderer
  28550. renderer._clearColor.getRGB( _clearColor$1 );
  28551. _clearColor$1.a = renderer._clearColor.a;
  28552. } else if ( background.isColor === true ) {
  28553. // background is an opaque color
  28554. background.getRGB( _clearColor$1 );
  28555. _clearColor$1.a = 1;
  28556. forceClear = true;
  28557. } else if ( background.isNode === true ) {
  28558. const sceneData = this.get( scene );
  28559. const backgroundNode = background;
  28560. _clearColor$1.copy( renderer._clearColor );
  28561. let backgroundMesh = sceneData.backgroundMesh;
  28562. if ( backgroundMesh === undefined ) {
  28563. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  28564. // @TODO: Add Texture2D support using node context
  28565. getUV: () => backgroundRotation.mul( normalWorld ),
  28566. getTextureLevel: () => backgroundBlurriness
  28567. } );
  28568. let viewProj = modelViewProjection;
  28569. viewProj = viewProj.setZ( viewProj.w );
  28570. const nodeMaterial = new NodeMaterial();
  28571. nodeMaterial.name = 'Background.material';
  28572. nodeMaterial.side = BackSide;
  28573. nodeMaterial.depthTest = false;
  28574. nodeMaterial.depthWrite = false;
  28575. nodeMaterial.fog = false;
  28576. nodeMaterial.lights = false;
  28577. nodeMaterial.vertexNode = viewProj;
  28578. nodeMaterial.colorNode = backgroundMeshNode;
  28579. sceneData.backgroundMeshNode = backgroundMeshNode;
  28580. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  28581. backgroundMesh.frustumCulled = false;
  28582. backgroundMesh.name = 'Background.mesh';
  28583. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  28584. this.matrixWorld.copyPosition( camera.matrixWorld );
  28585. };
  28586. }
  28587. const backgroundCacheKey = backgroundNode.getCacheKey();
  28588. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  28589. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  28590. sceneData.backgroundMeshNode.needsUpdate = true;
  28591. backgroundMesh.material.needsUpdate = true;
  28592. sceneData.backgroundCacheKey = backgroundCacheKey;
  28593. }
  28594. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  28595. } else {
  28596. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  28597. }
  28598. //
  28599. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  28600. if ( environmentBlendMode === 'additive' ) {
  28601. _clearColor$1.set( 0, 0, 0, 1 );
  28602. } else if ( environmentBlendMode === 'alpha-blend' ) {
  28603. _clearColor$1.set( 0, 0, 0, 0 );
  28604. }
  28605. //
  28606. if ( renderer.autoClear === true || forceClear === true ) {
  28607. const clearColorValue = renderContext.clearColorValue;
  28608. clearColorValue.r = _clearColor$1.r;
  28609. clearColorValue.g = _clearColor$1.g;
  28610. clearColorValue.b = _clearColor$1.b;
  28611. clearColorValue.a = _clearColor$1.a;
  28612. // premultiply alpha
  28613. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  28614. clearColorValue.r *= clearColorValue.a;
  28615. clearColorValue.g *= clearColorValue.a;
  28616. clearColorValue.b *= clearColorValue.a;
  28617. }
  28618. //
  28619. renderContext.depthClearValue = renderer._clearDepth;
  28620. renderContext.stencilClearValue = renderer._clearStencil;
  28621. renderContext.clearColor = renderer.autoClearColor === true;
  28622. renderContext.clearDepth = renderer.autoClearDepth === true;
  28623. renderContext.clearStencil = renderer.autoClearStencil === true;
  28624. } else {
  28625. renderContext.clearColor = false;
  28626. renderContext.clearDepth = false;
  28627. renderContext.clearStencil = false;
  28628. }
  28629. }
  28630. }
  28631. let _id$6 = 0;
  28632. /**
  28633. * A bind group represents a collection of bindings and thus a collection
  28634. * or resources. Bind groups are assigned to pipelines to provide them
  28635. * with the required resources (like uniform buffers or textures).
  28636. *
  28637. * @private
  28638. */
  28639. class BindGroup {
  28640. /**
  28641. * Constructs a new bind group.
  28642. *
  28643. * @param {string} name - The bind group's name.
  28644. * @param {Array<Binding>} bindings - An array of bindings.
  28645. * @param {number} index - The group index.
  28646. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  28647. */
  28648. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  28649. /**
  28650. * The bind group's name.
  28651. *
  28652. * @type {string}
  28653. */
  28654. this.name = name;
  28655. /**
  28656. * An array of bindings.
  28657. *
  28658. * @type {Array<Binding>}
  28659. */
  28660. this.bindings = bindings;
  28661. /**
  28662. * The group index.
  28663. *
  28664. * @type {number}
  28665. */
  28666. this.index = index;
  28667. /**
  28668. * An array of reference bindings.
  28669. *
  28670. * @type {Array<Binding>}
  28671. */
  28672. this.bindingsReference = bindingsReference;
  28673. /**
  28674. * The group's ID.
  28675. *
  28676. * @type {number}
  28677. */
  28678. this.id = _id$6 ++;
  28679. }
  28680. }
  28681. /**
  28682. * This module represents the state of a node builder after it was
  28683. * used to build the nodes for a render object. The state holds the
  28684. * results of the build for further processing in the renderer.
  28685. *
  28686. * Render objects with identical cache keys share the same node builder state.
  28687. *
  28688. * @private
  28689. */
  28690. class NodeBuilderState {
  28691. /**
  28692. * Constructs a new node builder state.
  28693. *
  28694. * @param {?string} vertexShader - The native vertex shader code.
  28695. * @param {?string} fragmentShader - The native fragment shader code.
  28696. * @param {?string} computeShader - The native compute shader code.
  28697. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  28698. * @param {Array<BindGroup>} bindings - An array of bind groups.
  28699. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  28700. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  28701. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  28702. * @param {NodeMaterialObserver} observer - A node material observer.
  28703. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  28704. */
  28705. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  28706. /**
  28707. * The native vertex shader code.
  28708. *
  28709. * @type {string}
  28710. */
  28711. this.vertexShader = vertexShader;
  28712. /**
  28713. * The native fragment shader code.
  28714. *
  28715. * @type {string}
  28716. */
  28717. this.fragmentShader = fragmentShader;
  28718. /**
  28719. * The native compute shader code.
  28720. *
  28721. * @type {string}
  28722. */
  28723. this.computeShader = computeShader;
  28724. /**
  28725. * An array with transform attribute objects.
  28726. * Only relevant when using compute shaders with WebGL 2.
  28727. *
  28728. * @type {Array<Object>}
  28729. */
  28730. this.transforms = transforms;
  28731. /**
  28732. * An array of node attributes representing
  28733. * the attributes of the shaders.
  28734. *
  28735. * @type {Array<NodeAttribute>}
  28736. */
  28737. this.nodeAttributes = nodeAttributes;
  28738. /**
  28739. * An array of bind groups representing the uniform or storage
  28740. * buffers, texture or samplers of the shader.
  28741. *
  28742. * @type {Array<BindGroup>}
  28743. */
  28744. this.bindings = bindings;
  28745. /**
  28746. * An array of nodes that implement their `update()` method.
  28747. *
  28748. * @type {Array<Node>}
  28749. */
  28750. this.updateNodes = updateNodes;
  28751. /**
  28752. * An array of nodes that implement their `updateBefore()` method.
  28753. *
  28754. * @type {Array<Node>}
  28755. */
  28756. this.updateBeforeNodes = updateBeforeNodes;
  28757. /**
  28758. * An array of nodes that implement their `updateAfter()` method.
  28759. *
  28760. * @type {Array<Node>}
  28761. */
  28762. this.updateAfterNodes = updateAfterNodes;
  28763. /**
  28764. * A node material observer.
  28765. *
  28766. * @type {NodeMaterialObserver}
  28767. */
  28768. this.observer = observer;
  28769. /**
  28770. * How often this state is used by render objects.
  28771. *
  28772. * @type {number}
  28773. */
  28774. this.usedTimes = 0;
  28775. }
  28776. /**
  28777. * This method is used to create a array of bind groups based
  28778. * on the existing bind groups of this state. Shared groups are
  28779. * not cloned.
  28780. *
  28781. * @return {Array<BindGroup>} A array of bind groups.
  28782. */
  28783. createBindings() {
  28784. const bindings = [];
  28785. for ( const instanceGroup of this.bindings ) {
  28786. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  28787. if ( shared !== true ) {
  28788. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28789. bindings.push( bindingsGroup );
  28790. for ( const instanceBinding of instanceGroup.bindings ) {
  28791. bindingsGroup.bindings.push( instanceBinding.clone() );
  28792. }
  28793. } else {
  28794. bindings.push( instanceGroup );
  28795. }
  28796. }
  28797. return bindings;
  28798. }
  28799. }
  28800. /**
  28801. * {@link NodeBuilder} is going to create instances of this class during the build process
  28802. * of nodes. They represent the final shader attributes that are going to be generated
  28803. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28804. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28805. */
  28806. class NodeAttribute {
  28807. /**
  28808. * Constructs a new node attribute.
  28809. *
  28810. * @param {string} name - The name of the attribute.
  28811. * @param {string} type - The type of the attribute.
  28812. * @param {?Node} node - An optional reference to the node.
  28813. */
  28814. constructor( name, type, node = null ) {
  28815. /**
  28816. * This flag can be used for type testing.
  28817. *
  28818. * @type {boolean}
  28819. * @readonly
  28820. * @default true
  28821. */
  28822. this.isNodeAttribute = true;
  28823. /**
  28824. * The name of the attribute.
  28825. *
  28826. * @type {string}
  28827. */
  28828. this.name = name;
  28829. /**
  28830. * The type of the attribute.
  28831. *
  28832. * @type {string}
  28833. */
  28834. this.type = type;
  28835. /**
  28836. * An optional reference to the node.
  28837. *
  28838. * @type {?Node}
  28839. * @default null
  28840. */
  28841. this.node = node;
  28842. }
  28843. }
  28844. /**
  28845. * {@link NodeBuilder} is going to create instances of this class during the build process
  28846. * of nodes. They represent the final shader uniforms that are going to be generated
  28847. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28848. * for this purpose.
  28849. */
  28850. class NodeUniform {
  28851. /**
  28852. * Constructs a new node uniform.
  28853. *
  28854. * @param {string} name - The name of the uniform.
  28855. * @param {string} type - The type of the uniform.
  28856. * @param {UniformNode} node - An reference to the node.
  28857. */
  28858. constructor( name, type, node ) {
  28859. /**
  28860. * This flag can be used for type testing.
  28861. *
  28862. * @type {boolean}
  28863. * @readonly
  28864. * @default true
  28865. */
  28866. this.isNodeUniform = true;
  28867. /**
  28868. * The name of the uniform.
  28869. *
  28870. * @type {string}
  28871. */
  28872. this.name = name;
  28873. /**
  28874. * The type of the uniform.
  28875. *
  28876. * @type {string}
  28877. */
  28878. this.type = type;
  28879. /**
  28880. * An reference to the node.
  28881. *
  28882. * @type {UniformNode}
  28883. */
  28884. this.node = node.getSelf();
  28885. }
  28886. /**
  28887. * The value of the uniform node.
  28888. *
  28889. * @type {any}
  28890. */
  28891. get value() {
  28892. return this.node.value;
  28893. }
  28894. set value( val ) {
  28895. this.node.value = val;
  28896. }
  28897. /**
  28898. * The id of the uniform node.
  28899. *
  28900. * @type {number}
  28901. */
  28902. get id() {
  28903. return this.node.id;
  28904. }
  28905. /**
  28906. * The uniform node's group.
  28907. *
  28908. * @type {UniformGroupNode}
  28909. */
  28910. get groupNode() {
  28911. return this.node.groupNode;
  28912. }
  28913. }
  28914. /**
  28915. * {@link NodeBuilder} is going to create instances of this class during the build process
  28916. * of nodes. They represent the final shader variables that are going to be generated
  28917. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28918. * this purpose.
  28919. */
  28920. class NodeVar {
  28921. /**
  28922. * Constructs a new node variable.
  28923. *
  28924. * @param {string} name - The name of the variable.
  28925. * @param {string} type - The type of the variable.
  28926. * @param {boolean} [readOnly=false] - The read-only flag.
  28927. * @param {?number} [count=null] - The size.
  28928. */
  28929. constructor( name, type, readOnly = false, count = null ) {
  28930. /**
  28931. * This flag can be used for type testing.
  28932. *
  28933. * @type {boolean}
  28934. * @readonly
  28935. * @default true
  28936. */
  28937. this.isNodeVar = true;
  28938. /**
  28939. * The name of the variable.
  28940. *
  28941. * @type {string}
  28942. */
  28943. this.name = name;
  28944. /**
  28945. * The type of the variable.
  28946. *
  28947. * @type {string}
  28948. */
  28949. this.type = type;
  28950. /**
  28951. * The read-only flag.
  28952. *
  28953. * @type {boolean}
  28954. */
  28955. this.readOnly = readOnly;
  28956. /**
  28957. * The size.
  28958. *
  28959. * @type {?number}
  28960. */
  28961. this.count = count;
  28962. }
  28963. }
  28964. /**
  28965. * {@link NodeBuilder} is going to create instances of this class during the build process
  28966. * of nodes. They represent the final shader varyings that are going to be generated
  28967. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28968. * this purpose.
  28969. *
  28970. * @augments NodeVar
  28971. */
  28972. class NodeVarying extends NodeVar {
  28973. /**
  28974. * Constructs a new node varying.
  28975. *
  28976. * @param {string} name - The name of the varying.
  28977. * @param {string} type - The type of the varying.
  28978. */
  28979. constructor( name, type ) {
  28980. super( name, type );
  28981. /**
  28982. * Whether this varying requires interpolation or not. This property can be used
  28983. * to check if the varying can be optimized for a variable.
  28984. *
  28985. * @type {boolean}
  28986. * @default false
  28987. */
  28988. this.needsInterpolation = false;
  28989. /**
  28990. * This flag can be used for type testing.
  28991. *
  28992. * @type {boolean}
  28993. * @readonly
  28994. * @default true
  28995. */
  28996. this.isNodeVarying = true;
  28997. }
  28998. }
  28999. /**
  29000. * {@link NodeBuilder} is going to create instances of this class during the build process
  29001. * of nodes. They represent user-defined, native shader code portions that are going to be
  29002. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  29003. * for this purpose.
  29004. */
  29005. class NodeCode {
  29006. /**
  29007. * Constructs a new code node.
  29008. *
  29009. * @param {string} name - The name of the code.
  29010. * @param {string} type - The node type.
  29011. * @param {string} [code=''] - The native shader code.
  29012. */
  29013. constructor( name, type, code = '' ) {
  29014. /**
  29015. * The name of the code.
  29016. *
  29017. * @type {string}
  29018. */
  29019. this.name = name;
  29020. /**
  29021. * The node type.
  29022. *
  29023. * @type {string}
  29024. */
  29025. this.type = type;
  29026. /**
  29027. * The native shader code.
  29028. *
  29029. * @type {string}
  29030. * @default ''
  29031. */
  29032. this.code = code;
  29033. Object.defineProperty( this, 'isNodeCode', { value: true } );
  29034. }
  29035. }
  29036. let _id$5 = 0;
  29037. /**
  29038. * This utility class is used in {@link NodeBuilder} as an internal
  29039. * cache data structure for node data.
  29040. */
  29041. class NodeCache {
  29042. /**
  29043. * Constructs a new node cache.
  29044. *
  29045. * @param {?NodeCache} parent - A reference to a parent cache.
  29046. */
  29047. constructor( parent = null ) {
  29048. /**
  29049. * The id of the cache.
  29050. *
  29051. * @type {number}
  29052. * @readonly
  29053. */
  29054. this.id = _id$5 ++;
  29055. /**
  29056. * A weak map for managing node data.
  29057. *
  29058. * @type {WeakMap<Node, Object>}
  29059. */
  29060. this.nodesData = new WeakMap();
  29061. /**
  29062. * Reference to a parent node cache.
  29063. *
  29064. * @type {?NodeCache}
  29065. * @default null
  29066. */
  29067. this.parent = parent;
  29068. }
  29069. /**
  29070. * Returns the data for the given node.
  29071. *
  29072. * @param {Node} node - The node.
  29073. * @return {?Object} The data for the node.
  29074. */
  29075. getData( node ) {
  29076. let data = this.nodesData.get( node );
  29077. if ( data === undefined && this.parent !== null ) {
  29078. data = this.parent.getData( node );
  29079. }
  29080. return data;
  29081. }
  29082. /**
  29083. * Sets the data for a given node.
  29084. *
  29085. * @param {Node} node - The node.
  29086. * @param {Object} data - The data that should be cached.
  29087. */
  29088. setData( node, data ) {
  29089. this.nodesData.set( node, data );
  29090. }
  29091. }
  29092. class StructType {
  29093. constructor( name, members ) {
  29094. this.name = name;
  29095. this.members = members;
  29096. this.output = false;
  29097. }
  29098. }
  29099. /**
  29100. * Abstract base class for uniforms.
  29101. *
  29102. * @abstract
  29103. * @private
  29104. */
  29105. class Uniform {
  29106. /**
  29107. * Constructs a new uniform.
  29108. *
  29109. * @param {string} name - The uniform's name.
  29110. * @param {any} value - The uniform's value.
  29111. */
  29112. constructor( name, value ) {
  29113. /**
  29114. * The uniform's name.
  29115. *
  29116. * @type {string}
  29117. */
  29118. this.name = name;
  29119. /**
  29120. * The uniform's value.
  29121. *
  29122. * @type {any}
  29123. */
  29124. this.value = value;
  29125. /**
  29126. * Used to build the uniform buffer according to the STD140 layout.
  29127. * Derived uniforms will set this property to a data type specific
  29128. * value.
  29129. *
  29130. * @type {number}
  29131. */
  29132. this.boundary = 0;
  29133. /**
  29134. * The item size. Derived uniforms will set this property to a data
  29135. * type specific value.
  29136. *
  29137. * @type {number}
  29138. */
  29139. this.itemSize = 0;
  29140. /**
  29141. * This property is set by {@link UniformsGroup} and marks
  29142. * the start position in the uniform buffer.
  29143. *
  29144. * @type {number}
  29145. */
  29146. this.offset = 0;
  29147. }
  29148. /**
  29149. * Sets the uniform's value.
  29150. *
  29151. * @param {any} value - The value to set.
  29152. */
  29153. setValue( value ) {
  29154. this.value = value;
  29155. }
  29156. /**
  29157. * Returns the uniform's value.
  29158. *
  29159. * @return {any} The value.
  29160. */
  29161. getValue() {
  29162. return this.value;
  29163. }
  29164. }
  29165. /**
  29166. * Represents a Number uniform.
  29167. *
  29168. * @private
  29169. * @augments Uniform
  29170. */
  29171. class NumberUniform extends Uniform {
  29172. /**
  29173. * Constructs a new Number uniform.
  29174. *
  29175. * @param {string} name - The uniform's name.
  29176. * @param {number} value - The uniform's value.
  29177. */
  29178. constructor( name, value = 0 ) {
  29179. super( name, value );
  29180. /**
  29181. * This flag can be used for type testing.
  29182. *
  29183. * @type {boolean}
  29184. * @readonly
  29185. * @default true
  29186. */
  29187. this.isNumberUniform = true;
  29188. this.boundary = 4;
  29189. this.itemSize = 1;
  29190. }
  29191. }
  29192. /**
  29193. * Represents a Vector2 uniform.
  29194. *
  29195. * @private
  29196. * @augments Uniform
  29197. */
  29198. class Vector2Uniform extends Uniform {
  29199. /**
  29200. * Constructs a new Number uniform.
  29201. *
  29202. * @param {string} name - The uniform's name.
  29203. * @param {Vector2} value - The uniform's value.
  29204. */
  29205. constructor( name, value = new Vector2() ) {
  29206. super( name, value );
  29207. /**
  29208. * This flag can be used for type testing.
  29209. *
  29210. * @type {boolean}
  29211. * @readonly
  29212. * @default true
  29213. */
  29214. this.isVector2Uniform = true;
  29215. this.boundary = 8;
  29216. this.itemSize = 2;
  29217. }
  29218. }
  29219. /**
  29220. * Represents a Vector3 uniform.
  29221. *
  29222. * @private
  29223. * @augments Uniform
  29224. */
  29225. class Vector3Uniform extends Uniform {
  29226. /**
  29227. * Constructs a new Number uniform.
  29228. *
  29229. * @param {string} name - The uniform's name.
  29230. * @param {Vector3} value - The uniform's value.
  29231. */
  29232. constructor( name, value = new Vector3() ) {
  29233. super( name, value );
  29234. /**
  29235. * This flag can be used for type testing.
  29236. *
  29237. * @type {boolean}
  29238. * @readonly
  29239. * @default true
  29240. */
  29241. this.isVector3Uniform = true;
  29242. this.boundary = 16;
  29243. this.itemSize = 3;
  29244. }
  29245. }
  29246. /**
  29247. * Represents a Vector4 uniform.
  29248. *
  29249. * @private
  29250. * @augments Uniform
  29251. */
  29252. class Vector4Uniform extends Uniform {
  29253. /**
  29254. * Constructs a new Number uniform.
  29255. *
  29256. * @param {string} name - The uniform's name.
  29257. * @param {Vector4} value - The uniform's value.
  29258. */
  29259. constructor( name, value = new Vector4() ) {
  29260. super( name, value );
  29261. /**
  29262. * This flag can be used for type testing.
  29263. *
  29264. * @type {boolean}
  29265. * @readonly
  29266. * @default true
  29267. */
  29268. this.isVector4Uniform = true;
  29269. this.boundary = 16;
  29270. this.itemSize = 4;
  29271. }
  29272. }
  29273. /**
  29274. * Represents a Color uniform.
  29275. *
  29276. * @private
  29277. * @augments Uniform
  29278. */
  29279. class ColorUniform extends Uniform {
  29280. /**
  29281. * Constructs a new Number uniform.
  29282. *
  29283. * @param {string} name - The uniform's name.
  29284. * @param {Color} value - The uniform's value.
  29285. */
  29286. constructor( name, value = new Color() ) {
  29287. super( name, value );
  29288. /**
  29289. * This flag can be used for type testing.
  29290. *
  29291. * @type {boolean}
  29292. * @readonly
  29293. * @default true
  29294. */
  29295. this.isColorUniform = true;
  29296. this.boundary = 16;
  29297. this.itemSize = 3;
  29298. }
  29299. }
  29300. /**
  29301. * Represents a Matrix2 uniform.
  29302. *
  29303. * @private
  29304. * @augments Uniform
  29305. */
  29306. class Matrix2Uniform extends Uniform {
  29307. /**
  29308. * Constructs a new Number uniform.
  29309. *
  29310. * @param {string} name - The uniform's name.
  29311. * @param {Matrix2} value - The uniform's value.
  29312. */
  29313. constructor( name, value = new Matrix2() ) {
  29314. super( name, value );
  29315. /**
  29316. * This flag can be used for type testing.
  29317. *
  29318. * @type {boolean}
  29319. * @readonly
  29320. * @default true
  29321. */
  29322. this.isMatrix2Uniform = true;
  29323. this.boundary = 16;
  29324. this.itemSize = 4;
  29325. }
  29326. }
  29327. /**
  29328. * Represents a Matrix3 uniform.
  29329. *
  29330. * @private
  29331. * @augments Uniform
  29332. */
  29333. class Matrix3Uniform extends Uniform {
  29334. /**
  29335. * Constructs a new Number uniform.
  29336. *
  29337. * @param {string} name - The uniform's name.
  29338. * @param {Matrix3} value - The uniform's value.
  29339. */
  29340. constructor( name, value = new Matrix3() ) {
  29341. super( name, value );
  29342. /**
  29343. * This flag can be used for type testing.
  29344. *
  29345. * @type {boolean}
  29346. * @readonly
  29347. * @default true
  29348. */
  29349. this.isMatrix3Uniform = true;
  29350. this.boundary = 48;
  29351. this.itemSize = 12;
  29352. }
  29353. }
  29354. /**
  29355. * Represents a Matrix4 uniform.
  29356. *
  29357. * @private
  29358. * @augments Uniform
  29359. */
  29360. class Matrix4Uniform extends Uniform {
  29361. /**
  29362. * Constructs a new Number uniform.
  29363. *
  29364. * @param {string} name - The uniform's name.
  29365. * @param {Matrix4} value - The uniform's value.
  29366. */
  29367. constructor( name, value = new Matrix4() ) {
  29368. super( name, value );
  29369. /**
  29370. * This flag can be used for type testing.
  29371. *
  29372. * @type {boolean}
  29373. * @readonly
  29374. * @default true
  29375. */
  29376. this.isMatrix4Uniform = true;
  29377. this.boundary = 64;
  29378. this.itemSize = 16;
  29379. }
  29380. }
  29381. /**
  29382. * A special form of Number uniform binding type.
  29383. * It's value is managed by a node object.
  29384. *
  29385. * @private
  29386. * @augments NumberUniform
  29387. */
  29388. class NumberNodeUniform extends NumberUniform {
  29389. /**
  29390. * Constructs a new node-based Number uniform.
  29391. *
  29392. * @param {NodeUniform} nodeUniform - The node uniform.
  29393. */
  29394. constructor( nodeUniform ) {
  29395. super( nodeUniform.name, nodeUniform.value );
  29396. /**
  29397. * The node uniform.
  29398. *
  29399. * @type {NodeUniform}
  29400. */
  29401. this.nodeUniform = nodeUniform;
  29402. }
  29403. /**
  29404. * Overwritten to return the value of the node uniform.
  29405. *
  29406. * @return {number} The value.
  29407. */
  29408. getValue() {
  29409. return this.nodeUniform.value;
  29410. }
  29411. /**
  29412. * Returns the node uniform data type.
  29413. *
  29414. * @return {string} The data type.
  29415. */
  29416. getType() {
  29417. return this.nodeUniform.type;
  29418. }
  29419. }
  29420. /**
  29421. * A special form of Vector2 uniform binding type.
  29422. * It's value is managed by a node object.
  29423. *
  29424. * @private
  29425. * @augments Vector2Uniform
  29426. */
  29427. class Vector2NodeUniform extends Vector2Uniform {
  29428. /**
  29429. * Constructs a new node-based Vector2 uniform.
  29430. *
  29431. * @param {NodeUniform} nodeUniform - The node uniform.
  29432. */
  29433. constructor( nodeUniform ) {
  29434. super( nodeUniform.name, nodeUniform.value );
  29435. /**
  29436. * The node uniform.
  29437. *
  29438. * @type {NodeUniform}
  29439. */
  29440. this.nodeUniform = nodeUniform;
  29441. }
  29442. /**
  29443. * Overwritten to return the value of the node uniform.
  29444. *
  29445. * @return {Vector2} The value.
  29446. */
  29447. getValue() {
  29448. return this.nodeUniform.value;
  29449. }
  29450. /**
  29451. * Returns the node uniform data type.
  29452. *
  29453. * @return {string} The data type.
  29454. */
  29455. getType() {
  29456. return this.nodeUniform.type;
  29457. }
  29458. }
  29459. /**
  29460. * A special form of Vector3 uniform binding type.
  29461. * It's value is managed by a node object.
  29462. *
  29463. * @private
  29464. * @augments Vector3Uniform
  29465. */
  29466. class Vector3NodeUniform extends Vector3Uniform {
  29467. /**
  29468. * Constructs a new node-based Vector3 uniform.
  29469. *
  29470. * @param {NodeUniform} nodeUniform - The node uniform.
  29471. */
  29472. constructor( nodeUniform ) {
  29473. super( nodeUniform.name, nodeUniform.value );
  29474. /**
  29475. * The node uniform.
  29476. *
  29477. * @type {NodeUniform}
  29478. */
  29479. this.nodeUniform = nodeUniform;
  29480. }
  29481. /**
  29482. * Overwritten to return the value of the node uniform.
  29483. *
  29484. * @return {Vector3} The value.
  29485. */
  29486. getValue() {
  29487. return this.nodeUniform.value;
  29488. }
  29489. /**
  29490. * Returns the node uniform data type.
  29491. *
  29492. * @return {string} The data type.
  29493. */
  29494. getType() {
  29495. return this.nodeUniform.type;
  29496. }
  29497. }
  29498. /**
  29499. * A special form of Vector4 uniform binding type.
  29500. * It's value is managed by a node object.
  29501. *
  29502. * @private
  29503. * @augments Vector4Uniform
  29504. */
  29505. class Vector4NodeUniform extends Vector4Uniform {
  29506. /**
  29507. * Constructs a new node-based Vector4 uniform.
  29508. *
  29509. * @param {NodeUniform} nodeUniform - The node uniform.
  29510. */
  29511. constructor( nodeUniform ) {
  29512. super( nodeUniform.name, nodeUniform.value );
  29513. /**
  29514. * The node uniform.
  29515. *
  29516. * @type {NodeUniform}
  29517. */
  29518. this.nodeUniform = nodeUniform;
  29519. }
  29520. /**
  29521. * Overwritten to return the value of the node uniform.
  29522. *
  29523. * @return {Vector4} The value.
  29524. */
  29525. getValue() {
  29526. return this.nodeUniform.value;
  29527. }
  29528. /**
  29529. * Returns the node uniform data type.
  29530. *
  29531. * @return {string} The data type.
  29532. */
  29533. getType() {
  29534. return this.nodeUniform.type;
  29535. }
  29536. }
  29537. /**
  29538. * A special form of Color uniform binding type.
  29539. * It's value is managed by a node object.
  29540. *
  29541. * @private
  29542. * @augments ColorUniform
  29543. */
  29544. class ColorNodeUniform extends ColorUniform {
  29545. /**
  29546. * Constructs a new node-based Color uniform.
  29547. *
  29548. * @param {NodeUniform} nodeUniform - The node uniform.
  29549. */
  29550. constructor( nodeUniform ) {
  29551. super( nodeUniform.name, nodeUniform.value );
  29552. /**
  29553. * The node uniform.
  29554. *
  29555. * @type {NodeUniform}
  29556. */
  29557. this.nodeUniform = nodeUniform;
  29558. }
  29559. /**
  29560. * Overwritten to return the value of the node uniform.
  29561. *
  29562. * @return {Color} The value.
  29563. */
  29564. getValue() {
  29565. return this.nodeUniform.value;
  29566. }
  29567. /**
  29568. * Returns the node uniform data type.
  29569. *
  29570. * @return {string} The data type.
  29571. */
  29572. getType() {
  29573. return this.nodeUniform.type;
  29574. }
  29575. }
  29576. /**
  29577. * A special form of Matrix2 uniform binding type.
  29578. * It's value is managed by a node object.
  29579. *
  29580. * @private
  29581. * @augments Matrix2Uniform
  29582. */
  29583. class Matrix2NodeUniform extends Matrix2Uniform {
  29584. /**
  29585. * Constructs a new node-based Matrix2 uniform.
  29586. *
  29587. * @param {NodeUniform} nodeUniform - The node uniform.
  29588. */
  29589. constructor( nodeUniform ) {
  29590. super( nodeUniform.name, nodeUniform.value );
  29591. /**
  29592. * The node uniform.
  29593. *
  29594. * @type {NodeUniform}
  29595. */
  29596. this.nodeUniform = nodeUniform;
  29597. }
  29598. /**
  29599. * Overwritten to return the value of the node uniform.
  29600. *
  29601. * @return {Matrix2} The value.
  29602. */
  29603. getValue() {
  29604. return this.nodeUniform.value;
  29605. }
  29606. /**
  29607. * Returns the node uniform data type.
  29608. *
  29609. * @return {string} The data type.
  29610. */
  29611. getType() {
  29612. return this.nodeUniform.type;
  29613. }
  29614. }
  29615. /**
  29616. * A special form of Matrix3 uniform binding type.
  29617. * It's value is managed by a node object.
  29618. *
  29619. * @private
  29620. * @augments Matrix3Uniform
  29621. */
  29622. class Matrix3NodeUniform extends Matrix3Uniform {
  29623. /**
  29624. * Constructs a new node-based Matrix3 uniform.
  29625. *
  29626. * @param {NodeUniform} nodeUniform - The node uniform.
  29627. */
  29628. constructor( nodeUniform ) {
  29629. super( nodeUniform.name, nodeUniform.value );
  29630. /**
  29631. * The node uniform.
  29632. *
  29633. * @type {NodeUniform}
  29634. */
  29635. this.nodeUniform = nodeUniform;
  29636. }
  29637. /**
  29638. * Overwritten to return the value of the node uniform.
  29639. *
  29640. * @return {Matrix3} The value.
  29641. */
  29642. getValue() {
  29643. return this.nodeUniform.value;
  29644. }
  29645. /**
  29646. * Returns the node uniform data type.
  29647. *
  29648. * @return {string} The data type.
  29649. */
  29650. getType() {
  29651. return this.nodeUniform.type;
  29652. }
  29653. }
  29654. /**
  29655. * A special form of Matrix4 uniform binding type.
  29656. * It's value is managed by a node object.
  29657. *
  29658. * @private
  29659. * @augments Matrix4Uniform
  29660. */
  29661. class Matrix4NodeUniform extends Matrix4Uniform {
  29662. /**
  29663. * Constructs a new node-based Matrix4 uniform.
  29664. *
  29665. * @param {NodeUniform} nodeUniform - The node uniform.
  29666. */
  29667. constructor( nodeUniform ) {
  29668. super( nodeUniform.name, nodeUniform.value );
  29669. /**
  29670. * The node uniform.
  29671. *
  29672. * @type {NodeUniform}
  29673. */
  29674. this.nodeUniform = nodeUniform;
  29675. }
  29676. /**
  29677. * Overwritten to return the value of the node uniform.
  29678. *
  29679. * @return {Matrix4} The value.
  29680. */
  29681. getValue() {
  29682. return this.nodeUniform.value;
  29683. }
  29684. /**
  29685. * Returns the node uniform data type.
  29686. *
  29687. * @return {string} The data type.
  29688. */
  29689. getType() {
  29690. return this.nodeUniform.type;
  29691. }
  29692. }
  29693. const LOD_MIN = 4;
  29694. // The standard deviations (radians) associated with the extra mips. These are
  29695. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29696. // geometric shadowing function. These sigma values squared must match the
  29697. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29698. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29699. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29700. // samples and exit early, but not recompile the shader.
  29701. const MAX_SAMPLES = 20;
  29702. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  29703. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  29704. const _clearColor = /*@__PURE__*/ new Color();
  29705. let _oldTarget = null;
  29706. let _oldActiveCubeFace = 0;
  29707. let _oldActiveMipmapLevel = 0;
  29708. // Golden Ratio
  29709. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29710. const INV_PHI = 1 / PHI;
  29711. // Vertices of a dodecahedron (except the opposites, which represent the
  29712. // same axis), used as axis directions evenly spread on a sphere.
  29713. const _axisDirections = [
  29714. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  29715. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29716. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29717. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29718. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29719. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29720. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  29721. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  29722. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  29723. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  29724. ];
  29725. const _origin = /*@__PURE__*/ new Vector3();
  29726. // maps blur materials to their uniforms dictionary
  29727. const _uniformsMap = new WeakMap();
  29728. // WebGPU Face indices
  29729. const _faceLib = [
  29730. 3, 1, 5,
  29731. 0, 4, 2
  29732. ];
  29733. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  29734. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  29735. /**
  29736. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29737. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29738. * blur to be quickly accessed based on material roughness. It is packed into a
  29739. * special CubeUV format that allows us to perform custom interpolation so that
  29740. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29741. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29742. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29743. * higher roughness levels. In this way we maintain resolution to smoothly
  29744. * interpolate diffuse lighting while limiting sampling computation.
  29745. *
  29746. * Paper: Fast, Accurate Image-Based Lighting:
  29747. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  29748. */
  29749. class PMREMGenerator {
  29750. constructor( renderer ) {
  29751. this._renderer = renderer;
  29752. this._pingPongRenderTarget = null;
  29753. this._lodMax = 0;
  29754. this._cubeSize = 0;
  29755. this._lodPlanes = [];
  29756. this._sizeLods = [];
  29757. this._sigmas = [];
  29758. this._lodMeshes = [];
  29759. this._blurMaterial = null;
  29760. this._cubemapMaterial = null;
  29761. this._equirectMaterial = null;
  29762. this._backgroundBox = null;
  29763. }
  29764. get _hasInitialized() {
  29765. return this._renderer.hasInitialized();
  29766. }
  29767. /**
  29768. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29769. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29770. * in radians to be applied to the scene before PMREM generation. Optional near
  29771. * and far planes ensure the scene is rendered in its entirety.
  29772. *
  29773. * @param {Scene} scene - The scene to be captured.
  29774. * @param {number} [sigma=0] - The blur radius in radians.
  29775. * @param {number} [near=0.1] - The near plane distance.
  29776. * @param {number} [far=100] - The far plane distance.
  29777. * @param {Object} [options={}] - The configuration options.
  29778. * @param {number} [options.size=256] - The texture size of the PMREM.
  29779. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  29780. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  29781. * @return {RenderTarget} The resulting PMREM.
  29782. * @see fromSceneAsync
  29783. */
  29784. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  29785. const {
  29786. size = 256,
  29787. position = _origin,
  29788. renderTarget = null,
  29789. } = options;
  29790. this._setSize( size );
  29791. if ( this._hasInitialized === false ) {
  29792. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29793. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29794. options.renderTarget = cubeUVRenderTarget;
  29795. this.fromSceneAsync( scene, sigma, near, far, options );
  29796. return cubeUVRenderTarget;
  29797. }
  29798. _oldTarget = this._renderer.getRenderTarget();
  29799. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29800. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29801. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29802. cubeUVRenderTarget.depthBuffer = true;
  29803. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  29804. if ( sigma > 0 ) {
  29805. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29806. }
  29807. this._applyPMREM( cubeUVRenderTarget );
  29808. this._cleanup( cubeUVRenderTarget );
  29809. return cubeUVRenderTarget;
  29810. }
  29811. /**
  29812. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29813. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29814. * in radians to be applied to the scene before PMREM generation. Optional near
  29815. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29816. * is placed at the origin).
  29817. *
  29818. * @param {Scene} scene - The scene to be captured.
  29819. * @param {number} [sigma=0] - The blur radius in radians.
  29820. * @param {number} [near=0.1] - The near plane distance.
  29821. * @param {number} [far=100] - The far plane distance.
  29822. * @param {Object} [options={}] - The configuration options.
  29823. * @param {number} [options.size=256] - The texture size of the PMREM.
  29824. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  29825. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  29826. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  29827. * @see fromScene
  29828. */
  29829. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  29830. if ( this._hasInitialized === false ) await this._renderer.init();
  29831. return this.fromScene( scene, sigma, near, far, options );
  29832. }
  29833. /**
  29834. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29835. * or HDR. The ideal input image size is 1k (1024 x 512),
  29836. * as this matches best with the 256 x 256 cubemap output.
  29837. *
  29838. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29839. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29840. * @return {RenderTarget} The resulting PMREM.
  29841. * @see fromEquirectangularAsync
  29842. */
  29843. fromEquirectangular( equirectangular, renderTarget = null ) {
  29844. if ( this._hasInitialized === false ) {
  29845. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29846. this._setSizeFromTexture( equirectangular );
  29847. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29848. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29849. return cubeUVRenderTarget;
  29850. }
  29851. return this._fromTexture( equirectangular, renderTarget );
  29852. }
  29853. /**
  29854. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29855. * or HDR. The ideal input image size is 1k (1024 x 512),
  29856. * as this matches best with the 256 x 256 cubemap output.
  29857. *
  29858. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29859. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29860. * @return {Promise<RenderTarget>} The resulting PMREM.
  29861. * @see fromEquirectangular
  29862. */
  29863. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29864. if ( this._hasInitialized === false ) await this._renderer.init();
  29865. return this._fromTexture( equirectangular, renderTarget );
  29866. }
  29867. /**
  29868. * Generates a PMREM from an cubemap texture, which can be either LDR
  29869. * or HDR. The ideal input cube size is 256 x 256,
  29870. * as this matches best with the 256 x 256 cubemap output.
  29871. *
  29872. * @param {Texture} cubemap - The cubemap texture to be converted.
  29873. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29874. * @return {RenderTarget} The resulting PMREM.
  29875. * @see fromCubemapAsync
  29876. */
  29877. fromCubemap( cubemap, renderTarget = null ) {
  29878. if ( this._hasInitialized === false ) {
  29879. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29880. this._setSizeFromTexture( cubemap );
  29881. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29882. this.fromCubemapAsync( cubemap, renderTarget );
  29883. return cubeUVRenderTarget;
  29884. }
  29885. return this._fromTexture( cubemap, renderTarget );
  29886. }
  29887. /**
  29888. * Generates a PMREM from an cubemap texture, which can be either LDR
  29889. * or HDR. The ideal input cube size is 256 x 256,
  29890. * with the 256 x 256 cubemap output.
  29891. *
  29892. * @param {Texture} cubemap - The cubemap texture to be converted.
  29893. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  29894. * @return {Promise<RenderTarget>} The resulting PMREM.
  29895. * @see fromCubemap
  29896. */
  29897. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29898. if ( this._hasInitialized === false ) await this._renderer.init();
  29899. return this._fromTexture( cubemap, renderTarget );
  29900. }
  29901. /**
  29902. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29903. * your texture's network fetch for increased concurrency.
  29904. *
  29905. * @returns {Promise}
  29906. */
  29907. async compileCubemapShader() {
  29908. if ( this._cubemapMaterial === null ) {
  29909. this._cubemapMaterial = _getCubemapMaterial();
  29910. await this._compileMaterial( this._cubemapMaterial );
  29911. }
  29912. }
  29913. /**
  29914. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29915. * your texture's network fetch for increased concurrency.
  29916. *
  29917. * @returns {Promise}
  29918. */
  29919. async compileEquirectangularShader() {
  29920. if ( this._equirectMaterial === null ) {
  29921. this._equirectMaterial = _getEquirectMaterial();
  29922. await this._compileMaterial( this._equirectMaterial );
  29923. }
  29924. }
  29925. /**
  29926. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29927. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29928. * one of them will cause any others to also become unusable.
  29929. */
  29930. dispose() {
  29931. this._dispose();
  29932. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29933. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29934. if ( this._backgroundBox !== null ) {
  29935. this._backgroundBox.geometry.dispose();
  29936. this._backgroundBox.material.dispose();
  29937. }
  29938. }
  29939. // private interface
  29940. _setSizeFromTexture( texture ) {
  29941. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29942. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29943. } else { // Equirectangular
  29944. this._setSize( texture.image.width / 4 );
  29945. }
  29946. }
  29947. _setSize( cubeSize ) {
  29948. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29949. this._cubeSize = Math.pow( 2, this._lodMax );
  29950. }
  29951. _dispose() {
  29952. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29953. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29954. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29955. this._lodPlanes[ i ].dispose();
  29956. }
  29957. }
  29958. _cleanup( outputTarget ) {
  29959. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29960. outputTarget.scissorTest = false;
  29961. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29962. }
  29963. _fromTexture( texture, renderTarget ) {
  29964. this._setSizeFromTexture( texture );
  29965. _oldTarget = this._renderer.getRenderTarget();
  29966. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29967. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29968. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29969. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29970. this._applyPMREM( cubeUVRenderTarget );
  29971. this._cleanup( cubeUVRenderTarget );
  29972. return cubeUVRenderTarget;
  29973. }
  29974. _allocateTargets() {
  29975. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29976. const height = 4 * this._cubeSize;
  29977. const params = {
  29978. magFilter: LinearFilter,
  29979. minFilter: LinearFilter,
  29980. generateMipmaps: false,
  29981. type: HalfFloatType,
  29982. format: RGBAFormat,
  29983. colorSpace: LinearSRGBColorSpace,
  29984. //depthBuffer: false
  29985. };
  29986. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29987. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29988. if ( this._pingPongRenderTarget !== null ) {
  29989. this._dispose();
  29990. }
  29991. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29992. const { _lodMax } = this;
  29993. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29994. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29995. }
  29996. return cubeUVRenderTarget;
  29997. }
  29998. async _compileMaterial( material ) {
  29999. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  30000. await this._renderer.compile( tmpMesh, _flatCamera );
  30001. }
  30002. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  30003. const cubeCamera = _cubeCamera;
  30004. cubeCamera.near = near;
  30005. cubeCamera.far = far;
  30006. // px, py, pz, nx, ny, nz
  30007. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  30008. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  30009. const renderer = this._renderer;
  30010. const originalAutoClear = renderer.autoClear;
  30011. renderer.getClearColor( _clearColor );
  30012. renderer.autoClear = false;
  30013. let backgroundBox = this._backgroundBox;
  30014. if ( backgroundBox === null ) {
  30015. const backgroundMaterial = new MeshBasicMaterial( {
  30016. name: 'PMREM.Background',
  30017. side: BackSide,
  30018. depthWrite: false,
  30019. depthTest: false
  30020. } );
  30021. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  30022. }
  30023. let useSolidColor = false;
  30024. const background = scene.background;
  30025. if ( background ) {
  30026. if ( background.isColor ) {
  30027. backgroundBox.material.color.copy( background );
  30028. scene.background = null;
  30029. useSolidColor = true;
  30030. }
  30031. } else {
  30032. backgroundBox.material.color.copy( _clearColor );
  30033. useSolidColor = true;
  30034. }
  30035. renderer.setRenderTarget( cubeUVRenderTarget );
  30036. renderer.clear();
  30037. if ( useSolidColor ) {
  30038. renderer.render( backgroundBox, cubeCamera );
  30039. }
  30040. for ( let i = 0; i < 6; i ++ ) {
  30041. const col = i % 3;
  30042. if ( col === 0 ) {
  30043. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30044. cubeCamera.position.set( position.x, position.y, position.z );
  30045. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  30046. } else if ( col === 1 ) {
  30047. cubeCamera.up.set( 0, 0, upSign[ i ] );
  30048. cubeCamera.position.set( position.x, position.y, position.z );
  30049. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  30050. } else {
  30051. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30052. cubeCamera.position.set( position.x, position.y, position.z );
  30053. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  30054. }
  30055. const size = this._cubeSize;
  30056. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  30057. renderer.render( scene, cubeCamera );
  30058. }
  30059. renderer.autoClear = originalAutoClear;
  30060. scene.background = background;
  30061. }
  30062. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  30063. const renderer = this._renderer;
  30064. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  30065. if ( isCubeTexture ) {
  30066. if ( this._cubemapMaterial === null ) {
  30067. this._cubemapMaterial = _getCubemapMaterial( texture );
  30068. }
  30069. } else {
  30070. if ( this._equirectMaterial === null ) {
  30071. this._equirectMaterial = _getEquirectMaterial( texture );
  30072. }
  30073. }
  30074. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  30075. material.fragmentNode.value = texture;
  30076. const mesh = this._lodMeshes[ 0 ];
  30077. mesh.material = material;
  30078. const size = this._cubeSize;
  30079. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  30080. renderer.setRenderTarget( cubeUVRenderTarget );
  30081. renderer.render( mesh, _flatCamera );
  30082. }
  30083. _applyPMREM( cubeUVRenderTarget ) {
  30084. const renderer = this._renderer;
  30085. const autoClear = renderer.autoClear;
  30086. renderer.autoClear = false;
  30087. const n = this._lodPlanes.length;
  30088. for ( let i = 1; i < n; i ++ ) {
  30089. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  30090. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  30091. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  30092. }
  30093. renderer.autoClear = autoClear;
  30094. }
  30095. /**
  30096. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  30097. * vertically and horizontally, but this breaks down on a cube. Here we apply
  30098. * the blur latitudinally (around the poles), and then longitudinally (towards
  30099. * the poles) to approximate the orthogonally-separable blur. It is least
  30100. * accurate at the poles, but still does a decent job.
  30101. *
  30102. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  30103. * @param {number} lodIn - The input level-of-detail.
  30104. * @param {number} lodOut - The output level-of-detail.
  30105. * @param {number} sigma - The blur radius in radians.
  30106. * @param {Vector3} [poleAxis] - The pole axis.
  30107. */
  30108. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  30109. const pingPongRenderTarget = this._pingPongRenderTarget;
  30110. this._halfBlur(
  30111. cubeUVRenderTarget,
  30112. pingPongRenderTarget,
  30113. lodIn,
  30114. lodOut,
  30115. sigma,
  30116. 'latitudinal',
  30117. poleAxis );
  30118. this._halfBlur(
  30119. pingPongRenderTarget,
  30120. cubeUVRenderTarget,
  30121. lodOut,
  30122. lodOut,
  30123. sigma,
  30124. 'longitudinal',
  30125. poleAxis );
  30126. }
  30127. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  30128. const renderer = this._renderer;
  30129. const blurMaterial = this._blurMaterial;
  30130. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  30131. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  30132. }
  30133. // Number of standard deviations at which to cut off the discrete approximation.
  30134. const STANDARD_DEVIATIONS = 3;
  30135. const blurMesh = this._lodMeshes[ lodOut ];
  30136. blurMesh.material = blurMaterial;
  30137. const blurUniforms = _uniformsMap.get( blurMaterial );
  30138. const pixels = this._sizeLods[ lodIn ] - 1;
  30139. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  30140. const sigmaPixels = sigmaRadians / radiansPerPixel;
  30141. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  30142. if ( samples > MAX_SAMPLES ) {
  30143. console.warn( `sigmaRadians, ${
  30144. sigmaRadians}, is too large and will clip, as it requested ${
  30145. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  30146. }
  30147. const weights = [];
  30148. let sum = 0;
  30149. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  30150. const x = i / sigmaPixels;
  30151. const weight = Math.exp( - x * x / 2 );
  30152. weights.push( weight );
  30153. if ( i === 0 ) {
  30154. sum += weight;
  30155. } else if ( i < samples ) {
  30156. sum += 2 * weight;
  30157. }
  30158. }
  30159. for ( let i = 0; i < weights.length; i ++ ) {
  30160. weights[ i ] = weights[ i ] / sum;
  30161. }
  30162. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  30163. blurUniforms.envMap.value = targetIn.texture;
  30164. blurUniforms.samples.value = samples;
  30165. blurUniforms.weights.array = weights;
  30166. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  30167. if ( poleAxis ) {
  30168. blurUniforms.poleAxis.value = poleAxis;
  30169. }
  30170. const { _lodMax } = this;
  30171. blurUniforms.dTheta.value = radiansPerPixel;
  30172. blurUniforms.mipInt.value = _lodMax - lodIn;
  30173. const outputSize = this._sizeLods[ lodOut ];
  30174. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  30175. const y = 4 * ( this._cubeSize - outputSize );
  30176. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  30177. renderer.setRenderTarget( targetOut );
  30178. renderer.render( blurMesh, _flatCamera );
  30179. }
  30180. }
  30181. function _createPlanes( lodMax ) {
  30182. const lodPlanes = [];
  30183. const sizeLods = [];
  30184. const sigmas = [];
  30185. const lodMeshes = [];
  30186. let lod = lodMax;
  30187. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  30188. for ( let i = 0; i < totalLods; i ++ ) {
  30189. const sizeLod = Math.pow( 2, lod );
  30190. sizeLods.push( sizeLod );
  30191. let sigma = 1.0 / sizeLod;
  30192. if ( i > lodMax - LOD_MIN ) {
  30193. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  30194. } else if ( i === 0 ) {
  30195. sigma = 0;
  30196. }
  30197. sigmas.push( sigma );
  30198. const texelSize = 1.0 / ( sizeLod - 2 );
  30199. const min = - texelSize;
  30200. const max = 1 + texelSize;
  30201. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  30202. const cubeFaces = 6;
  30203. const vertices = 6;
  30204. const positionSize = 3;
  30205. const uvSize = 2;
  30206. const faceIndexSize = 1;
  30207. const position = new Float32Array( positionSize * vertices * cubeFaces );
  30208. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  30209. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  30210. for ( let face = 0; face < cubeFaces; face ++ ) {
  30211. const x = ( face % 3 ) * 2 / 3 - 1;
  30212. const y = face > 2 ? 0 : -1;
  30213. const coordinates = [
  30214. x, y, 0,
  30215. x + 2 / 3, y, 0,
  30216. x + 2 / 3, y + 1, 0,
  30217. x, y, 0,
  30218. x + 2 / 3, y + 1, 0,
  30219. x, y + 1, 0
  30220. ];
  30221. const faceIdx = _faceLib[ face ];
  30222. position.set( coordinates, positionSize * vertices * faceIdx );
  30223. uv.set( uv1, uvSize * vertices * faceIdx );
  30224. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  30225. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  30226. }
  30227. const planes = new BufferGeometry();
  30228. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  30229. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  30230. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  30231. lodPlanes.push( planes );
  30232. lodMeshes.push( new Mesh( planes, null ) );
  30233. if ( lod > LOD_MIN ) {
  30234. lod --;
  30235. }
  30236. }
  30237. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  30238. }
  30239. function _createRenderTarget( width, height, params ) {
  30240. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  30241. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  30242. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  30243. cubeUVRenderTarget.texture.isPMREMTexture = true;
  30244. cubeUVRenderTarget.scissorTest = true;
  30245. return cubeUVRenderTarget;
  30246. }
  30247. function _setViewport( target, x, y, width, height ) {
  30248. target.viewport.set( x, y, width, height );
  30249. target.scissor.set( x, y, width, height );
  30250. }
  30251. function _getMaterial( type ) {
  30252. const material = new NodeMaterial();
  30253. material.depthTest = false;
  30254. material.depthWrite = false;
  30255. material.blending = NoBlending;
  30256. material.name = `PMREM_${ type }`;
  30257. return material;
  30258. }
  30259. function _getBlurShader( lodMax, width, height ) {
  30260. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  30261. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  30262. const dTheta = uniform( 0 );
  30263. const n = float( MAX_SAMPLES );
  30264. const latitudinal = uniform( 0 ); // false, bool
  30265. const samples = uniform( 1 ); // int
  30266. const envMap = texture( null );
  30267. const mipInt = uniform( 0 ); // int
  30268. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  30269. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  30270. const CUBEUV_MAX_MIP = float( lodMax );
  30271. const materialUniforms = {
  30272. n,
  30273. latitudinal,
  30274. weights,
  30275. poleAxis,
  30276. outputDirection: _outputDirection,
  30277. dTheta,
  30278. samples,
  30279. envMap,
  30280. mipInt,
  30281. CUBEUV_TEXEL_WIDTH,
  30282. CUBEUV_TEXEL_HEIGHT,
  30283. CUBEUV_MAX_MIP
  30284. };
  30285. const material = _getMaterial( 'blur' );
  30286. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  30287. _uniformsMap.set( material, materialUniforms );
  30288. return material;
  30289. }
  30290. function _getCubemapMaterial( envTexture ) {
  30291. const material = _getMaterial( 'cubemap' );
  30292. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  30293. return material;
  30294. }
  30295. function _getEquirectMaterial( envTexture ) {
  30296. const material = _getMaterial( 'equirect' );
  30297. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  30298. return material;
  30299. }
  30300. const rendererCache = new WeakMap();
  30301. const typeFromArray = new Map( [
  30302. [ Int8Array, 'int' ],
  30303. [ Int16Array, 'int' ],
  30304. [ Int32Array, 'int' ],
  30305. [ Uint8Array, 'uint' ],
  30306. [ Uint16Array, 'uint' ],
  30307. [ Uint32Array, 'uint' ],
  30308. [ Float32Array, 'float' ]
  30309. ] );
  30310. const toFloat = ( value ) => {
  30311. if ( /e/g.test( value ) ) {
  30312. return String( value ).replace( /\+/g, '' );
  30313. } else {
  30314. value = Number( value );
  30315. return value + ( value % 1 ? '' : '.0' );
  30316. }
  30317. };
  30318. /**
  30319. * Base class for builders which generate a shader program based
  30320. * on a 3D object and its node material definition.
  30321. */
  30322. class NodeBuilder {
  30323. /**
  30324. * Constructs a new node builder.
  30325. *
  30326. * @param {Object3D} object - The 3D object.
  30327. * @param {Renderer} renderer - The current renderer.
  30328. * @param {NodeParser} parser - A reference to a node parser.
  30329. */
  30330. constructor( object, renderer, parser ) {
  30331. /**
  30332. * The 3D object.
  30333. *
  30334. * @type {Object3D}
  30335. */
  30336. this.object = object;
  30337. /**
  30338. * The material of the 3D object.
  30339. *
  30340. * @type {?Material}
  30341. */
  30342. this.material = ( object && object.material ) || null;
  30343. /**
  30344. * The geometry of the 3D object.
  30345. *
  30346. * @type {?BufferGeometry}
  30347. */
  30348. this.geometry = ( object && object.geometry ) || null;
  30349. /**
  30350. * The current renderer.
  30351. *
  30352. * @type {Renderer}
  30353. */
  30354. this.renderer = renderer;
  30355. /**
  30356. * A reference to a node parser.
  30357. *
  30358. * @type {NodeParser}
  30359. */
  30360. this.parser = parser;
  30361. /**
  30362. * The scene the 3D object belongs to.
  30363. *
  30364. * @type {?Scene}
  30365. * @default null
  30366. */
  30367. this.scene = null;
  30368. /**
  30369. * The camera the 3D object is rendered with.
  30370. *
  30371. * @type {?Camera}
  30372. * @default null
  30373. */
  30374. this.camera = null;
  30375. /**
  30376. * A list of all nodes the builder is processing
  30377. * for this 3D object.
  30378. *
  30379. * @type {Array<Node>}
  30380. */
  30381. this.nodes = [];
  30382. /**
  30383. * A list of all sequential nodes.
  30384. *
  30385. * @type {Array<Node>}
  30386. */
  30387. this.sequentialNodes = [];
  30388. /**
  30389. * A list of all nodes which {@link Node#update} method should be executed.
  30390. *
  30391. * @type {Array<Node>}
  30392. */
  30393. this.updateNodes = [];
  30394. /**
  30395. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  30396. *
  30397. * @type {Array<Node>}
  30398. */
  30399. this.updateBeforeNodes = [];
  30400. /**
  30401. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  30402. *
  30403. * @type {Array<Node>}
  30404. */
  30405. this.updateAfterNodes = [];
  30406. /**
  30407. * A dictionary that assigns each node to a unique hash.
  30408. *
  30409. * @type {Object<number,Node>}
  30410. */
  30411. this.hashNodes = {};
  30412. /**
  30413. * A reference to a node material observer.
  30414. *
  30415. * @type {?NodeMaterialObserver}
  30416. * @default null
  30417. */
  30418. this.observer = null;
  30419. /**
  30420. * A reference to the current lights node.
  30421. *
  30422. * @type {?LightsNode}
  30423. * @default null
  30424. */
  30425. this.lightsNode = null;
  30426. /**
  30427. * A reference to the current environment node.
  30428. *
  30429. * @type {?Node}
  30430. * @default null
  30431. */
  30432. this.environmentNode = null;
  30433. /**
  30434. * A reference to the current fog node.
  30435. *
  30436. * @type {?FogNode}
  30437. * @default null
  30438. */
  30439. this.fogNode = null;
  30440. /**
  30441. * The current clipping context.
  30442. *
  30443. * @type {?ClippingContext}
  30444. */
  30445. this.clippingContext = null;
  30446. /**
  30447. * The generated vertex shader.
  30448. *
  30449. * @type {?string}
  30450. */
  30451. this.vertexShader = null;
  30452. /**
  30453. * The generated fragment shader.
  30454. *
  30455. * @type {?string}
  30456. */
  30457. this.fragmentShader = null;
  30458. /**
  30459. * The generated compute shader.
  30460. *
  30461. * @type {?string}
  30462. */
  30463. this.computeShader = null;
  30464. /**
  30465. * Nodes used in the primary flow of code generation.
  30466. *
  30467. * @type {Object<string,Array<Node>>}
  30468. */
  30469. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30470. /**
  30471. * Nodes code from `.flowNodes`.
  30472. *
  30473. * @type {Object<string,string>}
  30474. */
  30475. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30476. /**
  30477. * This dictionary holds the node uniforms of the builder.
  30478. * The uniforms are maintained in an array for each shader stage.
  30479. *
  30480. * @type {Object}
  30481. */
  30482. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30483. /**
  30484. * This dictionary holds the output structs of the builder.
  30485. * The structs are maintained in an array for each shader stage.
  30486. *
  30487. * @type {Object}
  30488. */
  30489. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30490. /**
  30491. * This dictionary holds the bindings for each shader stage.
  30492. *
  30493. * @type {Object}
  30494. */
  30495. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30496. /**
  30497. * This dictionary maintains the binding indices per bind group.
  30498. *
  30499. * @type {Object}
  30500. */
  30501. this.bindingsIndexes = {};
  30502. /**
  30503. * Reference to the array of bind groups.
  30504. *
  30505. * @type {?Array<BindGroup>}
  30506. */
  30507. this.bindGroups = null;
  30508. /**
  30509. * This array holds the node attributes of this builder
  30510. * created via {@link AttributeNode}.
  30511. *
  30512. * @type {Array<NodeAttribute>}
  30513. */
  30514. this.attributes = [];
  30515. /**
  30516. * This array holds the node attributes of this builder
  30517. * created via {@link BufferAttributeNode}.
  30518. *
  30519. * @type {Array<NodeAttribute>}
  30520. */
  30521. this.bufferAttributes = [];
  30522. /**
  30523. * This array holds the node varyings of this builder.
  30524. *
  30525. * @type {Array<NodeVarying>}
  30526. */
  30527. this.varyings = [];
  30528. /**
  30529. * This dictionary holds the (native) node codes of this builder.
  30530. * The codes are maintained in an array for each shader stage.
  30531. *
  30532. * @type {Object<string,Array<NodeCode>>}
  30533. */
  30534. this.codes = {};
  30535. /**
  30536. * This dictionary holds the node variables of this builder.
  30537. * The variables are maintained in an array for each shader stage.
  30538. *
  30539. * @type {Object<string,Array<NodeVar>>}
  30540. */
  30541. this.vars = {};
  30542. /**
  30543. * Current code flow.
  30544. * All code generated in this stack will be stored in `.flow`.
  30545. *
  30546. * @type {{code: string}}
  30547. */
  30548. this.flow = { code: '' };
  30549. /**
  30550. * A chain of nodes.
  30551. * Used to check recursive calls in node-graph.
  30552. *
  30553. * @type {Array<Node>}
  30554. */
  30555. this.chaining = [];
  30556. /**
  30557. * The current stack.
  30558. * This reflects the current process in the code block hierarchy,
  30559. * it is useful to know if the current process is inside a conditional for example.
  30560. *
  30561. * @type {StackNode}
  30562. */
  30563. this.stack = stack();
  30564. /**
  30565. * List of stack nodes.
  30566. * The current stack hierarchy is stored in an array.
  30567. *
  30568. * @type {Array<StackNode>}
  30569. */
  30570. this.stacks = [];
  30571. /**
  30572. * A tab value. Used for shader string generation.
  30573. *
  30574. * @type {string}
  30575. * @default '\t'
  30576. */
  30577. this.tab = '\t';
  30578. /**
  30579. * Reference to the current function node.
  30580. *
  30581. * @type {?FunctionNode}
  30582. * @default null
  30583. */
  30584. this.currentFunctionNode = null;
  30585. /**
  30586. * The builder's context.
  30587. *
  30588. * @type {Object}
  30589. */
  30590. this.context = {
  30591. material: this.material
  30592. };
  30593. /**
  30594. * The builder's cache.
  30595. *
  30596. * @type {NodeCache}
  30597. */
  30598. this.cache = new NodeCache();
  30599. /**
  30600. * Since the {@link NodeBuilder#cache} might be temporarily
  30601. * overwritten by other caches, this member retains the reference
  30602. * to the builder's own cache.
  30603. *
  30604. * @type {NodeCache}
  30605. * @default this.cache
  30606. */
  30607. this.globalCache = this.cache;
  30608. this.flowsData = new WeakMap();
  30609. /**
  30610. * The current shader stage.
  30611. *
  30612. * @type {?('vertex'|'fragment'|'compute'|'any')}
  30613. */
  30614. this.shaderStage = null;
  30615. /**
  30616. * The current build stage.
  30617. *
  30618. * @type {?('setup'|'analyze'|'generate')}
  30619. */
  30620. this.buildStage = null;
  30621. /**
  30622. * Whether comparison in shader code are generated with methods or not.
  30623. *
  30624. * @type {boolean}
  30625. * @default false
  30626. */
  30627. this.useComparisonMethod = false;
  30628. }
  30629. /**
  30630. * Returns the bind groups of the current renderer.
  30631. *
  30632. * @return {ChainMap} The cache.
  30633. */
  30634. getBindGroupsCache() {
  30635. let bindGroupsCache = rendererCache.get( this.renderer );
  30636. if ( bindGroupsCache === undefined ) {
  30637. bindGroupsCache = new ChainMap();
  30638. rendererCache.set( this.renderer, bindGroupsCache );
  30639. }
  30640. return bindGroupsCache;
  30641. }
  30642. /**
  30643. * Factory method for creating an instance of {@link RenderTarget} with the given
  30644. * dimensions and options.
  30645. *
  30646. * @param {number} width - The width of the render target.
  30647. * @param {number} height - The height of the render target.
  30648. * @param {Object} options - The options of the render target.
  30649. * @return {RenderTarget} The render target.
  30650. */
  30651. createRenderTarget( width, height, options ) {
  30652. return new RenderTarget( width, height, options );
  30653. }
  30654. /**
  30655. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  30656. * dimensions and options.
  30657. *
  30658. * @param {number} size - The size of the cube render target.
  30659. * @param {Object} options - The options of the cube render target.
  30660. * @return {CubeRenderTarget} The cube render target.
  30661. */
  30662. createCubeRenderTarget( size, options ) {
  30663. return new CubeRenderTarget( size, options );
  30664. }
  30665. /**
  30666. * Factory method for creating an instance of {@link PMREMGenerator}.
  30667. *
  30668. * @return {PMREMGenerator} The PMREM generator.
  30669. */
  30670. createPMREMGenerator() {
  30671. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30672. return new PMREMGenerator( this.renderer );
  30673. }
  30674. /**
  30675. * Whether the given node is included in the internal array of nodes or not.
  30676. *
  30677. * @param {Node} node - The node to test.
  30678. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  30679. */
  30680. includes( node ) {
  30681. return this.nodes.includes( node );
  30682. }
  30683. /**
  30684. * Returns the output struct name which is required by
  30685. * {@link OutputStructNode}.
  30686. *
  30687. * @abstract
  30688. * @return {string} The name of the output struct.
  30689. */
  30690. getOutputStructName() {}
  30691. /**
  30692. * Returns a bind group for the given group name and binding.
  30693. *
  30694. * @private
  30695. * @param {string} groupName - The group name.
  30696. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  30697. * @return {BindGroup} The bind group
  30698. */
  30699. _getBindGroup( groupName, bindings ) {
  30700. const bindGroupsCache = this.getBindGroupsCache();
  30701. //
  30702. const bindingsArray = [];
  30703. let sharedGroup = true;
  30704. for ( const binding of bindings ) {
  30705. bindingsArray.push( binding );
  30706. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30707. }
  30708. //
  30709. let bindGroup;
  30710. if ( sharedGroup ) {
  30711. bindGroup = bindGroupsCache.get( bindingsArray );
  30712. if ( bindGroup === undefined ) {
  30713. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30714. bindGroupsCache.set( bindingsArray, bindGroup );
  30715. }
  30716. } else {
  30717. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30718. }
  30719. return bindGroup;
  30720. }
  30721. /**
  30722. * Returns an array of node uniform groups for the given group name and shader stage.
  30723. *
  30724. * @param {string} groupName - The group name.
  30725. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30726. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  30727. */
  30728. getBindGroupArray( groupName, shaderStage ) {
  30729. const bindings = this.bindings[ shaderStage ];
  30730. let bindGroup = bindings[ groupName ];
  30731. if ( bindGroup === undefined ) {
  30732. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  30733. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  30734. }
  30735. bindings[ groupName ] = bindGroup = [];
  30736. }
  30737. return bindGroup;
  30738. }
  30739. /**
  30740. * Returns a list bindings of all shader stages separated by groups.
  30741. *
  30742. * @return {Array<BindGroup>} The list of bindings.
  30743. */
  30744. getBindings() {
  30745. let bindingsGroups = this.bindGroups;
  30746. if ( bindingsGroups === null ) {
  30747. const groups = {};
  30748. const bindings = this.bindings;
  30749. for ( const shaderStage of shaderStages ) {
  30750. for ( const groupName in bindings[ shaderStage ] ) {
  30751. const uniforms = bindings[ shaderStage ][ groupName ];
  30752. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  30753. groupUniforms.push( ...uniforms );
  30754. }
  30755. }
  30756. bindingsGroups = [];
  30757. for ( const groupName in groups ) {
  30758. const group = groups[ groupName ];
  30759. const bindingsGroup = this._getBindGroup( groupName, group );
  30760. bindingsGroups.push( bindingsGroup );
  30761. }
  30762. this.bindGroups = bindingsGroups;
  30763. }
  30764. return bindingsGroups;
  30765. }
  30766. /**
  30767. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  30768. */
  30769. sortBindingGroups() {
  30770. const bindingsGroups = this.getBindings();
  30771. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30772. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30773. const bindingGroup = bindingsGroups[ i ];
  30774. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30775. bindingGroup.index = i;
  30776. }
  30777. }
  30778. /**
  30779. * The builder maintains each node in a hash-based dictionary.
  30780. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30781. *
  30782. * @param {Node} node - The node to add.
  30783. * @param {number} hash - The hash of the node.
  30784. */
  30785. setHashNode( node, hash ) {
  30786. this.hashNodes[ hash ] = node;
  30787. }
  30788. /**
  30789. * Adds a node to this builder.
  30790. *
  30791. * @param {Node} node - The node to add.
  30792. */
  30793. addNode( node ) {
  30794. if ( this.nodes.includes( node ) === false ) {
  30795. this.nodes.push( node );
  30796. this.setHashNode( node, node.getHash( this ) );
  30797. }
  30798. }
  30799. /**
  30800. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30801. * and need to follow a certain sequence in the calls to work correctly.
  30802. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30803. *
  30804. * @param {Node} node - The node to add.
  30805. */
  30806. addSequentialNode( node ) {
  30807. if ( this.sequentialNodes.includes( node ) === false ) {
  30808. this.sequentialNodes.push( node );
  30809. }
  30810. }
  30811. /**
  30812. * Checks the update types of nodes
  30813. */
  30814. buildUpdateNodes() {
  30815. for ( const node of this.nodes ) {
  30816. const updateType = node.getUpdateType();
  30817. if ( updateType !== NodeUpdateType.NONE ) {
  30818. this.updateNodes.push( node.getSelf() );
  30819. }
  30820. }
  30821. for ( const node of this.sequentialNodes ) {
  30822. const updateBeforeType = node.getUpdateBeforeType();
  30823. const updateAfterType = node.getUpdateAfterType();
  30824. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30825. this.updateBeforeNodes.push( node.getSelf() );
  30826. }
  30827. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30828. this.updateAfterNodes.push( node.getSelf() );
  30829. }
  30830. }
  30831. }
  30832. /**
  30833. * A reference the current node which is the
  30834. * last node in the chain of nodes.
  30835. *
  30836. * @type {Node}
  30837. */
  30838. get currentNode() {
  30839. return this.chaining[ this.chaining.length - 1 ];
  30840. }
  30841. /**
  30842. * Whether the given texture is filtered or not.
  30843. *
  30844. * @param {Texture} texture - The texture to check.
  30845. * @return {boolean} Whether the given texture is filtered or not.
  30846. */
  30847. isFilteredTexture( texture ) {
  30848. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30849. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30850. }
  30851. /**
  30852. * Adds the given node to the internal node chain.
  30853. * This is used to check recursive calls in node-graph.
  30854. *
  30855. * @param {Node} node - The node to add.
  30856. */
  30857. addChain( node ) {
  30858. /*
  30859. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30860. console.warn( 'Recursive node: ', node );
  30861. }
  30862. */
  30863. this.chaining.push( node );
  30864. }
  30865. /**
  30866. * Removes the given node from the internal node chain.
  30867. *
  30868. * @param {Node} node - The node to remove.
  30869. */
  30870. removeChain( node ) {
  30871. const lastChain = this.chaining.pop();
  30872. if ( lastChain !== node ) {
  30873. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30874. }
  30875. }
  30876. /**
  30877. * Returns the native shader method name for a given generic name. E.g.
  30878. * the method name `textureDimensions` matches the WGSL name but must be
  30879. * resolved to `textureSize` in GLSL.
  30880. *
  30881. * @abstract
  30882. * @param {string} method - The method name to resolve.
  30883. * @return {string} The resolved method name.
  30884. */
  30885. getMethod( method ) {
  30886. return method;
  30887. }
  30888. /**
  30889. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30890. *
  30891. * @param {number} hash - The hash of the node.
  30892. * @return {Node} The found node.
  30893. */
  30894. getNodeFromHash( hash ) {
  30895. return this.hashNodes[ hash ];
  30896. }
  30897. /**
  30898. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30899. *
  30900. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30901. * @param {Node} node - The node to add.
  30902. * @return {Node} The node.
  30903. */
  30904. addFlow( shaderStage, node ) {
  30905. this.flowNodes[ shaderStage ].push( node );
  30906. return node;
  30907. }
  30908. /**
  30909. * Sets builder's context.
  30910. *
  30911. * @param {Object} context - The context to set.
  30912. */
  30913. setContext( context ) {
  30914. this.context = context;
  30915. }
  30916. /**
  30917. * Returns the builder's current context.
  30918. *
  30919. * @return {Object} The builder's current context.
  30920. */
  30921. getContext() {
  30922. return this.context;
  30923. }
  30924. /**
  30925. * Gets a context used in shader construction that can be shared across different materials.
  30926. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30927. *
  30928. * @return {Object} The builder's current context without material.
  30929. */
  30930. getSharedContext() {
  30931. ({ ...this.context });
  30932. return this.context;
  30933. }
  30934. /**
  30935. * Sets builder's cache.
  30936. *
  30937. * @param {NodeCache} cache - The cache to set.
  30938. */
  30939. setCache( cache ) {
  30940. this.cache = cache;
  30941. }
  30942. /**
  30943. * Returns the builder's current cache.
  30944. *
  30945. * @return {NodeCache} The builder's current cache.
  30946. */
  30947. getCache() {
  30948. return this.cache;
  30949. }
  30950. /**
  30951. * Returns a cache for the given node.
  30952. *
  30953. * @param {Node} node - The node.
  30954. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30955. * @return {NodeCache} The cache.
  30956. */
  30957. getCacheFromNode( node, parent = true ) {
  30958. const data = this.getDataFromNode( node );
  30959. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30960. return data.cache;
  30961. }
  30962. /**
  30963. * Whether the requested feature is available or not.
  30964. *
  30965. * @abstract
  30966. * @param {string} name - The requested feature.
  30967. * @return {boolean} Whether the requested feature is supported or not.
  30968. */
  30969. isAvailable( /*name*/ ) {
  30970. return false;
  30971. }
  30972. /**
  30973. * Returns the vertexIndex input variable as a native shader string.
  30974. *
  30975. * @abstract
  30976. * @return {string} The instanceIndex shader string.
  30977. */
  30978. getVertexIndex() {
  30979. console.warn( 'Abstract function.' );
  30980. }
  30981. /**
  30982. * Returns the instanceIndex input variable as a native shader string.
  30983. *
  30984. * @abstract
  30985. * @return {string} The instanceIndex shader string.
  30986. */
  30987. getInstanceIndex() {
  30988. console.warn( 'Abstract function.' );
  30989. }
  30990. /**
  30991. * Returns the drawIndex input variable as a native shader string.
  30992. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30993. *
  30994. * @abstract
  30995. * @return {string} The drawIndex shader string.
  30996. */
  30997. getDrawIndex() {
  30998. console.warn( 'Abstract function.' );
  30999. }
  31000. /**
  31001. * Returns the frontFacing input variable as a native shader string.
  31002. *
  31003. * @abstract
  31004. * @return {string} The frontFacing shader string.
  31005. */
  31006. getFrontFacing() {
  31007. console.warn( 'Abstract function.' );
  31008. }
  31009. /**
  31010. * Returns the fragCoord input variable as a native shader string.
  31011. *
  31012. * @abstract
  31013. * @return {string} The fragCoord shader string.
  31014. */
  31015. getFragCoord() {
  31016. console.warn( 'Abstract function.' );
  31017. }
  31018. /**
  31019. * Whether to flip texture data along its vertical axis or not. WebGL needs
  31020. * this method evaluate to `true`, WebGPU to `false`.
  31021. *
  31022. * @abstract
  31023. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  31024. */
  31025. isFlipY() {
  31026. return false;
  31027. }
  31028. /**
  31029. * Calling this method increases the usage count for the given node by one.
  31030. *
  31031. * @param {Node} node - The node to increase the usage count for.
  31032. * @return {number} The updated usage count.
  31033. */
  31034. increaseUsage( node ) {
  31035. const nodeData = this.getDataFromNode( node );
  31036. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31037. return nodeData.usageCount;
  31038. }
  31039. /**
  31040. * Generates a texture sample shader string for the given texture data.
  31041. *
  31042. * @abstract
  31043. * @param {Texture} texture - The texture.
  31044. * @param {string} textureProperty - The texture property name.
  31045. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31046. * @return {string} The generated shader string.
  31047. */
  31048. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31049. console.warn( 'Abstract function.' );
  31050. }
  31051. /**
  31052. * Generates a texture LOD shader string for the given texture data.
  31053. *
  31054. * @abstract
  31055. * @param {Texture} texture - The texture.
  31056. * @param {string} textureProperty - The texture property name.
  31057. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31058. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  31059. * @param {string} levelSnippet - Snippet defining the mip level.
  31060. * @return {string} The generated shader string.
  31061. */
  31062. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  31063. console.warn( 'Abstract function.' );
  31064. }
  31065. /**
  31066. * Generates the array declaration string.
  31067. *
  31068. * @param {string} type - The type.
  31069. * @param {?number} [count] - The count.
  31070. * @return {string} The generated value as a shader string.
  31071. */
  31072. generateArrayDeclaration( type, count ) {
  31073. return this.getType( type ) + '[ ' + count + ' ]';
  31074. }
  31075. /**
  31076. * Generates the array shader string for the given type and value.
  31077. *
  31078. * @param {string} type - The type.
  31079. * @param {?number} [count] - The count.
  31080. * @param {?Array<Node>} [values=null] - The default values.
  31081. * @return {string} The generated value as a shader string.
  31082. */
  31083. generateArray( type, count, values = null ) {
  31084. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  31085. for ( let i = 0; i < count; i ++ ) {
  31086. const value = values ? values[ i ] : null;
  31087. if ( value !== null ) {
  31088. snippet += value.build( this, type );
  31089. } else {
  31090. snippet += this.generateConst( type );
  31091. }
  31092. if ( i < count - 1 ) snippet += ', ';
  31093. }
  31094. snippet += ' )';
  31095. return snippet;
  31096. }
  31097. /**
  31098. * Generates the struct shader string.
  31099. *
  31100. * @param {string} type - The type.
  31101. * @param {Array<Object>} [membersLayout] - The count.
  31102. * @param {?Array<Node>} [values=null] - The default values.
  31103. * @return {string} The generated value as a shader string.
  31104. */
  31105. generateStruct( type, membersLayout, values = null ) {
  31106. const snippets = [];
  31107. for ( const member of membersLayout ) {
  31108. const { name, type } = member;
  31109. if ( values && values[ name ] && values[ name ].isNode ) {
  31110. snippets.push( values[ name ].build( this, type ) );
  31111. } else {
  31112. snippets.push( this.generateConst( type ) );
  31113. }
  31114. }
  31115. return type + '( ' + snippets.join( ', ' ) + ' )';
  31116. }
  31117. /**
  31118. * Generates the shader string for the given type and value.
  31119. *
  31120. * @param {string} type - The type.
  31121. * @param {?any} [value=null] - The value.
  31122. * @return {string} The generated value as a shader string.
  31123. */
  31124. generateConst( type, value = null ) {
  31125. if ( value === null ) {
  31126. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31127. else if ( type === 'bool' ) value = false;
  31128. else if ( type === 'color' ) value = new Color();
  31129. else if ( type === 'vec2' ) value = new Vector2();
  31130. else if ( type === 'vec3' ) value = new Vector3();
  31131. else if ( type === 'vec4' ) value = new Vector4();
  31132. }
  31133. if ( type === 'float' ) return toFloat( value );
  31134. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31135. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31136. if ( type === 'bool' ) return value ? 'true' : 'false';
  31137. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31138. const typeLength = this.getTypeLength( type );
  31139. const componentType = this.getComponentType( type );
  31140. const generateConst = value => this.generateConst( componentType, value );
  31141. if ( typeLength === 2 ) {
  31142. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31143. } else if ( typeLength === 3 ) {
  31144. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31145. } else if ( typeLength === 4 ) {
  31146. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31147. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  31148. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31149. } else if ( typeLength > 4 ) {
  31150. return `${ this.getType( type ) }()`;
  31151. }
  31152. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31153. }
  31154. /**
  31155. * It might be necessary to convert certain data types to different ones
  31156. * so this method can be used to hide the conversion.
  31157. *
  31158. * @param {string} type - The type.
  31159. * @return {string} The updated type.
  31160. */
  31161. getType( type ) {
  31162. if ( type === 'color' ) return 'vec3';
  31163. return type;
  31164. }
  31165. /**
  31166. * Whether the given attribute name is defined in the geometry or not.
  31167. *
  31168. * @param {string} name - The attribute name.
  31169. * @return {boolean} Whether the given attribute name is defined in the geometry.
  31170. */
  31171. hasGeometryAttribute( name ) {
  31172. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31173. }
  31174. /**
  31175. * Returns a node attribute for the given name and type.
  31176. *
  31177. * @param {string} name - The attribute's name.
  31178. * @param {string} type - The attribute's type.
  31179. * @return {NodeAttribute} The node attribute.
  31180. */
  31181. getAttribute( name, type ) {
  31182. const attributes = this.attributes;
  31183. // find attribute
  31184. for ( const attribute of attributes ) {
  31185. if ( attribute.name === name ) {
  31186. return attribute;
  31187. }
  31188. }
  31189. // create a new if no exist
  31190. const attribute = new NodeAttribute( name, type );
  31191. attributes.push( attribute );
  31192. return attribute;
  31193. }
  31194. /**
  31195. * Returns for the given node and shader stage the property name for the shader.
  31196. *
  31197. * @param {Node} node - The node.
  31198. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31199. * @return {string} The property name.
  31200. */
  31201. getPropertyName( node/*, shaderStage*/ ) {
  31202. return node.name;
  31203. }
  31204. /**
  31205. * Whether the given type is a vector type or not.
  31206. *
  31207. * @param {string} type - The type to check.
  31208. * @return {boolean} Whether the given type is a vector type or not.
  31209. */
  31210. isVector( type ) {
  31211. return /vec\d/.test( type );
  31212. }
  31213. /**
  31214. * Whether the given type is a matrix type or not.
  31215. *
  31216. * @param {string} type - The type to check.
  31217. * @return {boolean} Whether the given type is a matrix type or not.
  31218. */
  31219. isMatrix( type ) {
  31220. return /mat\d/.test( type );
  31221. }
  31222. /**
  31223. * Whether the given type is a reference type or not.
  31224. *
  31225. * @param {string} type - The type to check.
  31226. * @return {boolean} Whether the given type is a reference type or not.
  31227. */
  31228. isReference( type ) {
  31229. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31230. }
  31231. /**
  31232. * Checks if the given texture requires a manual conversion to the working color space.
  31233. *
  31234. * @abstract
  31235. * @param {Texture} texture - The texture to check.
  31236. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  31237. */
  31238. needsToWorkingColorSpace( /*texture*/ ) {
  31239. return false;
  31240. }
  31241. /**
  31242. * Returns the component type of a given texture.
  31243. *
  31244. * @param {Texture} texture - The texture.
  31245. * @return {string} The component type.
  31246. */
  31247. getComponentTypeFromTexture( texture ) {
  31248. const type = texture.type;
  31249. if ( texture.isDataTexture ) {
  31250. if ( type === IntType ) return 'int';
  31251. if ( type === UnsignedIntType ) return 'uint';
  31252. }
  31253. return 'float';
  31254. }
  31255. /**
  31256. * Returns the element type for a given type.
  31257. *
  31258. * @param {string} type - The type.
  31259. * @return {string} The element type.
  31260. */
  31261. getElementType( type ) {
  31262. if ( type === 'mat2' ) return 'vec2';
  31263. if ( type === 'mat3' ) return 'vec3';
  31264. if ( type === 'mat4' ) return 'vec4';
  31265. return this.getComponentType( type );
  31266. }
  31267. /**
  31268. * Returns the component type for a given type.
  31269. *
  31270. * @param {string} type - The type.
  31271. * @return {string} The component type.
  31272. */
  31273. getComponentType( type ) {
  31274. type = this.getVectorType( type );
  31275. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31276. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31277. if ( componentType === null ) return null;
  31278. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31279. if ( componentType[ 1 ] === 'i' ) return 'int';
  31280. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31281. return 'float';
  31282. }
  31283. /**
  31284. * Returns the vector type for a given type.
  31285. *
  31286. * @param {string} type - The type.
  31287. * @return {string} The vector type.
  31288. */
  31289. getVectorType( type ) {
  31290. if ( type === 'color' ) return 'vec3';
  31291. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31292. return type;
  31293. }
  31294. /**
  31295. * Returns the data type for the given the length and component type.
  31296. *
  31297. * @param {number} length - The length.
  31298. * @param {string} [componentType='float'] - The component type.
  31299. * @return {string} The type.
  31300. */
  31301. getTypeFromLength( length, componentType = 'float' ) {
  31302. if ( length === 1 ) return componentType;
  31303. let baseType = getTypeFromLength( length );
  31304. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31305. // fix edge case for mat2x2 being same size as vec4
  31306. if ( /mat2/.test( componentType ) === true ) {
  31307. baseType = baseType.replace( 'vec', 'mat' );
  31308. }
  31309. return prefix + baseType;
  31310. }
  31311. /**
  31312. * Returns the type for a given typed array.
  31313. *
  31314. * @param {TypedArray} array - The typed array.
  31315. * @return {string} The type.
  31316. */
  31317. getTypeFromArray( array ) {
  31318. return typeFromArray.get( array.constructor );
  31319. }
  31320. /**
  31321. * Returns the type for a given buffer attribute.
  31322. *
  31323. * @param {BufferAttribute} attribute - The buffer attribute.
  31324. * @return {string} The type.
  31325. */
  31326. getTypeFromAttribute( attribute ) {
  31327. let dataAttribute = attribute;
  31328. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31329. const array = dataAttribute.array;
  31330. const itemSize = attribute.itemSize;
  31331. const normalized = attribute.normalized;
  31332. let arrayType;
  31333. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31334. arrayType = this.getTypeFromArray( array );
  31335. }
  31336. return this.getTypeFromLength( itemSize, arrayType );
  31337. }
  31338. /**
  31339. * Returns the length for the given data type.
  31340. *
  31341. * @param {string} type - The data type.
  31342. * @return {number} The length.
  31343. */
  31344. getTypeLength( type ) {
  31345. const vecType = this.getVectorType( type );
  31346. const vecNum = /vec([2-4])/.exec( vecType );
  31347. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31348. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31349. if ( /mat2/.test( type ) === true ) return 4;
  31350. if ( /mat3/.test( type ) === true ) return 9;
  31351. if ( /mat4/.test( type ) === true ) return 16;
  31352. return 0;
  31353. }
  31354. /**
  31355. * Returns the vector type for a given matrix type.
  31356. *
  31357. * @param {string} type - The matrix type.
  31358. * @return {string} The vector type.
  31359. */
  31360. getVectorFromMatrix( type ) {
  31361. return type.replace( 'mat', 'vec' );
  31362. }
  31363. /**
  31364. * For a given type this method changes the component type to the
  31365. * given value. E.g. `vec4` should be changed to the new component type
  31366. * `uint` which results in `uvec4`.
  31367. *
  31368. * @param {string} type - The type.
  31369. * @param {string} newComponentType - The new component type.
  31370. * @return {string} The new type.
  31371. */
  31372. changeComponentType( type, newComponentType ) {
  31373. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31374. }
  31375. /**
  31376. * Returns the integer type pendant for the given type.
  31377. *
  31378. * @param {string} type - The type.
  31379. * @return {string} The integer type.
  31380. */
  31381. getIntegerType( type ) {
  31382. const componentType = this.getComponentType( type );
  31383. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31384. return this.changeComponentType( type, 'int' );
  31385. }
  31386. /**
  31387. * Adds a stack node to the internal stack.
  31388. *
  31389. * @return {StackNode} The added stack node.
  31390. */
  31391. addStack() {
  31392. this.stack = stack( this.stack );
  31393. this.stacks.push( getCurrentStack() || this.stack );
  31394. setCurrentStack( this.stack );
  31395. return this.stack;
  31396. }
  31397. /**
  31398. * Removes the last stack node from the internal stack.
  31399. *
  31400. * @return {StackNode} The removed stack node.
  31401. */
  31402. removeStack() {
  31403. const lastStack = this.stack;
  31404. this.stack = lastStack.parent;
  31405. setCurrentStack( this.stacks.pop() );
  31406. return lastStack;
  31407. }
  31408. /**
  31409. * The builder maintains (cached) data for each node during the building process. This method
  31410. * can be used to get these data for a specific shader stage and cache.
  31411. *
  31412. * @param {Node} node - The node to get the data for.
  31413. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31414. * @param {?NodeCache} cache - An optional cache.
  31415. * @return {Object} The node data.
  31416. */
  31417. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31418. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31419. let nodeData = cache.getData( node );
  31420. if ( nodeData === undefined ) {
  31421. nodeData = {};
  31422. cache.setData( node, nodeData );
  31423. }
  31424. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31425. return nodeData[ shaderStage ];
  31426. }
  31427. /**
  31428. * Returns the properties for the given node and shader stage.
  31429. *
  31430. * @param {Node} node - The node to get the properties for.
  31431. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  31432. * @return {Object} The node properties.
  31433. */
  31434. getNodeProperties( node, shaderStage = 'any' ) {
  31435. const nodeData = this.getDataFromNode( node, shaderStage );
  31436. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31437. }
  31438. /**
  31439. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  31440. *
  31441. * @param {BufferAttributeNode} node - The buffer attribute node.
  31442. * @param {string} type - The node type.
  31443. * @return {NodeAttribute} The node attribute.
  31444. */
  31445. getBufferAttributeFromNode( node, type ) {
  31446. const nodeData = this.getDataFromNode( node );
  31447. let bufferAttribute = nodeData.bufferAttribute;
  31448. if ( bufferAttribute === undefined ) {
  31449. const index = this.uniforms.index ++;
  31450. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31451. this.bufferAttributes.push( bufferAttribute );
  31452. nodeData.bufferAttribute = bufferAttribute;
  31453. }
  31454. return bufferAttribute;
  31455. }
  31456. /**
  31457. * Returns an instance of {@link StructType} for the given output struct node.
  31458. *
  31459. * @param {OutputStructNode} node - The output struct node.
  31460. * @param {Array<Object>} membersLayout - The output struct types.
  31461. * @param {?string} [name=null] - The name of the struct.
  31462. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31463. * @return {StructType} The struct type attribute.
  31464. */
  31465. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  31466. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31467. let structType = nodeData.structType;
  31468. if ( structType === undefined ) {
  31469. const index = this.structs.index ++;
  31470. if ( name === null ) name = 'StructType' + index;
  31471. structType = new StructType( name, membersLayout );
  31472. this.structs[ shaderStage ].push( structType );
  31473. nodeData.structType = structType;
  31474. }
  31475. return structType;
  31476. }
  31477. /**
  31478. * Returns an instance of {@link StructType} for the given output struct node.
  31479. *
  31480. * @param {OutputStructNode} node - The output struct node.
  31481. * @param {Array<Object>} membersLayout - The output struct types.
  31482. * @return {StructType} The struct type attribute.
  31483. */
  31484. getOutputStructTypeFromNode( node, membersLayout ) {
  31485. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  31486. structType.output = true;
  31487. return structType;
  31488. }
  31489. /**
  31490. * Returns an instance of {@link NodeUniform} for the given uniform node.
  31491. *
  31492. * @param {UniformNode} node - The uniform node.
  31493. * @param {string} type - The uniform type.
  31494. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31495. * @param {?string} name - The name of the uniform.
  31496. * @return {NodeUniform} The node uniform.
  31497. */
  31498. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31499. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31500. let nodeUniform = nodeData.uniform;
  31501. if ( nodeUniform === undefined ) {
  31502. const index = this.uniforms.index ++;
  31503. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31504. this.uniforms[ shaderStage ].push( nodeUniform );
  31505. nodeData.uniform = nodeUniform;
  31506. }
  31507. return nodeUniform;
  31508. }
  31509. /**
  31510. * Returns the array length.
  31511. *
  31512. * @param {Node} node - The node.
  31513. * @return {?number} The array length.
  31514. */
  31515. getArrayCount( node ) {
  31516. let count = null;
  31517. if ( node.isArrayNode ) count = node.count;
  31518. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  31519. return count;
  31520. }
  31521. /**
  31522. * Returns an instance of {@link NodeVar} for the given variable node.
  31523. *
  31524. * @param {VarNode} node - The variable node.
  31525. * @param {?string} name - The variable's name.
  31526. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  31527. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31528. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  31529. *
  31530. * @return {NodeVar} The node variable.
  31531. */
  31532. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  31533. const nodeData = this.getDataFromNode( node, shaderStage );
  31534. let nodeVar = nodeData.variable;
  31535. if ( nodeVar === undefined ) {
  31536. const idNS = readOnly ? '_const' : '_var';
  31537. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31538. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  31539. if ( name === null ) {
  31540. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  31541. this.vars[ idNS ] ++;
  31542. }
  31543. //
  31544. const count = this.getArrayCount( node );
  31545. nodeVar = new NodeVar( name, type, readOnly, count );
  31546. if ( ! readOnly ) {
  31547. vars.push( nodeVar );
  31548. }
  31549. nodeData.variable = nodeVar;
  31550. }
  31551. return nodeVar;
  31552. }
  31553. /**
  31554. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  31555. *
  31556. * @param {Node} node - The varying node.
  31557. * @return {boolean} Returns true if deterministic.
  31558. */
  31559. isDeterministic( node ) {
  31560. if ( node.isMathNode ) {
  31561. return this.isDeterministic( node.aNode ) &&
  31562. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  31563. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  31564. } else if ( node.isOperatorNode ) {
  31565. return this.isDeterministic( node.aNode ) &&
  31566. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  31567. } else if ( node.isArrayNode ) {
  31568. if ( node.values !== null ) {
  31569. for ( const n of node.values ) {
  31570. if ( ! this.isDeterministic( n ) ) {
  31571. return false;
  31572. }
  31573. }
  31574. }
  31575. return true;
  31576. } else if ( node.isConstNode ) {
  31577. return true;
  31578. }
  31579. return false;
  31580. }
  31581. /**
  31582. * Returns an instance of {@link NodeVarying} for the given varying node.
  31583. *
  31584. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  31585. * @param {?string} name - The varying's name.
  31586. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  31587. * @return {NodeVar} The node varying.
  31588. */
  31589. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31590. const nodeData = this.getDataFromNode( node, 'any' );
  31591. let nodeVarying = nodeData.varying;
  31592. if ( nodeVarying === undefined ) {
  31593. const varyings = this.varyings;
  31594. const index = varyings.length;
  31595. if ( name === null ) name = 'nodeVarying' + index;
  31596. nodeVarying = new NodeVarying( name, type );
  31597. varyings.push( nodeVarying );
  31598. nodeData.varying = nodeVarying;
  31599. }
  31600. return nodeVarying;
  31601. }
  31602. /**
  31603. * Returns an instance of {@link NodeCode} for the given code node.
  31604. *
  31605. * @param {CodeNode} node - The code node.
  31606. * @param {string} type - The node type.
  31607. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31608. * @return {NodeCode} The node code.
  31609. */
  31610. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31611. const nodeData = this.getDataFromNode( node );
  31612. let nodeCode = nodeData.code;
  31613. if ( nodeCode === undefined ) {
  31614. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31615. const index = codes.length;
  31616. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31617. codes.push( nodeCode );
  31618. nodeData.code = nodeCode;
  31619. }
  31620. return nodeCode;
  31621. }
  31622. /**
  31623. * Adds a code flow based on the code-block hierarchy.
  31624. * This is used so that code-blocks like If,Else create their variables locally if the Node
  31625. * is only used inside one of these conditionals in the current shader stage.
  31626. *
  31627. * @param {Node} node - The node to add.
  31628. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  31629. */
  31630. addFlowCodeHierarchy( node, nodeBlock ) {
  31631. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31632. let needsFlowCode = true;
  31633. let nodeBlockHierarchy = nodeBlock;
  31634. while ( nodeBlockHierarchy ) {
  31635. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31636. needsFlowCode = false;
  31637. break;
  31638. }
  31639. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31640. }
  31641. if ( needsFlowCode ) {
  31642. for ( const flowCode of flowCodes ) {
  31643. this.addLineFlowCode( flowCode );
  31644. }
  31645. }
  31646. }
  31647. /**
  31648. * Add a inline-code to the current flow code-block.
  31649. *
  31650. * @param {Node} node - The node to add.
  31651. * @param {string} code - The code to add.
  31652. * @param {Node} nodeBlock - Current ConditionalNode
  31653. */
  31654. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31655. const nodeData = this.getDataFromNode( node );
  31656. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31657. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31658. flowCodes.push( code );
  31659. codeBlock.set( nodeBlock, true );
  31660. }
  31661. /**
  31662. * Add a inline-code to the current flow.
  31663. *
  31664. * @param {string} code - The code to add.
  31665. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  31666. * @return {NodeBuilder} A reference to this node builder.
  31667. */
  31668. addLineFlowCode( code, node = null ) {
  31669. if ( code === '' ) return this;
  31670. if ( node !== null && this.context.nodeBlock ) {
  31671. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31672. }
  31673. code = this.tab + code;
  31674. if ( ! /;\s*$/.test( code ) ) {
  31675. code = code + ';\n';
  31676. }
  31677. this.flow.code += code;
  31678. return this;
  31679. }
  31680. /**
  31681. * Adds a code to the current code flow.
  31682. *
  31683. * @param {string} code - Shader code.
  31684. * @return {NodeBuilder} A reference to this node builder.
  31685. */
  31686. addFlowCode( code ) {
  31687. this.flow.code += code;
  31688. return this;
  31689. }
  31690. /**
  31691. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  31692. * Typically used in codes with If,Else.
  31693. *
  31694. * @return {NodeBuilder} A reference to this node builder.
  31695. */
  31696. addFlowTab() {
  31697. this.tab += '\t';
  31698. return this;
  31699. }
  31700. /**
  31701. * Removes a tab.
  31702. *
  31703. * @return {NodeBuilder} A reference to this node builder.
  31704. */
  31705. removeFlowTab() {
  31706. this.tab = this.tab.slice( 0, -1 );
  31707. return this;
  31708. }
  31709. /**
  31710. * Gets the current flow data based on a Node.
  31711. *
  31712. * @param {Node} node - Node that the flow was started.
  31713. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31714. * @return {Object} The flow data.
  31715. */
  31716. getFlowData( node/*, shaderStage*/ ) {
  31717. return this.flowsData.get( node );
  31718. }
  31719. /**
  31720. * Executes the node flow based on a root node to generate the final shader code.
  31721. *
  31722. * @param {Node} node - The node to execute.
  31723. * @return {Object} The code flow.
  31724. */
  31725. flowNode( node ) {
  31726. const output = node.getNodeType( this );
  31727. const flowData = this.flowChildNode( node, output );
  31728. this.flowsData.set( node, flowData );
  31729. return flowData;
  31730. }
  31731. /**
  31732. * Includes a node in the current function node.
  31733. *
  31734. * @param {Node} node - The node to include.
  31735. * @returns {void}
  31736. */
  31737. addInclude( node ) {
  31738. if ( this.currentFunctionNode !== null ) {
  31739. this.currentFunctionNode.includes.push( node );
  31740. }
  31741. }
  31742. /**
  31743. * Returns the native shader operator name for a given generic name.
  31744. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31745. *
  31746. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  31747. * @return {FunctionNode} The build function node.
  31748. */
  31749. buildFunctionNode( shaderNode ) {
  31750. const fn = new FunctionNode();
  31751. const previous = this.currentFunctionNode;
  31752. this.currentFunctionNode = fn;
  31753. fn.code = this.buildFunctionCode( shaderNode );
  31754. this.currentFunctionNode = previous;
  31755. return fn;
  31756. }
  31757. /**
  31758. * Generates a code flow based on a TSL function: Fn().
  31759. *
  31760. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  31761. * @return {Object}
  31762. */
  31763. flowShaderNode( shaderNode ) {
  31764. const layout = shaderNode.layout;
  31765. const inputs = {
  31766. [ Symbol.iterator ]() {
  31767. let index = 0;
  31768. const values = Object.values( this );
  31769. return {
  31770. next: () => ( {
  31771. value: values[ index ],
  31772. done: index ++ >= values.length
  31773. } )
  31774. };
  31775. }
  31776. };
  31777. for ( const input of layout.inputs ) {
  31778. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31779. }
  31780. //
  31781. shaderNode.layout = null;
  31782. const callNode = shaderNode.call( inputs );
  31783. const flowData = this.flowStagesNode( callNode, layout.type );
  31784. shaderNode.layout = layout;
  31785. return flowData;
  31786. }
  31787. /**
  31788. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  31789. *
  31790. * @param {Node} node - The node to execute.
  31791. * @param {?string} output - Expected output type. For example 'vec3'.
  31792. * @return {Object}
  31793. */
  31794. flowStagesNode( node, output = null ) {
  31795. const previousFlow = this.flow;
  31796. const previousVars = this.vars;
  31797. const previousCache = this.cache;
  31798. const previousBuildStage = this.buildStage;
  31799. const previousStack = this.stack;
  31800. const flow = {
  31801. code: ''
  31802. };
  31803. this.flow = flow;
  31804. this.vars = {};
  31805. this.cache = new NodeCache();
  31806. this.stack = stack();
  31807. for ( const buildStage of defaultBuildStages ) {
  31808. this.setBuildStage( buildStage );
  31809. flow.result = node.build( this, output );
  31810. }
  31811. flow.vars = this.getVars( this.shaderStage );
  31812. this.flow = previousFlow;
  31813. this.vars = previousVars;
  31814. this.cache = previousCache;
  31815. this.stack = previousStack;
  31816. this.setBuildStage( previousBuildStage );
  31817. return flow;
  31818. }
  31819. /**
  31820. * Returns the native shader operator name for a given generic name.
  31821. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31822. *
  31823. * @abstract
  31824. * @param {string} op - The operator name to resolve.
  31825. * @return {string} The resolved operator name.
  31826. */
  31827. getFunctionOperator( /* op */ ) {
  31828. return null;
  31829. }
  31830. /**
  31831. * Generates a code flow based on a child Node.
  31832. *
  31833. * @param {Node} node - The node to execute.
  31834. * @param {?string} output - Expected output type. For example 'vec3'.
  31835. * @return {Object} The code flow.
  31836. */
  31837. flowChildNode( node, output = null ) {
  31838. const previousFlow = this.flow;
  31839. const flow = {
  31840. code: ''
  31841. };
  31842. this.flow = flow;
  31843. flow.result = node.build( this, output );
  31844. this.flow = previousFlow;
  31845. return flow;
  31846. }
  31847. /**
  31848. * Executes a flow of code in a different stage.
  31849. *
  31850. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  31851. * return the value in fragment-stage even if it is being executed in an input fragment.
  31852. *
  31853. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31854. * @param {Node} node - The node to execute.
  31855. * @param {?string} output - Expected output type. For example 'vec3'.
  31856. * @param {?string} propertyName - The property name to assign the result.
  31857. * @return {Object}
  31858. */
  31859. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31860. const previousShaderStage = this.shaderStage;
  31861. this.setShaderStage( shaderStage );
  31862. const flowData = this.flowChildNode( node, output );
  31863. if ( propertyName !== null ) {
  31864. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31865. }
  31866. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31867. this.setShaderStage( previousShaderStage );
  31868. return flowData;
  31869. }
  31870. /**
  31871. * Returns an array holding all node attributes of this node builder.
  31872. *
  31873. * @return {Array<NodeAttribute>} The node attributes of this builder.
  31874. */
  31875. getAttributesArray() {
  31876. return this.attributes.concat( this.bufferAttributes );
  31877. }
  31878. /**
  31879. * Returns the attribute definitions as a shader string for the given shader stage.
  31880. *
  31881. * @abstract
  31882. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31883. * @return {string} The attribute code section.
  31884. */
  31885. getAttributes( /*shaderStage*/ ) {
  31886. console.warn( 'Abstract function.' );
  31887. }
  31888. /**
  31889. * Returns the varying definitions as a shader string for the given shader stage.
  31890. *
  31891. * @abstract
  31892. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31893. * @return {string} The varying code section.
  31894. */
  31895. getVaryings( /*shaderStage*/ ) {
  31896. console.warn( 'Abstract function.' );
  31897. }
  31898. /**
  31899. * Returns a single variable definition as a shader string for the given variable type and name.
  31900. *
  31901. * @param {string} type - The variable's type.
  31902. * @param {string} name - The variable's name.
  31903. * @param {?number} [count=null] - The array length.
  31904. * @return {string} The shader string.
  31905. */
  31906. getVar( type, name, count = null ) {
  31907. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  31908. }
  31909. /**
  31910. * Returns the variable definitions as a shader string for the given shader stage.
  31911. *
  31912. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31913. * @return {string} The variable code section.
  31914. */
  31915. getVars( shaderStage ) {
  31916. let snippet = '';
  31917. const vars = this.vars[ shaderStage ];
  31918. if ( vars !== undefined ) {
  31919. for ( const variable of vars ) {
  31920. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31921. }
  31922. }
  31923. return snippet;
  31924. }
  31925. /**
  31926. * Returns the uniform definitions as a shader string for the given shader stage.
  31927. *
  31928. * @abstract
  31929. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31930. * @return {string} The uniform code section.
  31931. */
  31932. getUniforms( /*shaderStage*/ ) {
  31933. console.warn( 'Abstract function.' );
  31934. }
  31935. /**
  31936. * Returns the native code definitions as a shader string for the given shader stage.
  31937. *
  31938. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31939. * @return {string} The native code section.
  31940. */
  31941. getCodes( shaderStage ) {
  31942. const codes = this.codes[ shaderStage ];
  31943. let code = '';
  31944. if ( codes !== undefined ) {
  31945. for ( const nodeCode of codes ) {
  31946. code += nodeCode.code + '\n';
  31947. }
  31948. }
  31949. return code;
  31950. }
  31951. /**
  31952. * Returns the hash of this node builder.
  31953. *
  31954. * @return {string} The hash.
  31955. */
  31956. getHash() {
  31957. return this.vertexShader + this.fragmentShader + this.computeShader;
  31958. }
  31959. /**
  31960. * Sets the current shader stage.
  31961. *
  31962. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  31963. */
  31964. setShaderStage( shaderStage ) {
  31965. this.shaderStage = shaderStage;
  31966. }
  31967. /**
  31968. * Returns the current shader stage.
  31969. *
  31970. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  31971. */
  31972. getShaderStage() {
  31973. return this.shaderStage;
  31974. }
  31975. /**
  31976. * Sets the current build stage.
  31977. *
  31978. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  31979. */
  31980. setBuildStage( buildStage ) {
  31981. this.buildStage = buildStage;
  31982. }
  31983. /**
  31984. * Returns the current build stage.
  31985. *
  31986. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  31987. */
  31988. getBuildStage() {
  31989. return this.buildStage;
  31990. }
  31991. /**
  31992. * Controls the code build of the shader stages.
  31993. *
  31994. * @abstract
  31995. */
  31996. buildCode() {
  31997. console.warn( 'Abstract function.' );
  31998. }
  31999. /**
  32000. * Central build method which controls the build for the given object.
  32001. *
  32002. * @return {NodeBuilder} A reference to this node builder.
  32003. */
  32004. build() {
  32005. const { object, material, renderer } = this;
  32006. if ( material !== null ) {
  32007. let nodeMaterial = renderer.library.fromMaterial( material );
  32008. if ( nodeMaterial === null ) {
  32009. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  32010. nodeMaterial = new NodeMaterial();
  32011. }
  32012. nodeMaterial.build( this );
  32013. } else {
  32014. this.addFlow( 'compute', object );
  32015. }
  32016. // setup() -> stage 1: create possible new nodes and returns an output reference node
  32017. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  32018. // generate() -> stage 3: generate shader
  32019. for ( const buildStage of defaultBuildStages ) {
  32020. this.setBuildStage( buildStage );
  32021. if ( this.context.vertex && this.context.vertex.isNode ) {
  32022. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  32023. }
  32024. for ( const shaderStage of shaderStages ) {
  32025. this.setShaderStage( shaderStage );
  32026. const flowNodes = this.flowNodes[ shaderStage ];
  32027. for ( const node of flowNodes ) {
  32028. if ( buildStage === 'generate' ) {
  32029. this.flowNode( node );
  32030. } else {
  32031. node.build( this );
  32032. }
  32033. }
  32034. }
  32035. }
  32036. this.setBuildStage( null );
  32037. this.setShaderStage( null );
  32038. // stage 4: build code for a specific output
  32039. this.buildCode();
  32040. this.buildUpdateNodes();
  32041. return this;
  32042. }
  32043. /**
  32044. * Returns a uniform representation which is later used for UBO generation and rendering.
  32045. *
  32046. * @param {NodeUniform} uniformNode - The uniform node.
  32047. * @param {string} type - The requested type.
  32048. * @return {Uniform} The uniform.
  32049. */
  32050. getNodeUniform( uniformNode, type ) {
  32051. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  32052. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  32053. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  32054. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  32055. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  32056. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  32057. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  32058. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  32059. throw new Error( `Uniform "${type}" not declared.` );
  32060. }
  32061. /**
  32062. * Formats the given shader snippet from a given type into another one. E.g.
  32063. * this method might be used to convert a simple float string `"1.0"` into a
  32064. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  32065. *
  32066. * @param {string} snippet - The shader snippet.
  32067. * @param {string} fromType - The source type.
  32068. * @param {string} toType - The target type.
  32069. * @return {string} The updated shader string.
  32070. */
  32071. format( snippet, fromType, toType ) {
  32072. fromType = this.getVectorType( fromType );
  32073. toType = this.getVectorType( toType );
  32074. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  32075. return snippet;
  32076. }
  32077. const fromTypeLength = this.getTypeLength( fromType );
  32078. const toTypeLength = this.getTypeLength( toType );
  32079. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  32080. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  32081. }
  32082. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  32083. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  32084. }
  32085. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  32086. // @TODO: ignore for now
  32087. return snippet;
  32088. }
  32089. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  32090. // @TODO: ignore for now
  32091. return snippet;
  32092. }
  32093. if ( fromTypeLength === toTypeLength ) {
  32094. return `${ this.getType( toType ) }( ${ snippet } )`;
  32095. }
  32096. if ( fromTypeLength > toTypeLength ) {
  32097. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  32098. }
  32099. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  32100. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  32101. }
  32102. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  32103. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  32104. }
  32105. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  32106. // convert a number value to vector type, e.g:
  32107. // vec3( 1u ) -> vec3( float( 1u ) )
  32108. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  32109. }
  32110. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  32111. }
  32112. /**
  32113. * Returns a signature with the engine's current revision.
  32114. *
  32115. * @return {string} The signature.
  32116. */
  32117. getSignature() {
  32118. return `// Three.js r${ REVISION } - Node System\n`;
  32119. }
  32120. // Deprecated
  32121. /**
  32122. * @function
  32123. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  32124. *
  32125. * @param {string} [type='NodeMaterial'] - The node material type.
  32126. * @throws {Error}
  32127. */
  32128. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  32129. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  32130. }
  32131. }
  32132. /**
  32133. * Management class for updating nodes. The module tracks metrics like
  32134. * the elapsed time, delta time, the render and frame ID to correctly
  32135. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  32136. * and {@link Node#updateAfter} depending on the node's configuration.
  32137. */
  32138. class NodeFrame {
  32139. /**
  32140. * Constructs a new node fame.
  32141. */
  32142. constructor() {
  32143. /**
  32144. * The elapsed time in seconds.
  32145. *
  32146. * @type {number}
  32147. * @default 0
  32148. */
  32149. this.time = 0;
  32150. /**
  32151. * The delta time in seconds.
  32152. *
  32153. * @type {number}
  32154. * @default 0
  32155. */
  32156. this.deltaTime = 0;
  32157. /**
  32158. * The frame ID.
  32159. *
  32160. * @type {number}
  32161. * @default 0
  32162. */
  32163. this.frameId = 0;
  32164. /**
  32165. * The render ID.
  32166. *
  32167. * @type {number}
  32168. * @default 0
  32169. */
  32170. this.renderId = 0;
  32171. /**
  32172. * Used to control the {@link Node#update} call.
  32173. *
  32174. * @type {WeakMap<Node, Object>}
  32175. */
  32176. this.updateMap = new WeakMap();
  32177. /**
  32178. * Used to control the {@link Node#updateBefore} call.
  32179. *
  32180. * @type {WeakMap<Node, Object>}
  32181. */
  32182. this.updateBeforeMap = new WeakMap();
  32183. /**
  32184. * Used to control the {@link Node#updateAfter} call.
  32185. *
  32186. * @type {WeakMap<Node, Object>}
  32187. */
  32188. this.updateAfterMap = new WeakMap();
  32189. /**
  32190. * A reference to the current renderer.
  32191. *
  32192. * @type {?Renderer}
  32193. * @default null
  32194. */
  32195. this.renderer = null;
  32196. /**
  32197. * A reference to the current material.
  32198. *
  32199. * @type {?Material}
  32200. * @default null
  32201. */
  32202. this.material = null;
  32203. /**
  32204. * A reference to the current camera.
  32205. *
  32206. * @type {?Camera}
  32207. * @default null
  32208. */
  32209. this.camera = null;
  32210. /**
  32211. * A reference to the current 3D object.
  32212. *
  32213. * @type {?Object3D}
  32214. * @default null
  32215. */
  32216. this.object = null;
  32217. /**
  32218. * A reference to the current scene.
  32219. *
  32220. * @type {?Scene}
  32221. * @default null
  32222. */
  32223. this.scene = null;
  32224. }
  32225. /**
  32226. * Returns a dictionary for a given node and update map which
  32227. * is used to correctly call node update methods per frame or render.
  32228. *
  32229. * @private
  32230. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  32231. * @param {Node} nodeRef - The reference to the current node.
  32232. * @return {Object<string,WeakMap>} The dictionary.
  32233. */
  32234. _getMaps( referenceMap, nodeRef ) {
  32235. let maps = referenceMap.get( nodeRef );
  32236. if ( maps === undefined ) {
  32237. maps = {
  32238. renderMap: new WeakMap(),
  32239. frameMap: new WeakMap()
  32240. };
  32241. referenceMap.set( nodeRef, maps );
  32242. }
  32243. return maps;
  32244. }
  32245. /**
  32246. * This method executes the {@link Node#updateBefore} for the given node.
  32247. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  32248. * is only executed once per frame, render or object depending on the update
  32249. * type.
  32250. *
  32251. * @param {Node} node - The node that should be updated.
  32252. */
  32253. updateBeforeNode( node ) {
  32254. const updateType = node.getUpdateBeforeType();
  32255. const reference = node.updateReference( this );
  32256. if ( updateType === NodeUpdateType.FRAME ) {
  32257. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  32258. if ( frameMap.get( reference ) !== this.frameId ) {
  32259. if ( node.updateBefore( this ) !== false ) {
  32260. frameMap.set( reference, this.frameId );
  32261. }
  32262. }
  32263. } else if ( updateType === NodeUpdateType.RENDER ) {
  32264. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  32265. if ( renderMap.get( reference ) !== this.renderId ) {
  32266. if ( node.updateBefore( this ) !== false ) {
  32267. renderMap.set( reference, this.renderId );
  32268. }
  32269. }
  32270. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32271. node.updateBefore( this );
  32272. }
  32273. }
  32274. /**
  32275. * This method executes the {@link Node#updateAfter} for the given node.
  32276. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  32277. * is only executed once per frame, render or object depending on the update
  32278. * type.
  32279. *
  32280. * @param {Node} node - The node that should be updated.
  32281. */
  32282. updateAfterNode( node ) {
  32283. const updateType = node.getUpdateAfterType();
  32284. const reference = node.updateReference( this );
  32285. if ( updateType === NodeUpdateType.FRAME ) {
  32286. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  32287. if ( frameMap.get( reference ) !== this.frameId ) {
  32288. if ( node.updateAfter( this ) !== false ) {
  32289. frameMap.set( reference, this.frameId );
  32290. }
  32291. }
  32292. } else if ( updateType === NodeUpdateType.RENDER ) {
  32293. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  32294. if ( renderMap.get( reference ) !== this.renderId ) {
  32295. if ( node.updateAfter( this ) !== false ) {
  32296. renderMap.set( reference, this.renderId );
  32297. }
  32298. }
  32299. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32300. node.updateAfter( this );
  32301. }
  32302. }
  32303. /**
  32304. * This method executes the {@link Node#update} for the given node.
  32305. * It makes sure {@link Node#updateType} is honored meaning the update
  32306. * is only executed once per frame, render or object depending on the update
  32307. * type.
  32308. *
  32309. * @param {Node} node - The node that should be updated.
  32310. */
  32311. updateNode( node ) {
  32312. const updateType = node.getUpdateType();
  32313. const reference = node.updateReference( this );
  32314. if ( updateType === NodeUpdateType.FRAME ) {
  32315. const { frameMap } = this._getMaps( this.updateMap, reference );
  32316. if ( frameMap.get( reference ) !== this.frameId ) {
  32317. if ( node.update( this ) !== false ) {
  32318. frameMap.set( reference, this.frameId );
  32319. }
  32320. }
  32321. } else if ( updateType === NodeUpdateType.RENDER ) {
  32322. const { renderMap } = this._getMaps( this.updateMap, reference );
  32323. if ( renderMap.get( reference ) !== this.renderId ) {
  32324. if ( node.update( this ) !== false ) {
  32325. renderMap.set( reference, this.renderId );
  32326. }
  32327. }
  32328. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32329. node.update( this );
  32330. }
  32331. }
  32332. /**
  32333. * Updates the internal state of the node frame. This method is
  32334. * called by the renderer in its internal animation loop.
  32335. */
  32336. update() {
  32337. this.frameId ++;
  32338. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  32339. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  32340. this.lastTime = performance.now();
  32341. this.time += this.deltaTime;
  32342. }
  32343. }
  32344. /**
  32345. * Describes the input of a {@link NodeFunction}.
  32346. */
  32347. class NodeFunctionInput {
  32348. /**
  32349. * Constructs a new node function input.
  32350. *
  32351. * @param {string} type - The input type.
  32352. * @param {string} name - The input name.
  32353. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  32354. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  32355. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  32356. */
  32357. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  32358. /**
  32359. * The input type.
  32360. *
  32361. * @type {string}
  32362. */
  32363. this.type = type;
  32364. /**
  32365. * The input name.
  32366. *
  32367. * @type {string}
  32368. */
  32369. this.name = name;
  32370. /**
  32371. * If the input is an Array, count will be the length.
  32372. *
  32373. * @type {?number}
  32374. * @default null
  32375. */
  32376. this.count = count;
  32377. /**
  32378. *The parameter qualifier (only relevant for GLSL).
  32379. *
  32380. * @type {('in'|'out'|'inout')}
  32381. * @default ''
  32382. */
  32383. this.qualifier = qualifier;
  32384. /**
  32385. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  32386. *
  32387. * @type {boolean}
  32388. * @default false
  32389. */
  32390. this.isConst = isConst;
  32391. }
  32392. }
  32393. NodeFunctionInput.isNodeFunctionInput = true;
  32394. /**
  32395. * Module for representing directional lights as nodes.
  32396. *
  32397. * @augments AnalyticLightNode
  32398. */
  32399. class DirectionalLightNode extends AnalyticLightNode {
  32400. static get type() {
  32401. return 'DirectionalLightNode';
  32402. }
  32403. /**
  32404. * Constructs a new directional light node.
  32405. *
  32406. * @param {?DirectionalLight} [light=null] - The directional light source.
  32407. */
  32408. constructor( light = null ) {
  32409. super( light );
  32410. }
  32411. setup( builder ) {
  32412. super.setup( builder );
  32413. const lightingModel = builder.context.lightingModel;
  32414. const lightColor = this.colorNode;
  32415. const lightDirection = lightTargetDirection( this.light );
  32416. const reflectedLight = builder.context.reflectedLight;
  32417. lightingModel.direct( {
  32418. lightDirection,
  32419. lightColor,
  32420. reflectedLight
  32421. }, builder.stack, builder );
  32422. }
  32423. }
  32424. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32425. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32426. let _ltcLib = null;
  32427. /**
  32428. * Module for representing rect area lights as nodes.
  32429. *
  32430. * @augments AnalyticLightNode
  32431. */
  32432. class RectAreaLightNode extends AnalyticLightNode {
  32433. static get type() {
  32434. return 'RectAreaLightNode';
  32435. }
  32436. /**
  32437. * Constructs a new rect area light node.
  32438. *
  32439. * @param {?RectAreaLight} [light=null] - The rect area light source.
  32440. */
  32441. constructor( light = null ) {
  32442. super( light );
  32443. /**
  32444. * Uniform node representing the half height of the are light.
  32445. *
  32446. * @type {UniformNode<vec3>}
  32447. */
  32448. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  32449. /**
  32450. * Uniform node representing the half width of the are light.
  32451. *
  32452. * @type {UniformNode<vec3>}
  32453. */
  32454. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  32455. /**
  32456. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  32457. * relies on `viewMatrix` which might vary per render call.
  32458. *
  32459. * @type {string}
  32460. * @default 'render'
  32461. */
  32462. this.updateType = NodeUpdateType.RENDER;
  32463. }
  32464. /**
  32465. * Overwritten to updated rect area light specific uniforms.
  32466. *
  32467. * @param {NodeFrame} frame - A reference to the current node frame.
  32468. */
  32469. update( frame ) {
  32470. super.update( frame );
  32471. const { light } = this;
  32472. const viewMatrix = frame.camera.matrixWorldInverse;
  32473. _matrix42.identity();
  32474. _matrix41.copy( light.matrixWorld );
  32475. _matrix41.premultiply( viewMatrix );
  32476. _matrix42.extractRotation( _matrix41 );
  32477. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32478. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32479. this.halfWidth.value.applyMatrix4( _matrix42 );
  32480. this.halfHeight.value.applyMatrix4( _matrix42 );
  32481. }
  32482. setup( builder ) {
  32483. super.setup( builder );
  32484. let ltc_1, ltc_2;
  32485. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32486. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  32487. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  32488. } else {
  32489. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  32490. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  32491. }
  32492. const { colorNode, light } = this;
  32493. const lightingModel = builder.context.lightingModel;
  32494. const lightPosition = lightViewPosition( light );
  32495. const reflectedLight = builder.context.reflectedLight;
  32496. lightingModel.directRectArea( {
  32497. lightColor: colorNode,
  32498. lightPosition,
  32499. halfWidth: this.halfWidth,
  32500. halfHeight: this.halfHeight,
  32501. reflectedLight,
  32502. ltc_1,
  32503. ltc_2
  32504. }, builder.stack, builder );
  32505. }
  32506. /**
  32507. * Used to configure the internal BRDF approximation texture data.
  32508. *
  32509. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  32510. */
  32511. static setLTC( ltc ) {
  32512. _ltcLib = ltc;
  32513. }
  32514. }
  32515. /**
  32516. * Module for representing spot lights as nodes.
  32517. *
  32518. * @augments AnalyticLightNode
  32519. */
  32520. class SpotLightNode extends AnalyticLightNode {
  32521. static get type() {
  32522. return 'SpotLightNode';
  32523. }
  32524. /**
  32525. * Constructs a new spot light node.
  32526. *
  32527. * @param {?SpotLight} [light=null] - The spot light source.
  32528. */
  32529. constructor( light = null ) {
  32530. super( light );
  32531. /**
  32532. * Uniform node representing the cone cosine.
  32533. *
  32534. * @type {UniformNode<float>}
  32535. */
  32536. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  32537. /**
  32538. * Uniform node representing the penumbra cosine.
  32539. *
  32540. * @type {UniformNode<float>}
  32541. */
  32542. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  32543. /**
  32544. * Uniform node representing the cutoff distance.
  32545. *
  32546. * @type {UniformNode<float>}
  32547. */
  32548. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32549. /**
  32550. * Uniform node representing the decay exponent.
  32551. *
  32552. * @type {UniformNode<float>}
  32553. */
  32554. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  32555. }
  32556. /**
  32557. * Overwritten to updated spot light specific uniforms.
  32558. *
  32559. * @param {NodeFrame} frame - A reference to the current node frame.
  32560. */
  32561. update( frame ) {
  32562. super.update( frame );
  32563. const { light } = this;
  32564. this.coneCosNode.value = Math.cos( light.angle );
  32565. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32566. this.cutoffDistanceNode.value = light.distance;
  32567. this.decayExponentNode.value = light.decay;
  32568. }
  32569. /**
  32570. * Computes the spot attenuation for the given angle.
  32571. *
  32572. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32573. * @return {Node<float>} The spot attenuation.
  32574. */
  32575. getSpotAttenuation( angleCosine ) {
  32576. const { coneCosNode, penumbraCosNode } = this;
  32577. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32578. }
  32579. setup( builder ) {
  32580. super.setup( builder );
  32581. const lightingModel = builder.context.lightingModel;
  32582. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32583. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32584. const lightDirection = lVector.normalize();
  32585. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32586. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32587. const lightDistance = lVector.length();
  32588. const lightAttenuation = getDistanceAttenuation( {
  32589. lightDistance,
  32590. cutoffDistance: cutoffDistanceNode,
  32591. decayExponent: decayExponentNode
  32592. } );
  32593. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32594. if ( light.map ) {
  32595. const spotLightCoord = lightProjectionUV( light );
  32596. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  32597. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  32598. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  32599. }
  32600. const reflectedLight = builder.context.reflectedLight;
  32601. lightingModel.direct( {
  32602. lightDirection,
  32603. lightColor,
  32604. reflectedLight
  32605. }, builder.stack, builder );
  32606. }
  32607. }
  32608. /**
  32609. * An IES version of the default spot light node.
  32610. *
  32611. * @augments SpotLightNode
  32612. */
  32613. class IESSpotLightNode extends SpotLightNode {
  32614. static get type() {
  32615. return 'IESSpotLightNode';
  32616. }
  32617. /**
  32618. * Overwrites the default implementation to compute an IES conform spot attenuation.
  32619. *
  32620. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32621. * @return {Node<float>} The spot attenuation.
  32622. */
  32623. getSpotAttenuation( angleCosine ) {
  32624. const iesMap = this.light.iesMap;
  32625. let spotAttenuation = null;
  32626. if ( iesMap && iesMap.isTexture === true ) {
  32627. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32628. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32629. } else {
  32630. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32631. }
  32632. return spotAttenuation;
  32633. }
  32634. }
  32635. /**
  32636. * Module for representing ambient lights as nodes.
  32637. *
  32638. * @augments AnalyticLightNode
  32639. */
  32640. class AmbientLightNode extends AnalyticLightNode {
  32641. static get type() {
  32642. return 'AmbientLightNode';
  32643. }
  32644. /**
  32645. * Constructs a new ambient light node.
  32646. *
  32647. * @param {?AmbientLight} [light=null] - The ambient light source.
  32648. */
  32649. constructor( light = null ) {
  32650. super( light );
  32651. }
  32652. setup( { context } ) {
  32653. context.irradiance.addAssign( this.colorNode );
  32654. }
  32655. }
  32656. /**
  32657. * Module for representing hemisphere lights as nodes.
  32658. *
  32659. * @augments AnalyticLightNode
  32660. */
  32661. class HemisphereLightNode extends AnalyticLightNode {
  32662. static get type() {
  32663. return 'HemisphereLightNode';
  32664. }
  32665. /**
  32666. * Constructs a new hemisphere light node.
  32667. *
  32668. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  32669. */
  32670. constructor( light = null ) {
  32671. super( light );
  32672. /**
  32673. * Uniform node representing the light's position.
  32674. *
  32675. * @type {UniformNode<vec3>}
  32676. */
  32677. this.lightPositionNode = lightPosition( light );
  32678. /**
  32679. * A node representing the light's direction.
  32680. *
  32681. * @type {Node<vec3>}
  32682. */
  32683. this.lightDirectionNode = this.lightPositionNode.normalize();
  32684. /**
  32685. * Uniform node representing the light's ground color.
  32686. *
  32687. * @type {UniformNode<vec3>}
  32688. */
  32689. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  32690. }
  32691. /**
  32692. * Overwritten to updated hemisphere light specific uniforms.
  32693. *
  32694. * @param {NodeFrame} frame - A reference to the current node frame.
  32695. */
  32696. update( frame ) {
  32697. const { light } = this;
  32698. super.update( frame );
  32699. this.lightPositionNode.object3d = light;
  32700. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32701. }
  32702. setup( builder ) {
  32703. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32704. const dotNL = normalView.dot( lightDirectionNode );
  32705. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32706. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32707. builder.context.irradiance.addAssign( irradiance );
  32708. }
  32709. }
  32710. /**
  32711. * Module for representing light probes as nodes.
  32712. *
  32713. * @augments AnalyticLightNode
  32714. */
  32715. class LightProbeNode extends AnalyticLightNode {
  32716. static get type() {
  32717. return 'LightProbeNode';
  32718. }
  32719. /**
  32720. * Constructs a new light probe node.
  32721. *
  32722. * @param {?LightProbe} [light=null] - The light probe.
  32723. */
  32724. constructor( light = null ) {
  32725. super( light );
  32726. const array = [];
  32727. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  32728. /**
  32729. * Light probe represented as a uniform of spherical harmonics.
  32730. *
  32731. * @type {UniformArrayNode}
  32732. */
  32733. this.lightProbe = uniformArray( array );
  32734. }
  32735. /**
  32736. * Overwritten to updated light probe specific uniforms.
  32737. *
  32738. * @param {NodeFrame} frame - A reference to the current node frame.
  32739. */
  32740. update( frame ) {
  32741. const { light } = this;
  32742. super.update( frame );
  32743. //
  32744. for ( let i = 0; i < 9; i ++ ) {
  32745. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  32746. }
  32747. }
  32748. setup( builder ) {
  32749. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  32750. builder.context.irradiance.addAssign( irradiance );
  32751. }
  32752. }
  32753. /**
  32754. * Base class for node parsers. A derived parser must be implemented
  32755. * for each supported native shader language.
  32756. */
  32757. class NodeParser {
  32758. /**
  32759. * The method parses the given native code an returns a node function.
  32760. *
  32761. * @abstract
  32762. * @param {string} source - The native shader code.
  32763. * @return {NodeFunction} A node function.
  32764. */
  32765. parseFunction( /*source*/ ) {
  32766. console.warn( 'Abstract function.' );
  32767. }
  32768. }
  32769. /**
  32770. * Base class for node functions. A derived module must be implemented
  32771. * for each supported native shader language. Similar to other `Node*` modules,
  32772. * this class is only relevant during the building process and not used
  32773. * in user-level code.
  32774. */
  32775. class NodeFunction {
  32776. /**
  32777. * Constructs a new node function.
  32778. *
  32779. * @param {string} type - The node type. This type is the return type of the node function.
  32780. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  32781. * @param {string} [name=''] - The function's name.
  32782. * @param {string} [precision=''] - The precision qualifier.
  32783. */
  32784. constructor( type, inputs, name = '', precision = '' ) {
  32785. /**
  32786. * The node type. This type is the return type of the node function.
  32787. *
  32788. * @type {string}
  32789. */
  32790. this.type = type;
  32791. /**
  32792. * The function's inputs.
  32793. *
  32794. * @type {Array<NodeFunctionInput>}
  32795. */
  32796. this.inputs = inputs;
  32797. /**
  32798. * The name of the uniform.
  32799. *
  32800. * @type {string}
  32801. * @default ''
  32802. */
  32803. this.name = name;
  32804. /**
  32805. * The precision qualifier.
  32806. *
  32807. * @type {string}
  32808. * @default ''
  32809. */
  32810. this.precision = precision;
  32811. }
  32812. /**
  32813. * This method returns the native code of the node function.
  32814. *
  32815. * @abstract
  32816. * @param {string} name - The function's name.
  32817. * @return {string} A shader code.
  32818. */
  32819. getCode( /*name = this.name*/ ) {
  32820. console.warn( 'Abstract function.' );
  32821. }
  32822. }
  32823. NodeFunction.isNodeFunction = true;
  32824. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  32825. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  32826. const pragmaMain = '#pragma main';
  32827. const parse$1 = ( source ) => {
  32828. source = source.trim();
  32829. const pragmaMainIndex = source.indexOf( pragmaMain );
  32830. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  32831. const declaration = mainCode.match( declarationRegexp$1 );
  32832. if ( declaration !== null && declaration.length === 5 ) {
  32833. // tokenizer
  32834. const inputsCode = declaration[ 4 ];
  32835. const propsMatches = [];
  32836. let nameMatch = null;
  32837. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  32838. propsMatches.push( nameMatch );
  32839. }
  32840. // parser
  32841. const inputs = [];
  32842. let i = 0;
  32843. while ( i < propsMatches.length ) {
  32844. const isConst = propsMatches[ i ][ 0 ] === 'const';
  32845. if ( isConst === true ) {
  32846. i ++;
  32847. }
  32848. let qualifier = propsMatches[ i ][ 0 ];
  32849. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  32850. i ++;
  32851. } else {
  32852. qualifier = '';
  32853. }
  32854. const type = propsMatches[ i ++ ][ 0 ];
  32855. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  32856. if ( Number.isNaN( count ) === false ) i ++;
  32857. else count = null;
  32858. const name = propsMatches[ i ++ ][ 0 ];
  32859. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  32860. }
  32861. //
  32862. const blockCode = mainCode.substring( declaration[ 0 ].length );
  32863. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  32864. const type = declaration[ 2 ];
  32865. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  32866. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  32867. return {
  32868. type,
  32869. inputs,
  32870. name,
  32871. precision,
  32872. inputsCode,
  32873. blockCode,
  32874. headerCode
  32875. };
  32876. } else {
  32877. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  32878. }
  32879. };
  32880. /**
  32881. * This class represents a GLSL node function.
  32882. *
  32883. * @augments NodeFunction
  32884. */
  32885. class GLSLNodeFunction extends NodeFunction {
  32886. /**
  32887. * Constructs a new GLSL node function.
  32888. *
  32889. * @param {string} source - The GLSL source.
  32890. */
  32891. constructor( source ) {
  32892. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32893. super( type, inputs, name, precision );
  32894. this.inputsCode = inputsCode;
  32895. this.blockCode = blockCode;
  32896. this.headerCode = headerCode;
  32897. }
  32898. /**
  32899. * This method returns the GLSL code of the node function.
  32900. *
  32901. * @param {string} [name=this.name] - The function's name.
  32902. * @return {string} The shader code.
  32903. */
  32904. getCode( name = this.name ) {
  32905. let code;
  32906. const blockCode = this.blockCode;
  32907. if ( blockCode !== '' ) {
  32908. const { type, inputsCode, headerCode, precision } = this;
  32909. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32910. if ( precision !== '' ) {
  32911. declarationCode = `${ precision } ${ declarationCode }`;
  32912. }
  32913. code = headerCode + declarationCode + blockCode;
  32914. } else {
  32915. // interface function
  32916. code = '';
  32917. }
  32918. return code;
  32919. }
  32920. }
  32921. /**
  32922. * A GLSL node parser.
  32923. *
  32924. * @augments NodeParser
  32925. */
  32926. class GLSLNodeParser extends NodeParser {
  32927. /**
  32928. * The method parses the given GLSL code an returns a node function.
  32929. *
  32930. * @param {string} source - The GLSL code.
  32931. * @return {GLSLNodeFunction} A node function.
  32932. */
  32933. parseFunction( source ) {
  32934. return new GLSLNodeFunction( source );
  32935. }
  32936. }
  32937. const _outputNodeMap = new WeakMap();
  32938. const _chainKeys$2 = [];
  32939. const _cacheKeyValues = [];
  32940. /**
  32941. * This renderer module manages node-related objects and is the
  32942. * primary interface between the renderer and the node system.
  32943. *
  32944. * @private
  32945. * @augments DataMap
  32946. */
  32947. class Nodes extends DataMap {
  32948. /**
  32949. * Constructs a new nodes management component.
  32950. *
  32951. * @param {Renderer} renderer - The renderer.
  32952. * @param {Backend} backend - The renderer's backend.
  32953. */
  32954. constructor( renderer, backend ) {
  32955. super();
  32956. /**
  32957. * The renderer.
  32958. *
  32959. * @type {Renderer}
  32960. */
  32961. this.renderer = renderer;
  32962. /**
  32963. * The renderer's backend.
  32964. *
  32965. * @type {Backend}
  32966. */
  32967. this.backend = backend;
  32968. /**
  32969. * The node frame.
  32970. *
  32971. * @type {Renderer}
  32972. */
  32973. this.nodeFrame = new NodeFrame();
  32974. /**
  32975. * A cache for managing node builder states.
  32976. *
  32977. * @type {Map<number,NodeBuilderState>}
  32978. */
  32979. this.nodeBuilderCache = new Map();
  32980. /**
  32981. * A cache for managing data cache key data.
  32982. *
  32983. * @type {ChainMap}
  32984. */
  32985. this.callHashCache = new ChainMap();
  32986. /**
  32987. * A cache for managing node uniforms group data.
  32988. *
  32989. * @type {ChainMap}
  32990. */
  32991. this.groupsData = new ChainMap();
  32992. /**
  32993. * A cache for managing node objects of
  32994. * scene properties like fog or environments.
  32995. *
  32996. * @type {Object<string,WeakMap>}
  32997. */
  32998. this.cacheLib = {};
  32999. }
  33000. /**
  33001. * Returns `true` if the given node uniforms group must be updated or not.
  33002. *
  33003. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  33004. * @return {boolean} Whether the node uniforms group requires an update or not.
  33005. */
  33006. updateGroup( nodeUniformsGroup ) {
  33007. const groupNode = nodeUniformsGroup.groupNode;
  33008. const name = groupNode.name;
  33009. // objectGroup is always updated
  33010. if ( name === objectGroup.name ) return true;
  33011. // renderGroup is updated once per render/compute call
  33012. if ( name === renderGroup.name ) {
  33013. const uniformsGroupData = this.get( nodeUniformsGroup );
  33014. const renderId = this.nodeFrame.renderId;
  33015. if ( uniformsGroupData.renderId !== renderId ) {
  33016. uniformsGroupData.renderId = renderId;
  33017. return true;
  33018. }
  33019. return false;
  33020. }
  33021. // frameGroup is updated once per frame
  33022. if ( name === frameGroup.name ) {
  33023. const uniformsGroupData = this.get( nodeUniformsGroup );
  33024. const frameId = this.nodeFrame.frameId;
  33025. if ( uniformsGroupData.frameId !== frameId ) {
  33026. uniformsGroupData.frameId = frameId;
  33027. return true;
  33028. }
  33029. return false;
  33030. }
  33031. // other groups are updated just when groupNode.needsUpdate is true
  33032. _chainKeys$2[ 0 ] = groupNode;
  33033. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  33034. let groupData = this.groupsData.get( _chainKeys$2 );
  33035. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  33036. _chainKeys$2.length = 0;
  33037. if ( groupData.version !== groupNode.version ) {
  33038. groupData.version = groupNode.version;
  33039. return true;
  33040. }
  33041. return false;
  33042. }
  33043. /**
  33044. * Returns the cache key for the given render object.
  33045. *
  33046. * @param {RenderObject} renderObject - The render object.
  33047. * @return {number} The cache key.
  33048. */
  33049. getForRenderCacheKey( renderObject ) {
  33050. return renderObject.initialCacheKey;
  33051. }
  33052. /**
  33053. * Returns a node builder state for the given render object.
  33054. *
  33055. * @param {RenderObject} renderObject - The render object.
  33056. * @return {NodeBuilderState} The node builder state.
  33057. */
  33058. getForRender( renderObject ) {
  33059. const renderObjectData = this.get( renderObject );
  33060. let nodeBuilderState = renderObjectData.nodeBuilderState;
  33061. if ( nodeBuilderState === undefined ) {
  33062. const { nodeBuilderCache } = this;
  33063. const cacheKey = this.getForRenderCacheKey( renderObject );
  33064. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  33065. if ( nodeBuilderState === undefined ) {
  33066. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  33067. nodeBuilder.scene = renderObject.scene;
  33068. nodeBuilder.material = renderObject.material;
  33069. nodeBuilder.camera = renderObject.camera;
  33070. nodeBuilder.context.material = renderObject.material;
  33071. nodeBuilder.lightsNode = renderObject.lightsNode;
  33072. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  33073. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  33074. nodeBuilder.clippingContext = renderObject.clippingContext;
  33075. nodeBuilder.build();
  33076. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33077. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  33078. }
  33079. nodeBuilderState.usedTimes ++;
  33080. renderObjectData.nodeBuilderState = nodeBuilderState;
  33081. }
  33082. return nodeBuilderState;
  33083. }
  33084. /**
  33085. * Deletes the given object from the internal data map
  33086. *
  33087. * @param {any} object - The object to delete.
  33088. * @return {?Object} The deleted dictionary.
  33089. */
  33090. delete( object ) {
  33091. if ( object.isRenderObject ) {
  33092. const nodeBuilderState = this.get( object ).nodeBuilderState;
  33093. nodeBuilderState.usedTimes --;
  33094. if ( nodeBuilderState.usedTimes === 0 ) {
  33095. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  33096. }
  33097. }
  33098. return super.delete( object );
  33099. }
  33100. /**
  33101. * Returns a node builder state for the given compute node.
  33102. *
  33103. * @param {Node} computeNode - The compute node.
  33104. * @return {NodeBuilderState} The node builder state.
  33105. */
  33106. getForCompute( computeNode ) {
  33107. const computeData = this.get( computeNode );
  33108. let nodeBuilderState = computeData.nodeBuilderState;
  33109. if ( nodeBuilderState === undefined ) {
  33110. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  33111. nodeBuilder.build();
  33112. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33113. computeData.nodeBuilderState = nodeBuilderState;
  33114. }
  33115. return nodeBuilderState;
  33116. }
  33117. /**
  33118. * Creates a node builder state for the given node builder.
  33119. *
  33120. * @private
  33121. * @param {NodeBuilder} nodeBuilder - The node builder.
  33122. * @return {NodeBuilderState} The node builder state.
  33123. */
  33124. _createNodeBuilderState( nodeBuilder ) {
  33125. return new NodeBuilderState(
  33126. nodeBuilder.vertexShader,
  33127. nodeBuilder.fragmentShader,
  33128. nodeBuilder.computeShader,
  33129. nodeBuilder.getAttributesArray(),
  33130. nodeBuilder.getBindings(),
  33131. nodeBuilder.updateNodes,
  33132. nodeBuilder.updateBeforeNodes,
  33133. nodeBuilder.updateAfterNodes,
  33134. nodeBuilder.observer,
  33135. nodeBuilder.transforms
  33136. );
  33137. }
  33138. /**
  33139. * Returns an environment node for the current configured
  33140. * scene environment.
  33141. *
  33142. * @param {Scene} scene - The scene.
  33143. * @return {Node} A node representing the current scene environment.
  33144. */
  33145. getEnvironmentNode( scene ) {
  33146. this.updateEnvironment( scene );
  33147. let environmentNode = null;
  33148. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  33149. environmentNode = scene.environmentNode;
  33150. } else {
  33151. const sceneData = this.get( scene );
  33152. if ( sceneData.environmentNode ) {
  33153. environmentNode = sceneData.environmentNode;
  33154. }
  33155. }
  33156. return environmentNode;
  33157. }
  33158. /**
  33159. * Returns a background node for the current configured
  33160. * scene background.
  33161. *
  33162. * @param {Scene} scene - The scene.
  33163. * @return {Node} A node representing the current scene background.
  33164. */
  33165. getBackgroundNode( scene ) {
  33166. this.updateBackground( scene );
  33167. let backgroundNode = null;
  33168. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  33169. backgroundNode = scene.backgroundNode;
  33170. } else {
  33171. const sceneData = this.get( scene );
  33172. if ( sceneData.backgroundNode ) {
  33173. backgroundNode = sceneData.backgroundNode;
  33174. }
  33175. }
  33176. return backgroundNode;
  33177. }
  33178. /**
  33179. * Returns a fog node for the current configured scene fog.
  33180. *
  33181. * @param {Scene} scene - The scene.
  33182. * @return {Node} A node representing the current scene fog.
  33183. */
  33184. getFogNode( scene ) {
  33185. this.updateFog( scene );
  33186. return scene.fogNode || this.get( scene ).fogNode || null;
  33187. }
  33188. /**
  33189. * Returns a cache key for the given scene and lights node.
  33190. * This key is used by `RenderObject` as a part of the dynamic
  33191. * cache key (a key that must be checked every time the render
  33192. * objects is drawn).
  33193. *
  33194. * @param {Scene} scene - The scene.
  33195. * @param {LightsNode} lightsNode - The lights node.
  33196. * @return {number} The cache key.
  33197. */
  33198. getCacheKey( scene, lightsNode ) {
  33199. _chainKeys$2[ 0 ] = scene;
  33200. _chainKeys$2[ 1 ] = lightsNode;
  33201. const callId = this.renderer.info.calls;
  33202. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  33203. if ( cacheKeyData.callId !== callId ) {
  33204. const environmentNode = this.getEnvironmentNode( scene );
  33205. const fogNode = this.getFogNode( scene );
  33206. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  33207. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  33208. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  33209. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  33210. cacheKeyData.callId = callId;
  33211. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  33212. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  33213. _cacheKeyValues.length = 0;
  33214. }
  33215. _chainKeys$2.length = 0;
  33216. return cacheKeyData.cacheKey;
  33217. }
  33218. /**
  33219. * A boolean that indicates whether tone mapping should be enabled
  33220. * or not.
  33221. *
  33222. * @type {boolean}
  33223. */
  33224. get isToneMappingState() {
  33225. return this.renderer.getRenderTarget() ? false : true;
  33226. }
  33227. /**
  33228. * If a scene background is configured, this method makes sure to
  33229. * represent the background with a corresponding node-based implementation.
  33230. *
  33231. * @param {Scene} scene - The scene.
  33232. */
  33233. updateBackground( scene ) {
  33234. const sceneData = this.get( scene );
  33235. const background = scene.background;
  33236. if ( background ) {
  33237. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  33238. if ( sceneData.background !== background || forceUpdate ) {
  33239. const backgroundNode = this.getCacheNode( 'background', background, () => {
  33240. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  33241. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  33242. return pmremTexture( background );
  33243. } else {
  33244. let envMap;
  33245. if ( background.isCubeTexture === true ) {
  33246. envMap = cubeTexture( background );
  33247. } else {
  33248. envMap = texture( background );
  33249. }
  33250. return cubeMapNode( envMap );
  33251. }
  33252. } else if ( background.isTexture === true ) {
  33253. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  33254. } else if ( background.isColor !== true ) {
  33255. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  33256. }
  33257. }, forceUpdate );
  33258. sceneData.backgroundNode = backgroundNode;
  33259. sceneData.background = background;
  33260. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  33261. }
  33262. } else if ( sceneData.backgroundNode ) {
  33263. delete sceneData.backgroundNode;
  33264. delete sceneData.background;
  33265. }
  33266. }
  33267. /**
  33268. * This method is part of the caching of nodes which are used to represents the
  33269. * scene's background, fog or environment.
  33270. *
  33271. * @param {string} type - The type of object to cache.
  33272. * @param {Object} object - The object.
  33273. * @param {Function} callback - A callback that produces a node representation for the given object.
  33274. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  33275. * @return {Node} The node representation.
  33276. */
  33277. getCacheNode( type, object, callback, forceUpdate = false ) {
  33278. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  33279. let node = nodeCache.get( object );
  33280. if ( node === undefined || forceUpdate ) {
  33281. node = callback();
  33282. nodeCache.set( object, node );
  33283. }
  33284. return node;
  33285. }
  33286. /**
  33287. * If a scene fog is configured, this method makes sure to
  33288. * represent the fog with a corresponding node-based implementation.
  33289. *
  33290. * @param {Scene} scene - The scene.
  33291. */
  33292. updateFog( scene ) {
  33293. const sceneData = this.get( scene );
  33294. const sceneFog = scene.fog;
  33295. if ( sceneFog ) {
  33296. if ( sceneData.fog !== sceneFog ) {
  33297. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  33298. if ( sceneFog.isFogExp2 ) {
  33299. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33300. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  33301. return fog( color, densityFogFactor( density ) );
  33302. } else if ( sceneFog.isFog ) {
  33303. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33304. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  33305. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  33306. return fog( color, rangeFogFactor( near, far ) );
  33307. } else {
  33308. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  33309. }
  33310. } );
  33311. sceneData.fogNode = fogNode;
  33312. sceneData.fog = sceneFog;
  33313. }
  33314. } else {
  33315. delete sceneData.fogNode;
  33316. delete sceneData.fog;
  33317. }
  33318. }
  33319. /**
  33320. * If a scene environment is configured, this method makes sure to
  33321. * represent the environment with a corresponding node-based implementation.
  33322. *
  33323. * @param {Scene} scene - The scene.
  33324. */
  33325. updateEnvironment( scene ) {
  33326. const sceneData = this.get( scene );
  33327. const environment = scene.environment;
  33328. if ( environment ) {
  33329. if ( sceneData.environment !== environment ) {
  33330. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  33331. if ( environment.isCubeTexture === true ) {
  33332. return cubeTexture( environment );
  33333. } else if ( environment.isTexture === true ) {
  33334. return texture( environment );
  33335. } else {
  33336. console.error( 'Nodes: Unsupported environment configuration.', environment );
  33337. }
  33338. } );
  33339. sceneData.environmentNode = environmentNode;
  33340. sceneData.environment = environment;
  33341. }
  33342. } else if ( sceneData.environmentNode ) {
  33343. delete sceneData.environmentNode;
  33344. delete sceneData.environment;
  33345. }
  33346. }
  33347. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  33348. const nodeFrame = this.nodeFrame;
  33349. nodeFrame.renderer = renderer;
  33350. nodeFrame.scene = scene;
  33351. nodeFrame.object = object;
  33352. nodeFrame.camera = camera;
  33353. nodeFrame.material = material;
  33354. return nodeFrame;
  33355. }
  33356. getNodeFrameForRender( renderObject ) {
  33357. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  33358. }
  33359. /**
  33360. * Returns the current output cache key.
  33361. *
  33362. * @return {string} The output cache key.
  33363. */
  33364. getOutputCacheKey() {
  33365. const renderer = this.renderer;
  33366. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  33367. }
  33368. /**
  33369. * Checks if the output configuration (tone mapping and color space) for
  33370. * the given target has changed.
  33371. *
  33372. * @param {Texture} outputTarget - The output target.
  33373. * @return {boolean} Whether the output configuration has changed or not.
  33374. */
  33375. hasOutputChange( outputTarget ) {
  33376. const cacheKey = _outputNodeMap.get( outputTarget );
  33377. return cacheKey !== this.getOutputCacheKey();
  33378. }
  33379. /**
  33380. * Returns a node that represents the output configuration (tone mapping and
  33381. * color space) for the current target.
  33382. *
  33383. * @param {Texture} outputTarget - The output target.
  33384. * @return {Node} The output node.
  33385. */
  33386. getOutputNode( outputTarget ) {
  33387. const renderer = this.renderer;
  33388. const cacheKey = this.getOutputCacheKey();
  33389. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  33390. _outputNodeMap.set( outputTarget, cacheKey );
  33391. return output;
  33392. }
  33393. /**
  33394. * Triggers the call of `updateBefore()` methods
  33395. * for all nodes of the given render object.
  33396. *
  33397. * @param {RenderObject} renderObject - The render object.
  33398. */
  33399. updateBefore( renderObject ) {
  33400. const nodeBuilder = renderObject.getNodeBuilderState();
  33401. for ( const node of nodeBuilder.updateBeforeNodes ) {
  33402. // update frame state for each node
  33403. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  33404. }
  33405. }
  33406. /**
  33407. * Triggers the call of `updateAfter()` methods
  33408. * for all nodes of the given render object.
  33409. *
  33410. * @param {RenderObject} renderObject - The render object.
  33411. */
  33412. updateAfter( renderObject ) {
  33413. const nodeBuilder = renderObject.getNodeBuilderState();
  33414. for ( const node of nodeBuilder.updateAfterNodes ) {
  33415. // update frame state for each node
  33416. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  33417. }
  33418. }
  33419. /**
  33420. * Triggers the call of `update()` methods
  33421. * for all nodes of the given compute node.
  33422. *
  33423. * @param {Node} computeNode - The compute node.
  33424. */
  33425. updateForCompute( computeNode ) {
  33426. const nodeFrame = this.getNodeFrame();
  33427. const nodeBuilder = this.getForCompute( computeNode );
  33428. for ( const node of nodeBuilder.updateNodes ) {
  33429. nodeFrame.updateNode( node );
  33430. }
  33431. }
  33432. /**
  33433. * Triggers the call of `update()` methods
  33434. * for all nodes of the given compute node.
  33435. *
  33436. * @param {RenderObject} renderObject - The render object.
  33437. */
  33438. updateForRender( renderObject ) {
  33439. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33440. const nodeBuilder = renderObject.getNodeBuilderState();
  33441. for ( const node of nodeBuilder.updateNodes ) {
  33442. nodeFrame.updateNode( node );
  33443. }
  33444. }
  33445. /**
  33446. * Returns `true` if the given render object requires a refresh.
  33447. *
  33448. * @param {RenderObject} renderObject - The render object.
  33449. * @return {boolean} Whether the given render object requires a refresh or not.
  33450. */
  33451. needsRefresh( renderObject ) {
  33452. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33453. const monitor = renderObject.getMonitor();
  33454. return monitor.needsRefresh( renderObject, nodeFrame );
  33455. }
  33456. /**
  33457. * Frees the internal resources.
  33458. */
  33459. dispose() {
  33460. super.dispose();
  33461. this.nodeFrame = new NodeFrame();
  33462. this.nodeBuilderCache = new Map();
  33463. this.cacheLib = {};
  33464. }
  33465. }
  33466. const _plane = /*@__PURE__*/ new Plane();
  33467. /**
  33468. * Represents the state that is used to perform clipping via clipping planes.
  33469. * There is a default clipping context for each render context. When the
  33470. * scene holds instances of `ClippingGroup`, there will be a context for each
  33471. * group.
  33472. *
  33473. * @private
  33474. */
  33475. class ClippingContext {
  33476. /**
  33477. * Constructs a new clipping context.
  33478. *
  33479. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  33480. */
  33481. constructor( parentContext = null ) {
  33482. /**
  33483. * The clipping context's version.
  33484. *
  33485. * @type {number}
  33486. * @readonly
  33487. */
  33488. this.version = 0;
  33489. /**
  33490. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  33491. *
  33492. * @type {?boolean}
  33493. * @default null
  33494. */
  33495. this.clipIntersection = null;
  33496. /**
  33497. * The clipping context's cache key.
  33498. *
  33499. * @type {string}
  33500. */
  33501. this.cacheKey = '';
  33502. /**
  33503. * Whether the shadow pass is active or not.
  33504. *
  33505. * @type {boolean}
  33506. * @default false
  33507. */
  33508. this.shadowPass = false;
  33509. /**
  33510. * The view normal matrix.
  33511. *
  33512. * @type {Matrix3}
  33513. */
  33514. this.viewNormalMatrix = new Matrix3();
  33515. /**
  33516. * Internal cache for maintaining clipping contexts.
  33517. *
  33518. * @type {WeakMap<ClippingGroup,ClippingContext>}
  33519. */
  33520. this.clippingGroupContexts = new WeakMap();
  33521. /**
  33522. * The intersection planes.
  33523. *
  33524. * @type {Array<Vector4>}
  33525. */
  33526. this.intersectionPlanes = [];
  33527. /**
  33528. * The intersection planes.
  33529. *
  33530. * @type {Array<Vector4>}
  33531. */
  33532. this.unionPlanes = [];
  33533. /**
  33534. * The version of the clipping context's parent context.
  33535. *
  33536. * @type {?number}
  33537. * @readonly
  33538. */
  33539. this.parentVersion = null;
  33540. if ( parentContext !== null ) {
  33541. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  33542. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  33543. this.shadowPass = parentContext.shadowPass;
  33544. this.viewMatrix = parentContext.viewMatrix;
  33545. }
  33546. }
  33547. /**
  33548. * Projects the given source clipping planes and writes the result into the
  33549. * destination array.
  33550. *
  33551. * @param {Array<Plane>} source - The source clipping planes.
  33552. * @param {Array<Vector4>} destination - The destination.
  33553. * @param {number} offset - The offset.
  33554. */
  33555. projectPlanes( source, destination, offset ) {
  33556. const l = source.length;
  33557. for ( let i = 0; i < l; i ++ ) {
  33558. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  33559. const v = destination[ offset + i ];
  33560. const normal = _plane.normal;
  33561. v.x = - normal.x;
  33562. v.y = - normal.y;
  33563. v.z = - normal.z;
  33564. v.w = _plane.constant;
  33565. }
  33566. }
  33567. /**
  33568. * Updates the root clipping context of a scene.
  33569. *
  33570. * @param {Scene} scene - The scene.
  33571. * @param {Camera} camera - The camera that is used to render the scene.
  33572. */
  33573. updateGlobal( scene, camera ) {
  33574. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  33575. this.viewMatrix = camera.matrixWorldInverse;
  33576. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  33577. }
  33578. /**
  33579. * Updates the clipping context.
  33580. *
  33581. * @param {ClippingContext} parentContext - The parent context.
  33582. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  33583. */
  33584. update( parentContext, clippingGroup ) {
  33585. let update = false;
  33586. if ( parentContext.version !== this.parentVersion ) {
  33587. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  33588. this.unionPlanes = Array.from( parentContext.unionPlanes );
  33589. this.parentVersion = parentContext.version;
  33590. }
  33591. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  33592. this.clipIntersection = clippingGroup.clipIntersection;
  33593. if ( this.clipIntersection ) {
  33594. this.unionPlanes.length = parentContext.unionPlanes.length;
  33595. } else {
  33596. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  33597. }
  33598. }
  33599. const srcClippingPlanes = clippingGroup.clippingPlanes;
  33600. const l = srcClippingPlanes.length;
  33601. let dstClippingPlanes;
  33602. let offset;
  33603. if ( this.clipIntersection ) {
  33604. dstClippingPlanes = this.intersectionPlanes;
  33605. offset = parentContext.intersectionPlanes.length;
  33606. } else {
  33607. dstClippingPlanes = this.unionPlanes;
  33608. offset = parentContext.unionPlanes.length;
  33609. }
  33610. if ( dstClippingPlanes.length !== offset + l ) {
  33611. dstClippingPlanes.length = offset + l;
  33612. for ( let i = 0; i < l; i ++ ) {
  33613. dstClippingPlanes[ offset + i ] = new Vector4();
  33614. }
  33615. update = true;
  33616. }
  33617. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  33618. if ( update ) {
  33619. this.version ++;
  33620. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  33621. }
  33622. }
  33623. /**
  33624. * Returns a clipping context for the given clipping group.
  33625. *
  33626. * @param {ClippingGroup} clippingGroup - The clipping group.
  33627. * @return {ClippingContext} The clipping context.
  33628. */
  33629. getGroupContext( clippingGroup ) {
  33630. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  33631. let context = this.clippingGroupContexts.get( clippingGroup );
  33632. if ( context === undefined ) {
  33633. context = new ClippingContext( this );
  33634. this.clippingGroupContexts.set( clippingGroup, context );
  33635. }
  33636. context.update( this, clippingGroup );
  33637. return context;
  33638. }
  33639. /**
  33640. * The count of union clipping planes.
  33641. *
  33642. * @type {number}
  33643. * @readonly
  33644. */
  33645. get unionClippingCount() {
  33646. return this.unionPlanes.length;
  33647. }
  33648. }
  33649. /**
  33650. * This module is used to represent render bundles inside the renderer
  33651. * for further processing.
  33652. *
  33653. * @private
  33654. */
  33655. class RenderBundle {
  33656. /**
  33657. * Constructs a new bundle group.
  33658. *
  33659. * @param {BundleGroup} bundleGroup - The bundle group.
  33660. * @param {Camera} camera - The camera the bundle group is rendered with.
  33661. */
  33662. constructor( bundleGroup, camera ) {
  33663. this.bundleGroup = bundleGroup;
  33664. this.camera = camera;
  33665. }
  33666. }
  33667. const _chainKeys$1 = [];
  33668. /**
  33669. * This renderer module manages render bundles.
  33670. *
  33671. * @private
  33672. */
  33673. class RenderBundles {
  33674. /**
  33675. * Constructs a new render bundle management component.
  33676. */
  33677. constructor() {
  33678. /**
  33679. * A chain map for maintaining the render bundles.
  33680. *
  33681. * @type {ChainMap}
  33682. */
  33683. this.bundles = new ChainMap();
  33684. }
  33685. /**
  33686. * Returns a render bundle for the given bundle group and camera.
  33687. *
  33688. * @param {BundleGroup} bundleGroup - The bundle group.
  33689. * @param {Camera} camera - The camera the bundle group is rendered with.
  33690. * @return {RenderBundle} The render bundle.
  33691. */
  33692. get( bundleGroup, camera ) {
  33693. const bundles = this.bundles;
  33694. _chainKeys$1[ 0 ] = bundleGroup;
  33695. _chainKeys$1[ 1 ] = camera;
  33696. let bundle = bundles.get( _chainKeys$1 );
  33697. if ( bundle === undefined ) {
  33698. bundle = new RenderBundle( bundleGroup, camera );
  33699. bundles.set( _chainKeys$1, bundle );
  33700. }
  33701. _chainKeys$1.length = 0;
  33702. return bundle;
  33703. }
  33704. /**
  33705. * Frees all internal resources.
  33706. */
  33707. dispose() {
  33708. this.bundles = new ChainMap();
  33709. }
  33710. }
  33711. /**
  33712. * The purpose of a node library is to assign node implementations
  33713. * to existing library features. In `WebGPURenderer` lights, materials
  33714. * which are not based on `NodeMaterial` as well as tone mapping techniques
  33715. * are implemented with node-based modules.
  33716. *
  33717. * @private
  33718. */
  33719. class NodeLibrary {
  33720. /**
  33721. * Constructs a new node library.
  33722. */
  33723. constructor() {
  33724. /**
  33725. * A weak map that maps lights to light nodes.
  33726. *
  33727. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  33728. */
  33729. this.lightNodes = new WeakMap();
  33730. /**
  33731. * A map that maps materials to node materials.
  33732. *
  33733. * @type {Map<string,NodeMaterial.constructor>}
  33734. */
  33735. this.materialNodes = new Map();
  33736. /**
  33737. * A map that maps tone mapping techniques (constants)
  33738. * to tone mapping node functions.
  33739. *
  33740. * @type {Map<number,Function>}
  33741. */
  33742. this.toneMappingNodes = new Map();
  33743. }
  33744. /**
  33745. * Returns a matching node material instance for the given material object.
  33746. *
  33747. * This method also assigns/copies the properties of the given material object
  33748. * to the node material. This is done to make sure the current material
  33749. * configuration carries over to the node version.
  33750. *
  33751. * @param {Material} material - A material.
  33752. * @return {NodeMaterial} The corresponding node material.
  33753. */
  33754. fromMaterial( material ) {
  33755. if ( material.isNodeMaterial ) return material;
  33756. let nodeMaterial = null;
  33757. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  33758. if ( nodeMaterialClass !== null ) {
  33759. nodeMaterial = new nodeMaterialClass();
  33760. for ( const key in material ) {
  33761. nodeMaterial[ key ] = material[ key ];
  33762. }
  33763. }
  33764. return nodeMaterial;
  33765. }
  33766. /**
  33767. * Adds a tone mapping node function for a tone mapping technique (constant).
  33768. *
  33769. * @param {Function} toneMappingNode - The tone mapping node function.
  33770. * @param {number} toneMapping - The tone mapping.
  33771. */
  33772. addToneMapping( toneMappingNode, toneMapping ) {
  33773. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  33774. }
  33775. /**
  33776. * Returns a tone mapping node function for a tone mapping technique (constant).
  33777. *
  33778. * @param {number} toneMapping - The tone mapping.
  33779. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  33780. */
  33781. getToneMappingFunction( toneMapping ) {
  33782. return this.toneMappingNodes.get( toneMapping ) || null;
  33783. }
  33784. /**
  33785. * Returns a node material class definition for a material type.
  33786. *
  33787. * @param {string} materialType - The material type.
  33788. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  33789. */
  33790. getMaterialNodeClass( materialType ) {
  33791. return this.materialNodes.get( materialType ) || null;
  33792. }
  33793. /**
  33794. * Adds a node material class definition for a given material type.
  33795. *
  33796. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  33797. * @param {string} materialClassType - The material type.
  33798. */
  33799. addMaterial( materialNodeClass, materialClassType ) {
  33800. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  33801. }
  33802. /**
  33803. * Returns a light node class definition for a light class definition.
  33804. *
  33805. * @param {Light.constructor} light - The light class definition.
  33806. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  33807. */
  33808. getLightNodeClass( light ) {
  33809. return this.lightNodes.get( light ) || null;
  33810. }
  33811. /**
  33812. * Adds a light node class definition for a given light class definition.
  33813. *
  33814. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  33815. * @param {Light.constructor} lightClass - The light class definition.
  33816. */
  33817. addLight( lightNodeClass, lightClass ) {
  33818. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  33819. }
  33820. /**
  33821. * Adds a node class definition for the given type to the provided type library.
  33822. *
  33823. * @param {any} nodeClass - The node class definition.
  33824. * @param {number|string} type - The object type.
  33825. * @param {Map} library - The type library.
  33826. */
  33827. addType( nodeClass, type, library ) {
  33828. if ( library.has( type ) ) {
  33829. console.warn( `Redefinition of node ${ type }` );
  33830. return;
  33831. }
  33832. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33833. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  33834. library.set( type, nodeClass );
  33835. }
  33836. /**
  33837. * Adds a node class definition for the given class definition to the provided type library.
  33838. *
  33839. * @param {any} nodeClass - The node class definition.
  33840. * @param {any} baseClass - The class definition.
  33841. * @param {WeakMap} library - The type library.
  33842. */
  33843. addClass( nodeClass, baseClass, library ) {
  33844. if ( library.has( baseClass ) ) {
  33845. console.warn( `Redefinition of node ${ baseClass.name }` );
  33846. return;
  33847. }
  33848. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33849. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  33850. library.set( baseClass, nodeClass );
  33851. }
  33852. }
  33853. const _defaultLights = /*@__PURE__*/ new LightsNode();
  33854. const _chainKeys = [];
  33855. /**
  33856. * This renderer module manages the lights nodes which are unique
  33857. * per scene and camera combination.
  33858. *
  33859. * The lights node itself is later configured in the render list
  33860. * with the actual lights from the scene.
  33861. *
  33862. * @private
  33863. * @augments ChainMap
  33864. */
  33865. class Lighting extends ChainMap {
  33866. /**
  33867. * Constructs a lighting management component.
  33868. */
  33869. constructor() {
  33870. super();
  33871. }
  33872. /**
  33873. * Creates a new lights node for the given array of lights.
  33874. *
  33875. * @param {Array<Light>} lights - The render object.
  33876. * @return {LightsNode} The lights node.
  33877. */
  33878. createNode( lights = [] ) {
  33879. return new LightsNode().setLights( lights );
  33880. }
  33881. /**
  33882. * Returns a lights node for the given scene and camera.
  33883. *
  33884. * @param {Scene} scene - The scene.
  33885. * @param {Camera} camera - The camera.
  33886. * @return {LightsNode} The lights node.
  33887. */
  33888. getNode( scene, camera ) {
  33889. // ignore post-processing
  33890. if ( scene.isQuadMesh ) return _defaultLights;
  33891. _chainKeys[ 0 ] = scene;
  33892. _chainKeys[ 1 ] = camera;
  33893. let node = this.get( _chainKeys );
  33894. if ( node === undefined ) {
  33895. node = this.createNode();
  33896. this.set( _chainKeys, node );
  33897. }
  33898. _chainKeys.length = 0;
  33899. return node;
  33900. }
  33901. }
  33902. /**
  33903. * A special type of render target that is used when rendering
  33904. * with the WebXR Device API.
  33905. *
  33906. * @private
  33907. * @augments RenderTarget
  33908. */
  33909. class XRRenderTarget extends RenderTarget {
  33910. /**
  33911. * Constructs a new XR render target.
  33912. *
  33913. * @param {number} [width=1] - The width of the render target.
  33914. * @param {number} [height=1] - The height of the render target.
  33915. * @param {Object} [options={}] - The configuration options.
  33916. */
  33917. constructor( width = 1, height = 1, options = {} ) {
  33918. super( width, height, options );
  33919. /**
  33920. * This flag can be used for type testing.
  33921. *
  33922. * @type {boolean}
  33923. * @readonly
  33924. * @default true
  33925. */
  33926. this.isXRRenderTarget = true;
  33927. /**
  33928. * Whether the attachments of the render target
  33929. * are defined by external textures. This flag is
  33930. * set to `true` when using the WebXR Layers API.
  33931. *
  33932. * @type {boolean}
  33933. * @default false
  33934. */
  33935. this.hasExternalTextures = false;
  33936. /**
  33937. * Whether a depth buffer should automatically be allocated
  33938. * for this XR render target or not.
  33939. *
  33940. * Allocating a depth buffer is the default behavior of XR render
  33941. * targets. However, when using the WebXR Layers API, this flag
  33942. * must be set to `false` when the `ignoreDepthValues` property of
  33943. * the projection layers evaluates to `false`.
  33944. *
  33945. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  33946. *
  33947. * @type {boolean}
  33948. * @default true
  33949. */
  33950. this.autoAllocateDepthBuffer = true;
  33951. }
  33952. copy( source ) {
  33953. super.copy( source );
  33954. this.hasExternalTextures = source.hasExternalTextures;
  33955. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  33956. return this;
  33957. }
  33958. }
  33959. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33960. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33961. /**
  33962. * The XR manager is built on top of the WebXR Device API to
  33963. * manage XR sessions with `WebGPURenderer`.
  33964. *
  33965. * XR is currently only supported with a WebGL 2 backend.
  33966. *
  33967. * @augments EventDispatcher
  33968. */
  33969. class XRManager extends EventDispatcher {
  33970. /**
  33971. * Constructs a new XR manager.
  33972. *
  33973. * @param {Renderer} renderer - The renderer.
  33974. */
  33975. constructor( renderer ) {
  33976. super();
  33977. /**
  33978. * This flag globally enables XR rendering.
  33979. *
  33980. * @type {boolean}
  33981. * @default false
  33982. */
  33983. this.enabled = false;
  33984. /**
  33985. * Whether the XR device is currently presenting or not.
  33986. *
  33987. * @type {boolean}
  33988. * @default false
  33989. * @readonly
  33990. */
  33991. this.isPresenting = false;
  33992. /**
  33993. * Whether the XR camera should automatically be updated or not.
  33994. *
  33995. * @type {boolean}
  33996. * @default true
  33997. */
  33998. this.cameraAutoUpdate = true;
  33999. /**
  34000. * The renderer.
  34001. *
  34002. * @private
  34003. * @type {Renderer}
  34004. */
  34005. this._renderer = renderer;
  34006. // camera
  34007. /**
  34008. * Represents the camera for the left eye.
  34009. *
  34010. * @private
  34011. * @type {PerspectiveCamera}
  34012. */
  34013. this._cameraL = new PerspectiveCamera();
  34014. this._cameraL.viewport = new Vector4();
  34015. /**
  34016. * Represents the camera for the right eye.
  34017. *
  34018. * @private
  34019. * @type {PerspectiveCamera}
  34020. */
  34021. this._cameraR = new PerspectiveCamera();
  34022. this._cameraR.viewport = new Vector4();
  34023. /**
  34024. * A list of cameras used for rendering the XR views.
  34025. *
  34026. * @private
  34027. * @type {Array<Camera>}
  34028. */
  34029. this._cameras = [ this._cameraL, this._cameraR ];
  34030. /**
  34031. * The main XR camera.
  34032. *
  34033. * @private
  34034. * @type {ArrayCamera}
  34035. */
  34036. this._cameraXR = new ArrayCamera();
  34037. /**
  34038. * The current near value of the XR camera.
  34039. *
  34040. * @private
  34041. * @type {?number}
  34042. * @default null
  34043. */
  34044. this._currentDepthNear = null;
  34045. /**
  34046. * The current far value of the XR camera.
  34047. *
  34048. * @private
  34049. * @type {?number}
  34050. * @default null
  34051. */
  34052. this._currentDepthFar = null;
  34053. /**
  34054. * A list of WebXR controllers requested by the application.
  34055. *
  34056. * @private
  34057. * @type {Array<WebXRController>}
  34058. */
  34059. this._controllers = [];
  34060. /**
  34061. * A list of XR input source. Each input source belongs to
  34062. * an instance of WebXRController.
  34063. *
  34064. * @private
  34065. * @type {Array<XRInputSource?>}
  34066. */
  34067. this._controllerInputSources = [];
  34068. /**
  34069. * The XR render target that represents the rendering destination
  34070. * during an active XR session.
  34071. *
  34072. * @private
  34073. * @type {?RenderTarget}
  34074. * @default null
  34075. */
  34076. this._xrRenderTarget = null;
  34077. /**
  34078. * The current animation context.
  34079. *
  34080. * @private
  34081. * @type {?Window}
  34082. * @default null
  34083. */
  34084. this._currentAnimationContext = null;
  34085. /**
  34086. * The current animation loop.
  34087. *
  34088. * @private
  34089. * @type {?Function}
  34090. * @default null
  34091. */
  34092. this._currentAnimationLoop = null;
  34093. /**
  34094. * The current pixel ratio.
  34095. *
  34096. * @private
  34097. * @type {?number}
  34098. * @default null
  34099. */
  34100. this._currentPixelRatio = null;
  34101. /**
  34102. * The current size of the renderer's canvas
  34103. * in logical pixel unit.
  34104. *
  34105. * @private
  34106. * @type {Vector2}
  34107. */
  34108. this._currentSize = new Vector2();
  34109. /**
  34110. * The default event listener for handling events inside a XR session.
  34111. *
  34112. * @private
  34113. * @type {Function}
  34114. */
  34115. this._onSessionEvent = onSessionEvent.bind( this );
  34116. /**
  34117. * The event listener for handling the end of a XR session.
  34118. *
  34119. * @private
  34120. * @type {Function}
  34121. */
  34122. this._onSessionEnd = onSessionEnd.bind( this );
  34123. /**
  34124. * The event listener for handling the `inputsourceschange` event.
  34125. *
  34126. * @private
  34127. * @type {Function}
  34128. */
  34129. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  34130. /**
  34131. * The animation loop which is used as a replacement for the default
  34132. * animation loop of the applicatio. It is only used when a XR session
  34133. * is active.
  34134. *
  34135. * @private
  34136. * @type {Function}
  34137. */
  34138. this._onAnimationFrame = onAnimationFrame.bind( this );
  34139. /**
  34140. * The current XR reference space.
  34141. *
  34142. * @private
  34143. * @type {?XRReferenceSpace}
  34144. * @default null
  34145. */
  34146. this._referenceSpace = null;
  34147. /**
  34148. * The current XR reference space type.
  34149. *
  34150. * @private
  34151. * @type {string}
  34152. * @default 'local-floor'
  34153. */
  34154. this._referenceSpaceType = 'local-floor';
  34155. /**
  34156. * A custom reference space defined by the application.
  34157. *
  34158. * @private
  34159. * @type {?XRReferenceSpace}
  34160. * @default null
  34161. */
  34162. this._customReferenceSpace = null;
  34163. /**
  34164. * The framebuffer scale factor.
  34165. *
  34166. * @private
  34167. * @type {number}
  34168. * @default 1
  34169. */
  34170. this._framebufferScaleFactor = 1;
  34171. /**
  34172. * The foveation factor.
  34173. *
  34174. * @private
  34175. * @type {number}
  34176. * @default 1
  34177. */
  34178. this._foveation = 1.0;
  34179. /**
  34180. * A reference to the current XR session.
  34181. *
  34182. * @private
  34183. * @type {?XRSession}
  34184. * @default null
  34185. */
  34186. this._session = null;
  34187. /**
  34188. * A reference to the current XR base layer.
  34189. *
  34190. * @private
  34191. * @type {?XRWebGLLayer}
  34192. * @default null
  34193. */
  34194. this._glBaseLayer = null;
  34195. /**
  34196. * A reference to the current XR binding.
  34197. *
  34198. * @private
  34199. * @type {?XRWebGLBinding}
  34200. * @default null
  34201. */
  34202. this._glBinding = null;
  34203. /**
  34204. * A reference to the current XR projection layer.
  34205. *
  34206. * @private
  34207. * @type {?XRProjectionLayer}
  34208. * @default null
  34209. */
  34210. this._glProjLayer = null;
  34211. /**
  34212. * A reference to the current XR frame.
  34213. *
  34214. * @private
  34215. * @type {?XRFrame}
  34216. * @default null
  34217. */
  34218. this._xrFrame = null;
  34219. /**
  34220. * Whether to use the WebXR Layers API or not.
  34221. *
  34222. * @private
  34223. * @type {boolean}
  34224. * @readonly
  34225. */
  34226. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  34227. }
  34228. /**
  34229. * Returns an instance of `THREE.Group` that represents the transformation
  34230. * of a XR controller in target ray space. The requested controller is defined
  34231. * by the given index.
  34232. *
  34233. * @param {number} index - The index of the XR controller.
  34234. * @return {Group} A group that represents the controller's transformation.
  34235. */
  34236. getController( index ) {
  34237. const controller = this._getController( index );
  34238. return controller.getTargetRaySpace();
  34239. }
  34240. /**
  34241. * Returns an instance of `THREE.Group` that represents the transformation
  34242. * of a XR controller in grip space. The requested controller is defined
  34243. * by the given index.
  34244. *
  34245. * @param {number} index - The index of the XR controller.
  34246. * @return {Group} A group that represents the controller's transformation.
  34247. */
  34248. getControllerGrip( index ) {
  34249. const controller = this._getController( index );
  34250. return controller.getGripSpace();
  34251. }
  34252. /**
  34253. * Returns an instance of `THREE.Group` that represents the transformation
  34254. * of a XR controller in hand space. The requested controller is defined
  34255. * by the given index.
  34256. *
  34257. * @param {number} index - The index of the XR controller.
  34258. * @return {Group} A group that represents the controller's transformation.
  34259. */
  34260. getHand( index ) {
  34261. const controller = this._getController( index );
  34262. return controller.getHandSpace();
  34263. }
  34264. /**
  34265. * Returns the foveation value.
  34266. *
  34267. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  34268. */
  34269. getFoveation() {
  34270. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  34271. return undefined;
  34272. }
  34273. return this._foveation;
  34274. }
  34275. /**
  34276. * Sets the foveation value.
  34277. *
  34278. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  34279. * and `1` means maximum foveation (the edges render at lower resolution).
  34280. */
  34281. setFoveation( foveation ) {
  34282. this._foveation = foveation;
  34283. if ( this._glProjLayer !== null ) {
  34284. this._glProjLayer.fixedFoveation = foveation;
  34285. }
  34286. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  34287. this._glBaseLayer.fixedFoveation = foveation;
  34288. }
  34289. }
  34290. /**
  34291. * Returns the framebuffer scale factor.
  34292. *
  34293. * @return {number} The framebuffer scale factor.
  34294. */
  34295. getFramebufferScaleFactor() {
  34296. return this._framebufferScaleFactor;
  34297. }
  34298. /**
  34299. * Sets the framebuffer scale factor.
  34300. *
  34301. * This method can not be used during a XR session.
  34302. *
  34303. * @param {number} factor - The framebuffer scale factor.
  34304. */
  34305. setFramebufferScaleFactor( factor ) {
  34306. this._framebufferScaleFactor = factor;
  34307. if ( this.isPresenting === true ) {
  34308. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  34309. }
  34310. }
  34311. /**
  34312. * Returns the reference space type.
  34313. *
  34314. * @return {string} The reference space type.
  34315. */
  34316. getReferenceSpaceType() {
  34317. return this._referenceSpaceType;
  34318. }
  34319. /**
  34320. * Sets the reference space type.
  34321. *
  34322. * This method can not be used during a XR session.
  34323. *
  34324. * @param {string} type - The reference space type.
  34325. */
  34326. setReferenceSpaceType( type ) {
  34327. this._referenceSpaceType = type;
  34328. if ( this.isPresenting === true ) {
  34329. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  34330. }
  34331. }
  34332. /**
  34333. * Returns the XR reference space.
  34334. *
  34335. * @return {XRReferenceSpace} The XR reference space.
  34336. */
  34337. getReferenceSpace() {
  34338. return this._customReferenceSpace || this._referenceSpace;
  34339. }
  34340. /**
  34341. * Sets a custom XR reference space.
  34342. *
  34343. * @param {XRReferenceSpace} space - The XR reference space.
  34344. */
  34345. setReferenceSpace( space ) {
  34346. this._customReferenceSpace = space;
  34347. }
  34348. /**
  34349. * Returns the XR camera.
  34350. *
  34351. * @return {ArrayCamera} The XR camera.
  34352. */
  34353. getCamera() {
  34354. return this._cameraXR;
  34355. }
  34356. /**
  34357. * Returns the environment blend mode from the current XR session.
  34358. *
  34359. * @return {?('opaque'|'additive'|'alpha-blend')} The environment blend mode. Returns `null` when used outside of a XR session.
  34360. */
  34361. getEnvironmentBlendMode() {
  34362. if ( this._session !== null ) {
  34363. return this._session.environmentBlendMode;
  34364. }
  34365. }
  34366. /**
  34367. * Returns the current XR frame.
  34368. *
  34369. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  34370. */
  34371. getFrame() {
  34372. return this._xrFrame;
  34373. }
  34374. /**
  34375. * Returns the current XR session.
  34376. *
  34377. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  34378. */
  34379. getSession() {
  34380. return this._session;
  34381. }
  34382. /**
  34383. * After a XR session has been requested usually with one of the `*Button` modules, it
  34384. * is injected into the renderer with this method. This method triggers the start of
  34385. * the actual XR rendering.
  34386. *
  34387. * @async
  34388. * @param {XRSession} session - The XR session to set.
  34389. * @return {Promise} A Promise that resolves when the session has been set.
  34390. */
  34391. async setSession( session ) {
  34392. const renderer = this._renderer;
  34393. const backend = renderer.backend;
  34394. const gl = renderer.getContext();
  34395. this._session = session;
  34396. if ( session !== null ) {
  34397. 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.' );
  34398. session.addEventListener( 'select', this._onSessionEvent );
  34399. session.addEventListener( 'selectstart', this._onSessionEvent );
  34400. session.addEventListener( 'selectend', this._onSessionEvent );
  34401. session.addEventListener( 'squeeze', this._onSessionEvent );
  34402. session.addEventListener( 'squeezestart', this._onSessionEvent );
  34403. session.addEventListener( 'squeezeend', this._onSessionEvent );
  34404. session.addEventListener( 'end', this._onSessionEnd );
  34405. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34406. await backend.makeXRCompatible();
  34407. this._currentPixelRatio = renderer.getPixelRatio();
  34408. renderer.getSize( this._currentSize );
  34409. this._currentAnimationContext = renderer._animation.getContext();
  34410. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  34411. renderer._animation.stop();
  34412. //
  34413. if ( this._useLayers === true ) {
  34414. // default path using XRWebGLBinding/XRProjectionLayer
  34415. let depthFormat = null;
  34416. let depthType = null;
  34417. let glDepthFormat = null;
  34418. if ( renderer.depth ) {
  34419. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  34420. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  34421. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  34422. }
  34423. const projectionlayerInit = {
  34424. colorFormat: gl.RGBA8,
  34425. depthFormat: glDepthFormat,
  34426. scaleFactor: this._framebufferScaleFactor
  34427. };
  34428. const glBinding = new XRWebGLBinding( session, gl );
  34429. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  34430. this._glBinding = glBinding;
  34431. this._glProjLayer = glProjLayer;
  34432. session.updateRenderState( { layers: [ glProjLayer ] } );
  34433. renderer.setPixelRatio( 1 );
  34434. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  34435. this._xrRenderTarget = new XRRenderTarget(
  34436. glProjLayer.textureWidth,
  34437. glProjLayer.textureHeight,
  34438. {
  34439. format: RGBAFormat,
  34440. type: UnsignedByteType,
  34441. colorSpace: renderer.outputColorSpace,
  34442. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  34443. stencilBuffer: renderer.stencil,
  34444. samples: renderer.samples
  34445. } );
  34446. this._xrRenderTarget.hasExternalTextures = true;
  34447. } else {
  34448. // fallback to XRWebGLLayer
  34449. const layerInit = {
  34450. antialias: renderer.samples > 0,
  34451. alpha: true,
  34452. depth: renderer.depth,
  34453. stencil: renderer.stencil,
  34454. framebufferScaleFactor: this.getFramebufferScaleFactor()
  34455. };
  34456. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  34457. this._glBaseLayer = glBaseLayer;
  34458. session.updateRenderState( { baseLayer: glBaseLayer } );
  34459. renderer.setPixelRatio( 1 );
  34460. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  34461. this._xrRenderTarget = new XRRenderTarget(
  34462. glBaseLayer.framebufferWidth,
  34463. glBaseLayer.framebufferHeight,
  34464. {
  34465. format: RGBAFormat,
  34466. type: UnsignedByteType,
  34467. colorSpace: renderer.outputColorSpace,
  34468. stencilBuffer: renderer.stencil
  34469. }
  34470. );
  34471. }
  34472. //
  34473. this.setFoveation( this.getFoveation() );
  34474. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  34475. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  34476. renderer._animation.setContext( session );
  34477. renderer._animation.start();
  34478. this.isPresenting = true;
  34479. this.dispatchEvent( { type: 'sessionstart' } );
  34480. }
  34481. }
  34482. /**
  34483. * This method is called by the renderer per frame and updates the XR camera
  34484. * and it sub cameras based on the given camera. The given camera is the "user"
  34485. * camera created on application level and used for non-XR rendering.
  34486. *
  34487. * @param {PerspectiveCamera} camera - The camera.
  34488. */
  34489. updateCamera( camera ) {
  34490. const session = this._session;
  34491. if ( session === null ) return;
  34492. const depthNear = camera.near;
  34493. const depthFar = camera.far;
  34494. const cameraXR = this._cameraXR;
  34495. const cameraL = this._cameraL;
  34496. const cameraR = this._cameraR;
  34497. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  34498. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  34499. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  34500. // Note that the new renderState won't apply until the next frame. See #18320
  34501. session.updateRenderState( {
  34502. depthNear: cameraXR.near,
  34503. depthFar: cameraXR.far
  34504. } );
  34505. this._currentDepthNear = cameraXR.near;
  34506. this._currentDepthFar = cameraXR.far;
  34507. }
  34508. cameraL.layers.mask = camera.layers.mask | 0b010;
  34509. cameraR.layers.mask = camera.layers.mask | 0b100;
  34510. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  34511. const parent = camera.parent;
  34512. const cameras = cameraXR.cameras;
  34513. updateCamera( cameraXR, parent );
  34514. for ( let i = 0; i < cameras.length; i ++ ) {
  34515. updateCamera( cameras[ i ], parent );
  34516. }
  34517. // update projection matrix for proper view frustum culling
  34518. if ( cameras.length === 2 ) {
  34519. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  34520. } else {
  34521. // assume single camera setup (AR)
  34522. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  34523. }
  34524. // update user camera and its children
  34525. updateUserCamera( camera, cameraXR, parent );
  34526. }
  34527. /**
  34528. * Returns a WebXR controller for the given controller index.
  34529. *
  34530. * @private
  34531. * @param {number} index - The controller index.
  34532. * @return {WebXRController} The XR controller.
  34533. */
  34534. _getController( index ) {
  34535. let controller = this._controllers[ index ];
  34536. if ( controller === undefined ) {
  34537. controller = new WebXRController();
  34538. this._controllers[ index ] = controller;
  34539. }
  34540. return controller;
  34541. }
  34542. }
  34543. /**
  34544. * Assumes 2 cameras that are parallel and share an X-axis, and that
  34545. * the cameras' projection and world matrices have already been set.
  34546. * And that near and far planes are identical for both cameras.
  34547. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  34548. *
  34549. * @param {ArrayCamera} camera - The camera to update.
  34550. * @param {PerspectiveCamera} cameraL - The left camera.
  34551. * @param {PerspectiveCamera} cameraR - The right camera.
  34552. */
  34553. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  34554. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  34555. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  34556. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  34557. const projL = cameraL.projectionMatrix.elements;
  34558. const projR = cameraR.projectionMatrix.elements;
  34559. // VR systems will have identical far and near planes, and
  34560. // most likely identical top and bottom frustum extents.
  34561. // Use the left camera for these values.
  34562. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  34563. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  34564. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  34565. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  34566. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  34567. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  34568. const left = near * leftFov;
  34569. const right = near * rightFov;
  34570. // Calculate the new camera's position offset from the
  34571. // left camera. xOffset should be roughly half `ipd`.
  34572. const zOffset = ipd / ( - leftFov + rightFov );
  34573. const xOffset = zOffset * - leftFov;
  34574. // TODO: Better way to apply this offset?
  34575. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  34576. camera.translateX( xOffset );
  34577. camera.translateZ( zOffset );
  34578. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  34579. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34580. // Check if the projection uses an infinite far plane.
  34581. if ( projL[ 10 ] === -1 ) {
  34582. // Use the projection matrix from the left eye.
  34583. // The camera offset is sufficient to include the view volumes
  34584. // of both eyes (assuming symmetric projections).
  34585. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  34586. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  34587. } else {
  34588. // Find the union of the frustum values of the cameras and scale
  34589. // the values so that the near plane's position does not change in world space,
  34590. // although must now be relative to the new union camera.
  34591. const near2 = near + zOffset;
  34592. const far2 = far + zOffset;
  34593. const left2 = left - xOffset;
  34594. const right2 = right + ( ipd - xOffset );
  34595. const top2 = topFov * far / far2 * near2;
  34596. const bottom2 = bottomFov * far / far2 * near2;
  34597. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  34598. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34599. }
  34600. }
  34601. /**
  34602. * Updates the world matrices for the given camera based on the parent 3D object.
  34603. *
  34604. * @inner
  34605. * @param {Camera} camera - The camera to update.
  34606. * @param {Object3D} parent - The parent 3D object.
  34607. */
  34608. function updateCamera( camera, parent ) {
  34609. if ( parent === null ) {
  34610. camera.matrixWorld.copy( camera.matrix );
  34611. } else {
  34612. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  34613. }
  34614. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34615. }
  34616. /**
  34617. * Updates the given camera with the transfomration of the XR camera and parent object.
  34618. *
  34619. * @inner
  34620. * @param {Camera} camera - The camera to update.
  34621. * @param {ArrayCamera} cameraXR - The XR camera.
  34622. * @param {Object3D} parent - The parent 3D object.
  34623. */
  34624. function updateUserCamera( camera, cameraXR, parent ) {
  34625. if ( parent === null ) {
  34626. camera.matrix.copy( cameraXR.matrixWorld );
  34627. } else {
  34628. camera.matrix.copy( parent.matrixWorld );
  34629. camera.matrix.invert();
  34630. camera.matrix.multiply( cameraXR.matrixWorld );
  34631. }
  34632. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34633. camera.updateMatrixWorld( true );
  34634. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  34635. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  34636. if ( camera.isPerspectiveCamera ) {
  34637. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  34638. camera.zoom = 1;
  34639. }
  34640. }
  34641. function onSessionEvent( event ) {
  34642. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  34643. if ( controllerIndex === -1 ) {
  34644. return;
  34645. }
  34646. const controller = this._controllers[ controllerIndex ];
  34647. if ( controller !== undefined ) {
  34648. const referenceSpace = this.getReferenceSpace();
  34649. controller.update( event.inputSource, event.frame, referenceSpace );
  34650. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  34651. }
  34652. }
  34653. function onSessionEnd() {
  34654. const session = this._session;
  34655. const renderer = this._renderer;
  34656. session.removeEventListener( 'select', this._onSessionEvent );
  34657. session.removeEventListener( 'selectstart', this._onSessionEvent );
  34658. session.removeEventListener( 'selectend', this._onSessionEvent );
  34659. session.removeEventListener( 'squeeze', this._onSessionEvent );
  34660. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  34661. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  34662. session.removeEventListener( 'end', this._onSessionEnd );
  34663. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34664. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34665. const inputSource = this._controllerInputSources[ i ];
  34666. if ( inputSource === null ) continue;
  34667. this._controllerInputSources[ i ] = null;
  34668. this._controllers[ i ].disconnect( inputSource );
  34669. }
  34670. this._currentDepthNear = null;
  34671. this._currentDepthFar = null;
  34672. // restore framebuffer/rendering state
  34673. renderer.backend.setXRTarget( null );
  34674. renderer.setOutputRenderTarget( null );
  34675. this._session = null;
  34676. this._xrRenderTarget = null;
  34677. //
  34678. this.isPresenting = false;
  34679. renderer._animation.stop();
  34680. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  34681. renderer._animation.setContext( this._currentAnimationContext );
  34682. renderer._animation.start();
  34683. renderer.setPixelRatio( this._currentPixelRatio );
  34684. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  34685. this.dispatchEvent( { type: 'sessionend' } );
  34686. }
  34687. function onInputSourcesChange( event ) {
  34688. const controllers = this._controllers;
  34689. const controllerInputSources = this._controllerInputSources;
  34690. // Notify disconnected
  34691. for ( let i = 0; i < event.removed.length; i ++ ) {
  34692. const inputSource = event.removed[ i ];
  34693. const index = controllerInputSources.indexOf( inputSource );
  34694. if ( index >= 0 ) {
  34695. controllerInputSources[ index ] = null;
  34696. controllers[ index ].disconnect( inputSource );
  34697. }
  34698. }
  34699. // Notify connected
  34700. for ( let i = 0; i < event.added.length; i ++ ) {
  34701. const inputSource = event.added[ i ];
  34702. let controllerIndex = controllerInputSources.indexOf( inputSource );
  34703. if ( controllerIndex === -1 ) {
  34704. // Assign input source a controller that currently has no input source
  34705. for ( let i = 0; i < controllers.length; i ++ ) {
  34706. if ( i >= controllerInputSources.length ) {
  34707. controllerInputSources.push( inputSource );
  34708. controllerIndex = i;
  34709. break;
  34710. } else if ( controllerInputSources[ i ] === null ) {
  34711. controllerInputSources[ i ] = inputSource;
  34712. controllerIndex = i;
  34713. break;
  34714. }
  34715. }
  34716. // If all controllers do currently receive input we ignore new ones
  34717. if ( controllerIndex === -1 ) break;
  34718. }
  34719. const controller = controllers[ controllerIndex ];
  34720. if ( controller ) {
  34721. controller.connect( inputSource );
  34722. }
  34723. }
  34724. }
  34725. function onAnimationFrame( time, frame ) {
  34726. if ( frame === undefined ) return;
  34727. const cameraXR = this._cameraXR;
  34728. const renderer = this._renderer;
  34729. const backend = renderer.backend;
  34730. const glBaseLayer = this._glBaseLayer;
  34731. const referenceSpace = this.getReferenceSpace();
  34732. const pose = frame.getViewerPose( referenceSpace );
  34733. this._xrFrame = frame;
  34734. if ( pose !== null ) {
  34735. const views = pose.views;
  34736. if ( this._glBaseLayer !== null ) {
  34737. backend.setXRTarget( glBaseLayer.framebuffer );
  34738. }
  34739. let cameraXRNeedsUpdate = false;
  34740. // check if it's necessary to rebuild cameraXR's camera list
  34741. if ( views.length !== cameraXR.cameras.length ) {
  34742. cameraXR.cameras.length = 0;
  34743. cameraXRNeedsUpdate = true;
  34744. }
  34745. for ( let i = 0; i < views.length; i ++ ) {
  34746. const view = views[ i ];
  34747. let viewport;
  34748. if ( this._useLayers === true ) {
  34749. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  34750. viewport = glSubImage.viewport;
  34751. // For side-by-side projection, we only produce a single texture for both eyes.
  34752. if ( i === 0 ) {
  34753. backend.setXRRenderTargetTextures(
  34754. this._xrRenderTarget,
  34755. glSubImage.colorTexture,
  34756. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  34757. );
  34758. }
  34759. } else {
  34760. viewport = glBaseLayer.getViewport( view );
  34761. }
  34762. let camera = this._cameras[ i ];
  34763. if ( camera === undefined ) {
  34764. camera = new PerspectiveCamera();
  34765. camera.layers.enable( i );
  34766. camera.viewport = new Vector4();
  34767. this._cameras[ i ] = camera;
  34768. }
  34769. camera.matrix.fromArray( view.transform.matrix );
  34770. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34771. camera.projectionMatrix.fromArray( view.projectionMatrix );
  34772. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34773. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  34774. if ( i === 0 ) {
  34775. cameraXR.matrix.copy( camera.matrix );
  34776. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  34777. }
  34778. if ( cameraXRNeedsUpdate === true ) {
  34779. cameraXR.cameras.push( camera );
  34780. }
  34781. }
  34782. renderer.setOutputRenderTarget( this._xrRenderTarget );
  34783. }
  34784. //
  34785. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34786. const inputSource = this._controllerInputSources[ i ];
  34787. const controller = this._controllers[ i ];
  34788. if ( inputSource !== null && controller !== undefined ) {
  34789. controller.update( inputSource, frame, referenceSpace );
  34790. }
  34791. }
  34792. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  34793. if ( frame.detectedPlanes ) {
  34794. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  34795. }
  34796. this._xrFrame = null;
  34797. }
  34798. const _scene = /*@__PURE__*/ new Scene();
  34799. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  34800. const _screen = /*@__PURE__*/ new Vector4();
  34801. const _frustum = /*@__PURE__*/ new Frustum();
  34802. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  34803. const _vector4 = /*@__PURE__*/ new Vector4();
  34804. /**
  34805. * Base class for renderers.
  34806. */
  34807. class Renderer {
  34808. /**
  34809. * Constructs a new renderer.
  34810. *
  34811. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  34812. * @param {Object} parameters - The configuration parameter.
  34813. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  34814. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  34815. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  34816. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  34817. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  34818. * @param {number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  34819. * to overwrite the default.
  34820. * @param {?Function} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34821. * @param {number} [parameters.colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  34822. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  34823. */
  34824. constructor( backend, parameters = {} ) {
  34825. /**
  34826. * This flag can be used for type testing.
  34827. *
  34828. * @type {boolean}
  34829. * @readonly
  34830. * @default true
  34831. */
  34832. this.isRenderer = true;
  34833. //
  34834. const {
  34835. logarithmicDepthBuffer = false,
  34836. alpha = true,
  34837. depth = true,
  34838. stencil = false,
  34839. antialias = false,
  34840. samples = 0,
  34841. getFallback = null,
  34842. colorBufferType = HalfFloatType
  34843. } = parameters;
  34844. /**
  34845. * A reference to the canvas element the renderer is drawing to.
  34846. * This value of this property will automatically be created by
  34847. * the renderer.
  34848. *
  34849. * @type {HTMLCanvasElement|OffscreenCanvas}
  34850. */
  34851. this.domElement = backend.getDomElement();
  34852. /**
  34853. * A reference to the current backend.
  34854. *
  34855. * @type {Backend}
  34856. */
  34857. this.backend = backend;
  34858. /**
  34859. * The number of MSAA samples.
  34860. *
  34861. * @type {number}
  34862. * @default 0
  34863. */
  34864. this.samples = samples || ( antialias === true ) ? 4 : 0;
  34865. /**
  34866. * Whether the renderer should automatically clear the current rendering target
  34867. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  34868. * or the current bound render target (custom framebuffer).
  34869. *
  34870. * @type {boolean}
  34871. * @default true
  34872. */
  34873. this.autoClear = true;
  34874. /**
  34875. * When `autoClear` is set to `true`, this property defines whether the renderer
  34876. * should clear the color buffer.
  34877. *
  34878. * @type {boolean}
  34879. * @default true
  34880. */
  34881. this.autoClearColor = true;
  34882. /**
  34883. * When `autoClear` is set to `true`, this property defines whether the renderer
  34884. * should clear the depth buffer.
  34885. *
  34886. * @type {boolean}
  34887. * @default true
  34888. */
  34889. this.autoClearDepth = true;
  34890. /**
  34891. * When `autoClear` is set to `true`, this property defines whether the renderer
  34892. * should clear the stencil buffer.
  34893. *
  34894. * @type {boolean}
  34895. * @default true
  34896. */
  34897. this.autoClearStencil = true;
  34898. /**
  34899. * Whether the default framebuffer should be transparent or opaque.
  34900. *
  34901. * @type {boolean}
  34902. * @default true
  34903. */
  34904. this.alpha = alpha;
  34905. /**
  34906. * Whether logarithmic depth buffer is enabled or not.
  34907. *
  34908. * @type {boolean}
  34909. * @default false
  34910. */
  34911. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  34912. /**
  34913. * Defines the output color space of the renderer.
  34914. *
  34915. * @type {string}
  34916. * @default SRGBColorSpace
  34917. */
  34918. this.outputColorSpace = SRGBColorSpace;
  34919. /**
  34920. * Defines the tone mapping of the renderer.
  34921. *
  34922. * @type {number}
  34923. * @default NoToneMapping
  34924. */
  34925. this.toneMapping = NoToneMapping;
  34926. /**
  34927. * Defines the tone mapping exposure.
  34928. *
  34929. * @type {number}
  34930. * @default 1
  34931. */
  34932. this.toneMappingExposure = 1.0;
  34933. /**
  34934. * Whether the renderer should sort its render lists or not.
  34935. *
  34936. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  34937. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  34938. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  34939. * e.g. manually determining each object's rendering order.
  34940. *
  34941. * @type {boolean}
  34942. * @default true
  34943. */
  34944. this.sortObjects = true;
  34945. /**
  34946. * Whether the default framebuffer should have a depth buffer or not.
  34947. *
  34948. * @type {boolean}
  34949. * @default true
  34950. */
  34951. this.depth = depth;
  34952. /**
  34953. * Whether the default framebuffer should have a stencil buffer or not.
  34954. *
  34955. * @type {boolean}
  34956. * @default false
  34957. */
  34958. this.stencil = stencil;
  34959. /**
  34960. * Holds a series of statistical information about the GPU memory
  34961. * and the rendering process. Useful for debugging and monitoring.
  34962. *
  34963. * @type {Info}
  34964. */
  34965. this.info = new Info();
  34966. this.nodes = {
  34967. modelViewMatrix: null,
  34968. modelNormalViewMatrix: null
  34969. };
  34970. /**
  34971. * The node library defines how certain library objects like materials, lights
  34972. * or tone mapping functions are mapped to node types. This is required since
  34973. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  34974. * be part of the scene graph, they are internally represented as nodes for
  34975. * further processing.
  34976. *
  34977. * @type {NodeLibrary}
  34978. */
  34979. this.library = new NodeLibrary();
  34980. /**
  34981. * A map-like data structure for managing lights.
  34982. *
  34983. * @type {Lighting}
  34984. */
  34985. this.lighting = new Lighting();
  34986. // internals
  34987. /**
  34988. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34989. *
  34990. * @private
  34991. * @type {Function}
  34992. */
  34993. this._getFallback = getFallback;
  34994. /**
  34995. * The renderer's pixel ration.
  34996. *
  34997. * @private
  34998. * @type {number}
  34999. * @default 1
  35000. */
  35001. this._pixelRatio = 1;
  35002. /**
  35003. * The width of the renderer's default framebuffer in logical pixel unit.
  35004. *
  35005. * @private
  35006. * @type {number}
  35007. */
  35008. this._width = this.domElement.width;
  35009. /**
  35010. * The height of the renderer's default framebuffer in logical pixel unit.
  35011. *
  35012. * @private
  35013. * @type {number}
  35014. */
  35015. this._height = this.domElement.height;
  35016. /**
  35017. * The viewport of the renderer in logical pixel unit.
  35018. *
  35019. * @private
  35020. * @type {Vector4}
  35021. */
  35022. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35023. /**
  35024. * The scissor rectangle of the renderer in logical pixel unit.
  35025. *
  35026. * @private
  35027. * @type {Vector4}
  35028. */
  35029. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35030. /**
  35031. * Whether the scissor test should be enabled or not.
  35032. *
  35033. * @private
  35034. * @type {boolean}
  35035. */
  35036. this._scissorTest = false;
  35037. /**
  35038. * A reference to a renderer module for managing shader attributes.
  35039. *
  35040. * @private
  35041. * @type {?Attributes}
  35042. * @default null
  35043. */
  35044. this._attributes = null;
  35045. /**
  35046. * A reference to a renderer module for managing geometries.
  35047. *
  35048. * @private
  35049. * @type {?Geometries}
  35050. * @default null
  35051. */
  35052. this._geometries = null;
  35053. /**
  35054. * A reference to a renderer module for managing node related logic.
  35055. *
  35056. * @private
  35057. * @type {?Nodes}
  35058. * @default null
  35059. */
  35060. this._nodes = null;
  35061. /**
  35062. * A reference to a renderer module for managing the internal animation loop.
  35063. *
  35064. * @private
  35065. * @type {?Animation}
  35066. * @default null
  35067. */
  35068. this._animation = null;
  35069. /**
  35070. * A reference to a renderer module for managing shader program bindings.
  35071. *
  35072. * @private
  35073. * @type {?Bindings}
  35074. * @default null
  35075. */
  35076. this._bindings = null;
  35077. /**
  35078. * A reference to a renderer module for managing render objects.
  35079. *
  35080. * @private
  35081. * @type {?RenderObjects}
  35082. * @default null
  35083. */
  35084. this._objects = null;
  35085. /**
  35086. * A reference to a renderer module for managing render and compute pipelines.
  35087. *
  35088. * @private
  35089. * @type {?Pipelines}
  35090. * @default null
  35091. */
  35092. this._pipelines = null;
  35093. /**
  35094. * A reference to a renderer module for managing render bundles.
  35095. *
  35096. * @private
  35097. * @type {?RenderBundles}
  35098. * @default null
  35099. */
  35100. this._bundles = null;
  35101. /**
  35102. * A reference to a renderer module for managing render lists.
  35103. *
  35104. * @private
  35105. * @type {?RenderLists}
  35106. * @default null
  35107. */
  35108. this._renderLists = null;
  35109. /**
  35110. * A reference to a renderer module for managing render contexts.
  35111. *
  35112. * @private
  35113. * @type {?RenderContexts}
  35114. * @default null
  35115. */
  35116. this._renderContexts = null;
  35117. /**
  35118. * A reference to a renderer module for managing textures.
  35119. *
  35120. * @private
  35121. * @type {?Textures}
  35122. * @default null
  35123. */
  35124. this._textures = null;
  35125. /**
  35126. * A reference to a renderer module for backgrounds.
  35127. *
  35128. * @private
  35129. * @type {?Background}
  35130. * @default null
  35131. */
  35132. this._background = null;
  35133. /**
  35134. * This fullscreen quad is used for internal render passes
  35135. * like the tone mapping and color space output pass.
  35136. *
  35137. * @private
  35138. * @type {QuadMesh}
  35139. */
  35140. this._quad = new QuadMesh( new NodeMaterial() );
  35141. this._quad.material.name = 'Renderer_output';
  35142. /**
  35143. * A reference to the current render context.
  35144. *
  35145. * @private
  35146. * @type {?RenderContext}
  35147. * @default null
  35148. */
  35149. this._currentRenderContext = null;
  35150. /**
  35151. * A custom sort function for the opaque render list.
  35152. *
  35153. * @private
  35154. * @type {?Function}
  35155. * @default null
  35156. */
  35157. this._opaqueSort = null;
  35158. /**
  35159. * A custom sort function for the transparent render list.
  35160. *
  35161. * @private
  35162. * @type {?Function}
  35163. * @default null
  35164. */
  35165. this._transparentSort = null;
  35166. /**
  35167. * The framebuffer target.
  35168. *
  35169. * @private
  35170. * @type {?RenderTarget}
  35171. * @default null
  35172. */
  35173. this._frameBufferTarget = null;
  35174. const alphaClear = this.alpha === true ? 0 : 1;
  35175. /**
  35176. * The clear color value.
  35177. *
  35178. * @private
  35179. * @type {Color4}
  35180. */
  35181. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35182. /**
  35183. * The clear depth value.
  35184. *
  35185. * @private
  35186. * @type {number}
  35187. * @default 1
  35188. */
  35189. this._clearDepth = 1;
  35190. /**
  35191. * The clear stencil value.
  35192. *
  35193. * @private
  35194. * @type {number}
  35195. * @default 0
  35196. */
  35197. this._clearStencil = 0;
  35198. /**
  35199. * The current render target.
  35200. *
  35201. * @private
  35202. * @type {?RenderTarget}
  35203. * @default null
  35204. */
  35205. this._renderTarget = null;
  35206. /**
  35207. * The active cube face.
  35208. *
  35209. * @private
  35210. * @type {number}
  35211. * @default 0
  35212. */
  35213. this._activeCubeFace = 0;
  35214. /**
  35215. * The active mipmap level.
  35216. *
  35217. * @private
  35218. * @type {number}
  35219. * @default 0
  35220. */
  35221. this._activeMipmapLevel = 0;
  35222. /**
  35223. * The current output render target.
  35224. *
  35225. * @private
  35226. * @type {?RenderTarget}
  35227. * @default null
  35228. */
  35229. this._outputRenderTarget = null;
  35230. /**
  35231. * The MRT setting.
  35232. *
  35233. * @private
  35234. * @type {?MRTNode}
  35235. * @default null
  35236. */
  35237. this._mrt = null;
  35238. /**
  35239. * This function defines how a render object is going
  35240. * to be rendered.
  35241. *
  35242. * @private
  35243. * @type {?Function}
  35244. * @default null
  35245. */
  35246. this._renderObjectFunction = null;
  35247. /**
  35248. * Used to keep track of the current render object function.
  35249. *
  35250. * @private
  35251. * @type {?Function}
  35252. * @default null
  35253. */
  35254. this._currentRenderObjectFunction = null;
  35255. /**
  35256. * Used to keep track of the current render bundle.
  35257. *
  35258. * @private
  35259. * @type {?RenderBundle}
  35260. * @default null
  35261. */
  35262. this._currentRenderBundle = null;
  35263. /**
  35264. * Next to `_renderObjectFunction()`, this function provides another hook
  35265. * for influencing the render process of a render object. It is meant for internal
  35266. * use and only relevant for `compileAsync()` right now. Instead of using
  35267. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  35268. * a different function might be used which performs no draw but just the node
  35269. * and pipeline updates.
  35270. *
  35271. * @private
  35272. * @type {?Function}
  35273. * @default null
  35274. */
  35275. this._handleObjectFunction = this._renderObjectDirect;
  35276. /**
  35277. * Indicates whether the device has been lost or not. In WebGL terms, the device
  35278. * lost is considered as a context lost. When this is set to `true`, rendering
  35279. * isn't possible anymore.
  35280. *
  35281. * @private
  35282. * @type {boolean}
  35283. * @default false
  35284. */
  35285. this._isDeviceLost = false;
  35286. /**
  35287. * A callback function that defines what should happen when a device/context lost occurs.
  35288. *
  35289. * @type {Function}
  35290. */
  35291. this.onDeviceLost = this._onDeviceLost;
  35292. /**
  35293. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  35294. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  35295. * This will reduce rendering quality though.
  35296. *
  35297. * @private
  35298. * @type {number}
  35299. * @default HalfFloatType
  35300. */
  35301. this._colorBufferType = colorBufferType;
  35302. /**
  35303. * Whether the renderer has been initialized or not.
  35304. *
  35305. * @private
  35306. * @type {boolean}
  35307. * @default false
  35308. */
  35309. this._initialized = false;
  35310. /**
  35311. * A reference to the promise which initializes the renderer.
  35312. *
  35313. * @private
  35314. * @type {?Promise}
  35315. * @default null
  35316. */
  35317. this._initPromise = null;
  35318. /**
  35319. * An array of compilation promises which are used in `compileAsync()`.
  35320. *
  35321. * @private
  35322. * @type {?Array<Promise>}
  35323. * @default null
  35324. */
  35325. this._compilationPromises = null;
  35326. /**
  35327. * Whether the renderer should render transparent render objects or not.
  35328. *
  35329. * @type {boolean}
  35330. * @default true
  35331. */
  35332. this.transparent = true;
  35333. /**
  35334. * Whether the renderer should render opaque render objects or not.
  35335. *
  35336. * @type {boolean}
  35337. * @default true
  35338. */
  35339. this.opaque = true;
  35340. /**
  35341. * Shadow map configuration
  35342. * @typedef {Object} ShadowMapConfig
  35343. * @property {boolean} enabled - Whether to globally enable shadows or not.
  35344. * @property {number} type - The shadow map type.
  35345. */
  35346. /**
  35347. * The renderer's shadow configuration.
  35348. *
  35349. * @type {ShadowMapConfig}
  35350. */
  35351. this.shadowMap = {
  35352. enabled: false,
  35353. type: PCFShadowMap
  35354. };
  35355. /**
  35356. * XR configuration.
  35357. * @typedef {Object} XRConfig
  35358. * @property {boolean} enabled - Whether to globally enable XR or not.
  35359. */
  35360. /**
  35361. * The renderer's XR manager.
  35362. *
  35363. * @type {XRManager}
  35364. */
  35365. this.xr = new XRManager( this );
  35366. /**
  35367. * Debug configuration.
  35368. * @typedef {Object} DebugConfig
  35369. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  35370. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  35371. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  35372. */
  35373. /**
  35374. * The renderer's debug configuration.
  35375. *
  35376. * @type {DebugConfig}
  35377. */
  35378. this.debug = {
  35379. checkShaderErrors: true,
  35380. onShaderError: null,
  35381. getShaderAsync: async ( scene, camera, object ) => {
  35382. await this.compileAsync( scene, camera );
  35383. const renderList = this._renderLists.get( scene, camera );
  35384. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  35385. const material = scene.overrideMaterial || object.material;
  35386. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  35387. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  35388. return { fragmentShader, vertexShader };
  35389. }
  35390. };
  35391. }
  35392. /**
  35393. * Initializes the renderer so it is ready for usage.
  35394. *
  35395. * @async
  35396. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  35397. */
  35398. async init() {
  35399. if ( this._initialized ) {
  35400. throw new Error( 'Renderer: Backend has already been initialized.' );
  35401. }
  35402. if ( this._initPromise !== null ) {
  35403. return this._initPromise;
  35404. }
  35405. this._initPromise = new Promise( async ( resolve, reject ) => {
  35406. let backend = this.backend;
  35407. try {
  35408. await backend.init( this );
  35409. } catch ( error ) {
  35410. if ( this._getFallback !== null ) {
  35411. // try the fallback
  35412. try {
  35413. this.backend = backend = this._getFallback( error );
  35414. await backend.init( this );
  35415. } catch ( error ) {
  35416. reject( error );
  35417. return;
  35418. }
  35419. } else {
  35420. reject( error );
  35421. return;
  35422. }
  35423. }
  35424. this._nodes = new Nodes( this, backend );
  35425. this._animation = new Animation( this._nodes, this.info );
  35426. this._attributes = new Attributes( backend );
  35427. this._background = new Background( this, this._nodes );
  35428. this._geometries = new Geometries( this._attributes, this.info );
  35429. this._textures = new Textures( this, backend, this.info );
  35430. this._pipelines = new Pipelines( backend, this._nodes );
  35431. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35432. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35433. this._renderLists = new RenderLists( this.lighting );
  35434. this._bundles = new RenderBundles();
  35435. this._renderContexts = new RenderContexts();
  35436. //
  35437. this._animation.start();
  35438. this._initialized = true;
  35439. resolve();
  35440. } );
  35441. return this._initPromise;
  35442. }
  35443. /**
  35444. * The coordinate system of the renderer. The value of this property
  35445. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  35446. * `THREE.WebGPUCoordinateSystem`.
  35447. *
  35448. * @readonly
  35449. * @type {number}
  35450. */
  35451. get coordinateSystem() {
  35452. return this.backend.coordinateSystem;
  35453. }
  35454. /**
  35455. * Compiles all materials in the given scene. This can be useful to avoid a
  35456. * phenomenon which is called "shader compilation stutter", which occurs when
  35457. * rendering an object with a new shader for the first time.
  35458. *
  35459. * If you want to add a 3D object to an existing scene, use the third optional
  35460. * parameter for applying the target scene. Note that the (target) scene's lighting
  35461. * and environment must be configured before calling this method.
  35462. *
  35463. * @async
  35464. * @param {Object3D} scene - The scene or 3D object to precompile.
  35465. * @param {Camera} camera - The camera that is used to render the scene.
  35466. * @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.
  35467. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  35468. */
  35469. async compileAsync( scene, camera, targetScene = null ) {
  35470. if ( this._isDeviceLost === true ) return;
  35471. if ( this._initialized === false ) await this.init();
  35472. // preserve render tree
  35473. const nodeFrame = this._nodes.nodeFrame;
  35474. const previousRenderId = nodeFrame.renderId;
  35475. const previousRenderContext = this._currentRenderContext;
  35476. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35477. const previousCompilationPromises = this._compilationPromises;
  35478. //
  35479. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35480. if ( targetScene === null ) targetScene = scene;
  35481. const renderTarget = this._renderTarget;
  35482. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  35483. const activeMipmapLevel = this._activeMipmapLevel;
  35484. const compilationPromises = [];
  35485. this._currentRenderContext = renderContext;
  35486. this._currentRenderObjectFunction = this.renderObject;
  35487. this._handleObjectFunction = this._createObjectPipeline;
  35488. this._compilationPromises = compilationPromises;
  35489. nodeFrame.renderId ++;
  35490. //
  35491. nodeFrame.update();
  35492. //
  35493. renderContext.depth = this.depth;
  35494. renderContext.stencil = this.stencil;
  35495. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35496. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35497. //
  35498. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35499. //
  35500. const renderList = this._renderLists.get( scene, camera );
  35501. renderList.begin();
  35502. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35503. // include lights from target scene
  35504. if ( targetScene !== scene ) {
  35505. targetScene.traverseVisible( function ( object ) {
  35506. if ( object.isLight && object.layers.test( camera.layers ) ) {
  35507. renderList.pushLight( object );
  35508. }
  35509. } );
  35510. }
  35511. renderList.finish();
  35512. //
  35513. if ( renderTarget !== null ) {
  35514. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35515. const renderTargetData = this._textures.get( renderTarget );
  35516. renderContext.textures = renderTargetData.textures;
  35517. renderContext.depthTexture = renderTargetData.depthTexture;
  35518. } else {
  35519. renderContext.textures = null;
  35520. renderContext.depthTexture = null;
  35521. }
  35522. //
  35523. this._background.update( sceneRef, renderList, renderContext );
  35524. // process render lists
  35525. const opaqueObjects = renderList.opaque;
  35526. const transparentObjects = renderList.transparent;
  35527. const transparentDoublePassObjects = renderList.transparentDoublePass;
  35528. const lightsNode = renderList.lightsNode;
  35529. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35530. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35531. // restore render tree
  35532. nodeFrame.renderId = previousRenderId;
  35533. this._currentRenderContext = previousRenderContext;
  35534. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35535. this._compilationPromises = previousCompilationPromises;
  35536. this._handleObjectFunction = this._renderObjectDirect;
  35537. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  35538. await Promise.all( compilationPromises );
  35539. }
  35540. /**
  35541. * Renders the scene in an async fashion.
  35542. *
  35543. * @async
  35544. * @param {Object3D} scene - The scene or 3D object to render.
  35545. * @param {Camera} camera - The camera.
  35546. * @return {Promise} A Promise that resolves when the render has been finished.
  35547. */
  35548. async renderAsync( scene, camera ) {
  35549. if ( this._initialized === false ) await this.init();
  35550. this._renderScene( scene, camera );
  35551. }
  35552. /**
  35553. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  35554. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  35555. *
  35556. * @async
  35557. * @return {Promise} A Promise that resolves when synchronization has been finished.
  35558. */
  35559. async waitForGPU() {
  35560. await this.backend.waitForGPU();
  35561. }
  35562. /**
  35563. * Sets the given MRT configuration.
  35564. *
  35565. * @param {MRTNode} mrt - The MRT node to set.
  35566. * @return {Renderer} A reference to this renderer.
  35567. */
  35568. setMRT( mrt ) {
  35569. this._mrt = mrt;
  35570. return this;
  35571. }
  35572. /**
  35573. * Returns the MRT configuration.
  35574. *
  35575. * @return {MRTNode} The MRT configuration.
  35576. */
  35577. getMRT() {
  35578. return this._mrt;
  35579. }
  35580. /**
  35581. * Returns the color buffer type.
  35582. *
  35583. * @return {number} The color buffer type.
  35584. */
  35585. getColorBufferType() {
  35586. return this._colorBufferType;
  35587. }
  35588. /**
  35589. * Default implementation of the device lost callback.
  35590. *
  35591. * @private
  35592. * @param {Object} info - Information about the context lost.
  35593. */
  35594. _onDeviceLost( info ) {
  35595. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  35596. if ( info.reason ) {
  35597. errorMessage += `\nReason: ${info.reason}`;
  35598. }
  35599. console.error( errorMessage );
  35600. this._isDeviceLost = true;
  35601. }
  35602. /**
  35603. * Renders the given render bundle.
  35604. *
  35605. * @private
  35606. * @param {Object} bundle - Render bundle data.
  35607. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  35608. * @param {LightsNode} lightsNode - The current lights node.
  35609. */
  35610. _renderBundle( bundle, sceneRef, lightsNode ) {
  35611. const { bundleGroup, camera, renderList } = bundle;
  35612. const renderContext = this._currentRenderContext;
  35613. //
  35614. const renderBundle = this._bundles.get( bundleGroup, camera );
  35615. const renderBundleData = this.backend.get( renderBundle );
  35616. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  35617. //
  35618. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  35619. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  35620. renderBundleData.renderContexts.add( renderContext );
  35621. if ( renderBundleNeedsUpdate ) {
  35622. this.backend.beginBundle( renderContext );
  35623. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  35624. renderBundleData.renderObjects = [];
  35625. }
  35626. this._currentRenderBundle = renderBundle;
  35627. const opaqueObjects = renderList.opaque;
  35628. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35629. this._currentRenderBundle = null;
  35630. //
  35631. this.backend.finishBundle( renderContext, renderBundle );
  35632. renderBundleData.version = bundleGroup.version;
  35633. } else {
  35634. const { renderObjects } = renderBundleData;
  35635. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  35636. const renderObject = renderObjects[ i ];
  35637. if ( this._nodes.needsRefresh( renderObject ) ) {
  35638. this._nodes.updateBefore( renderObject );
  35639. this._nodes.updateForRender( renderObject );
  35640. this._bindings.updateForRender( renderObject );
  35641. this._nodes.updateAfter( renderObject );
  35642. }
  35643. }
  35644. }
  35645. this.backend.addBundle( renderContext, renderBundle );
  35646. }
  35647. /**
  35648. * Renders the scene or 3D object with the given camera. This method can only be called
  35649. * if the renderer has been initialized.
  35650. *
  35651. * The target of the method is the default framebuffer (meaning the canvas)
  35652. * or alternatively a render target when specified via `setRenderTarget()`.
  35653. *
  35654. * @param {Object3D} scene - The scene or 3D object to render.
  35655. * @param {Camera} camera - The camera to render the scene with.
  35656. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  35657. * Only returned when the renderer has not been initialized.
  35658. */
  35659. render( scene, camera ) {
  35660. if ( this._initialized === false ) {
  35661. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35662. return this.renderAsync( scene, camera );
  35663. }
  35664. this._renderScene( scene, camera );
  35665. }
  35666. /**
  35667. * Returns an internal render target which is used when computing the output tone mapping
  35668. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  35669. * pass and not inline to achieve more correct results.
  35670. *
  35671. * @private
  35672. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  35673. */
  35674. _getFrameBufferTarget() {
  35675. const { currentToneMapping, currentColorSpace } = this;
  35676. const useToneMapping = currentToneMapping !== NoToneMapping;
  35677. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  35678. if ( useToneMapping === false && useColorSpace === false ) return null;
  35679. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35680. const { depth, stencil } = this;
  35681. let frameBufferTarget = this._frameBufferTarget;
  35682. if ( frameBufferTarget === null ) {
  35683. frameBufferTarget = new RenderTarget( width, height, {
  35684. depthBuffer: depth,
  35685. stencilBuffer: stencil,
  35686. type: this._colorBufferType,
  35687. format: RGBAFormat,
  35688. colorSpace: LinearSRGBColorSpace,
  35689. generateMipmaps: false,
  35690. minFilter: LinearFilter,
  35691. magFilter: LinearFilter,
  35692. samples: this.samples
  35693. } );
  35694. frameBufferTarget.isPostProcessingRenderTarget = true;
  35695. this._frameBufferTarget = frameBufferTarget;
  35696. }
  35697. frameBufferTarget.depthBuffer = depth;
  35698. frameBufferTarget.stencilBuffer = stencil;
  35699. frameBufferTarget.setSize( width, height );
  35700. frameBufferTarget.viewport.copy( this._viewport );
  35701. frameBufferTarget.scissor.copy( this._scissor );
  35702. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35703. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35704. frameBufferTarget.scissorTest = this._scissorTest;
  35705. return frameBufferTarget;
  35706. }
  35707. /**
  35708. * Renders the scene or 3D object with the given camera.
  35709. *
  35710. * @private
  35711. * @param {Object3D} scene - The scene or 3D object to render.
  35712. * @param {Camera} camera - The camera to render the scene with.
  35713. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  35714. * @return {RenderContext} The current render context.
  35715. */
  35716. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35717. if ( this._isDeviceLost === true ) return;
  35718. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35719. // preserve render tree
  35720. const nodeFrame = this._nodes.nodeFrame;
  35721. const previousRenderId = nodeFrame.renderId;
  35722. const previousRenderContext = this._currentRenderContext;
  35723. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35724. //
  35725. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35726. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  35727. const activeCubeFace = this._activeCubeFace;
  35728. const activeMipmapLevel = this._activeMipmapLevel;
  35729. //
  35730. let renderTarget;
  35731. if ( frameBufferTarget !== null ) {
  35732. renderTarget = frameBufferTarget;
  35733. this.setRenderTarget( renderTarget );
  35734. } else {
  35735. renderTarget = outputRenderTarget;
  35736. }
  35737. //
  35738. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35739. this._currentRenderContext = renderContext;
  35740. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35741. //
  35742. this.info.calls ++;
  35743. this.info.render.calls ++;
  35744. this.info.render.frameCalls ++;
  35745. nodeFrame.renderId = this.info.calls;
  35746. //
  35747. const coordinateSystem = this.coordinateSystem;
  35748. const xr = this.xr;
  35749. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  35750. camera.coordinateSystem = coordinateSystem;
  35751. camera.updateProjectionMatrix();
  35752. if ( camera.isArrayCamera ) {
  35753. for ( const subCamera of camera.cameras ) {
  35754. subCamera.coordinateSystem = coordinateSystem;
  35755. subCamera.updateProjectionMatrix();
  35756. }
  35757. }
  35758. }
  35759. //
  35760. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35761. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35762. if ( xr.enabled === true && xr.isPresenting === true ) {
  35763. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  35764. camera = xr.getCamera(); // use XR camera for rendering
  35765. }
  35766. //
  35767. let viewport = this._viewport;
  35768. let scissor = this._scissor;
  35769. let pixelRatio = this._pixelRatio;
  35770. if ( renderTarget !== null ) {
  35771. viewport = renderTarget.viewport;
  35772. scissor = renderTarget.scissor;
  35773. pixelRatio = 1;
  35774. }
  35775. this.getDrawingBufferSize( _drawingBufferSize );
  35776. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35777. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35778. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35779. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35780. renderContext.viewportValue.width >>= activeMipmapLevel;
  35781. renderContext.viewportValue.height >>= activeMipmapLevel;
  35782. renderContext.viewportValue.minDepth = minDepth;
  35783. renderContext.viewportValue.maxDepth = maxDepth;
  35784. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35785. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35786. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35787. renderContext.scissorValue.width >>= activeMipmapLevel;
  35788. renderContext.scissorValue.height >>= activeMipmapLevel;
  35789. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35790. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35791. //
  35792. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35793. //
  35794. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35795. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35796. const renderList = this._renderLists.get( scene, camera );
  35797. renderList.begin();
  35798. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35799. renderList.finish();
  35800. if ( this.sortObjects === true ) {
  35801. renderList.sort( this._opaqueSort, this._transparentSort );
  35802. }
  35803. //
  35804. if ( renderTarget !== null ) {
  35805. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35806. const renderTargetData = this._textures.get( renderTarget );
  35807. renderContext.textures = renderTargetData.textures;
  35808. renderContext.depthTexture = renderTargetData.depthTexture;
  35809. renderContext.width = renderTargetData.width;
  35810. renderContext.height = renderTargetData.height;
  35811. renderContext.renderTarget = renderTarget;
  35812. renderContext.depth = renderTarget.depthBuffer;
  35813. renderContext.stencil = renderTarget.stencilBuffer;
  35814. } else {
  35815. renderContext.textures = null;
  35816. renderContext.depthTexture = null;
  35817. renderContext.width = this.domElement.width;
  35818. renderContext.height = this.domElement.height;
  35819. renderContext.depth = this.depth;
  35820. renderContext.stencil = this.stencil;
  35821. }
  35822. renderContext.width >>= activeMipmapLevel;
  35823. renderContext.height >>= activeMipmapLevel;
  35824. renderContext.activeCubeFace = activeCubeFace;
  35825. renderContext.activeMipmapLevel = activeMipmapLevel;
  35826. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35827. //
  35828. this._background.update( sceneRef, renderList, renderContext );
  35829. //
  35830. this.backend.beginRender( renderContext );
  35831. // process render lists
  35832. const {
  35833. bundles,
  35834. lightsNode,
  35835. transparentDoublePass: transparentDoublePassObjects,
  35836. transparent: transparentObjects,
  35837. opaque: opaqueObjects
  35838. } = renderList;
  35839. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35840. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35841. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35842. // finish render pass
  35843. this.backend.finishRender( renderContext );
  35844. // restore render tree
  35845. nodeFrame.renderId = previousRenderId;
  35846. this._currentRenderContext = previousRenderContext;
  35847. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35848. //
  35849. if ( frameBufferTarget !== null ) {
  35850. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  35851. this._renderOutput( renderTarget );
  35852. }
  35853. //
  35854. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  35855. //
  35856. return renderContext;
  35857. }
  35858. /**
  35859. * The output pass performs tone mapping and color space conversion.
  35860. *
  35861. * @private
  35862. * @param {RenderTarget} renderTarget - The current render target.
  35863. */
  35864. _renderOutput( renderTarget ) {
  35865. const quad = this._quad;
  35866. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35867. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35868. quad.material.needsUpdate = true;
  35869. }
  35870. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  35871. const currentAutoClear = this.autoClear;
  35872. this.autoClear = false;
  35873. this._renderScene( quad, quad.camera, false );
  35874. this.autoClear = currentAutoClear;
  35875. }
  35876. /**
  35877. * Returns the maximum available anisotropy for texture filtering.
  35878. *
  35879. * @return {number} The maximum available anisotropy.
  35880. */
  35881. getMaxAnisotropy() {
  35882. return this.backend.getMaxAnisotropy();
  35883. }
  35884. /**
  35885. * Returns the active cube face.
  35886. *
  35887. * @return {number} The active cube face.
  35888. */
  35889. getActiveCubeFace() {
  35890. return this._activeCubeFace;
  35891. }
  35892. /**
  35893. * Returns the active mipmap level.
  35894. *
  35895. * @return {number} The active mipmap level.
  35896. */
  35897. getActiveMipmapLevel() {
  35898. return this._activeMipmapLevel;
  35899. }
  35900. /**
  35901. * Applications are advised to always define the animation loop
  35902. * with this method and not manually with `requestAnimationFrame()`
  35903. * for best compatibility.
  35904. *
  35905. * @async
  35906. * @param {Function} callback - The application's animation loop.
  35907. * @return {Promise} A Promise that resolves when the set has been executed.
  35908. */
  35909. async setAnimationLoop( callback ) {
  35910. if ( this._initialized === false ) await this.init();
  35911. this._animation.setAnimationLoop( callback );
  35912. }
  35913. /**
  35914. * Can be used to transfer buffer data from a storage buffer attribute
  35915. * from the GPU to the CPU in context of compute shaders.
  35916. *
  35917. * @async
  35918. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  35919. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  35920. */
  35921. async getArrayBufferAsync( attribute ) {
  35922. return await this.backend.getArrayBufferAsync( attribute );
  35923. }
  35924. /**
  35925. * Returns the rendering context.
  35926. *
  35927. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  35928. */
  35929. getContext() {
  35930. return this.backend.getContext();
  35931. }
  35932. /**
  35933. * Returns the pixel ratio.
  35934. *
  35935. * @return {number} The pixel ratio.
  35936. */
  35937. getPixelRatio() {
  35938. return this._pixelRatio;
  35939. }
  35940. /**
  35941. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  35942. *
  35943. * @param {Vector2} target - The method writes the result in this target object.
  35944. * @return {Vector2} The drawing buffer size.
  35945. */
  35946. getDrawingBufferSize( target ) {
  35947. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  35948. }
  35949. /**
  35950. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  35951. *
  35952. * @param {Vector2} target - The method writes the result in this target object.
  35953. * @return {Vector2} The drawing buffer size.
  35954. */
  35955. getSize( target ) {
  35956. return target.set( this._width, this._height );
  35957. }
  35958. /**
  35959. * Sets the given pixel ration and resizes the canvas if necessary.
  35960. *
  35961. * @param {number} [value=1] - The pixel ratio.
  35962. */
  35963. setPixelRatio( value = 1 ) {
  35964. if ( this._pixelRatio === value ) return;
  35965. this._pixelRatio = value;
  35966. this.setSize( this._width, this._height, false );
  35967. }
  35968. /**
  35969. * This method allows to define the drawing buffer size by specifying
  35970. * width, height and pixel ratio all at once. The size of the drawing
  35971. * buffer is computed with this formula:
  35972. * ````
  35973. * size.x = width * pixelRatio;
  35974. * size.y = height * pixelRatio;
  35975. *```
  35976. *
  35977. * @param {number} width - The width in logical pixels.
  35978. * @param {number} height - The height in logical pixels.
  35979. * @param {number} pixelRatio - The pixel ratio.
  35980. */
  35981. setDrawingBufferSize( width, height, pixelRatio ) {
  35982. this._width = width;
  35983. this._height = height;
  35984. this._pixelRatio = pixelRatio;
  35985. this.domElement.width = Math.floor( width * pixelRatio );
  35986. this.domElement.height = Math.floor( height * pixelRatio );
  35987. this.setViewport( 0, 0, width, height );
  35988. if ( this._initialized ) this.backend.updateSize();
  35989. }
  35990. /**
  35991. * Sets the size of the renderer.
  35992. *
  35993. * @param {number} width - The width in logical pixels.
  35994. * @param {number} height - The height in logical pixels.
  35995. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  35996. */
  35997. setSize( width, height, updateStyle = true ) {
  35998. this._width = width;
  35999. this._height = height;
  36000. this.domElement.width = Math.floor( width * this._pixelRatio );
  36001. this.domElement.height = Math.floor( height * this._pixelRatio );
  36002. if ( updateStyle === true ) {
  36003. this.domElement.style.width = width + 'px';
  36004. this.domElement.style.height = height + 'px';
  36005. }
  36006. this.setViewport( 0, 0, width, height );
  36007. if ( this._initialized ) this.backend.updateSize();
  36008. }
  36009. /**
  36010. * Defines a manual sort function for the opaque render list.
  36011. * Pass `null` to use the default sort.
  36012. *
  36013. * @param {Function} method - The sort function.
  36014. */
  36015. setOpaqueSort( method ) {
  36016. this._opaqueSort = method;
  36017. }
  36018. /**
  36019. * Defines a manual sort function for the transparent render list.
  36020. * Pass `null` to use the default sort.
  36021. *
  36022. * @param {Function} method - The sort function.
  36023. */
  36024. setTransparentSort( method ) {
  36025. this._transparentSort = method;
  36026. }
  36027. /**
  36028. * Returns the scissor rectangle.
  36029. *
  36030. * @param {Vector4} target - The method writes the result in this target object.
  36031. * @return {Vector4} The scissor rectangle.
  36032. */
  36033. getScissor( target ) {
  36034. const scissor = this._scissor;
  36035. target.x = scissor.x;
  36036. target.y = scissor.y;
  36037. target.width = scissor.width;
  36038. target.height = scissor.height;
  36039. return target;
  36040. }
  36041. /**
  36042. * Defines the scissor rectangle.
  36043. *
  36044. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  36045. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  36046. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  36047. * @param {number} width - The width of the scissor box in logical pixel unit.
  36048. * @param {number} height - The height of the scissor box in logical pixel unit.
  36049. */
  36050. setScissor( x, y, width, height ) {
  36051. const scissor = this._scissor;
  36052. if ( x.isVector4 ) {
  36053. scissor.copy( x );
  36054. } else {
  36055. scissor.set( x, y, width, height );
  36056. }
  36057. }
  36058. /**
  36059. * Returns the scissor test value.
  36060. *
  36061. * @return {boolean} Whether the scissor test should be enabled or not.
  36062. */
  36063. getScissorTest() {
  36064. return this._scissorTest;
  36065. }
  36066. /**
  36067. * Defines the scissor test.
  36068. *
  36069. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  36070. */
  36071. setScissorTest( boolean ) {
  36072. this._scissorTest = boolean;
  36073. this.backend.setScissorTest( boolean );
  36074. }
  36075. /**
  36076. * Returns the viewport definition.
  36077. *
  36078. * @param {Vector4} target - The method writes the result in this target object.
  36079. * @return {Vector4} The viewport definition.
  36080. */
  36081. getViewport( target ) {
  36082. return target.copy( this._viewport );
  36083. }
  36084. /**
  36085. * Defines the viewport.
  36086. *
  36087. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36088. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36089. * @param {number} width - The width of the viewport in logical pixel unit.
  36090. * @param {number} height - The height of the viewport in logical pixel unit.
  36091. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  36092. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  36093. */
  36094. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36095. const viewport = this._viewport;
  36096. if ( x.isVector4 ) {
  36097. viewport.copy( x );
  36098. } else {
  36099. viewport.set( x, y, width, height );
  36100. }
  36101. viewport.minDepth = minDepth;
  36102. viewport.maxDepth = maxDepth;
  36103. }
  36104. /**
  36105. * Returns the clear color.
  36106. *
  36107. * @param {Color} target - The method writes the result in this target object.
  36108. * @return {Color} The clear color.
  36109. */
  36110. getClearColor( target ) {
  36111. return target.copy( this._clearColor );
  36112. }
  36113. /**
  36114. * Defines the clear color and optionally the clear alpha.
  36115. *
  36116. * @param {Color} color - The clear color.
  36117. * @param {number} [alpha=1] - The clear alpha.
  36118. */
  36119. setClearColor( color, alpha = 1 ) {
  36120. this._clearColor.set( color );
  36121. this._clearColor.a = alpha;
  36122. }
  36123. /**
  36124. * Returns the clear alpha.
  36125. *
  36126. * @return {number} The clear alpha.
  36127. */
  36128. getClearAlpha() {
  36129. return this._clearColor.a;
  36130. }
  36131. /**
  36132. * Defines the clear alpha.
  36133. *
  36134. * @param {number} alpha - The clear alpha.
  36135. */
  36136. setClearAlpha( alpha ) {
  36137. this._clearColor.a = alpha;
  36138. }
  36139. /**
  36140. * Returns the clear depth.
  36141. *
  36142. * @return {number} The clear depth.
  36143. */
  36144. getClearDepth() {
  36145. return this._clearDepth;
  36146. }
  36147. /**
  36148. * Defines the clear depth.
  36149. *
  36150. * @param {number} depth - The clear depth.
  36151. */
  36152. setClearDepth( depth ) {
  36153. this._clearDepth = depth;
  36154. }
  36155. /**
  36156. * Returns the clear stencil.
  36157. *
  36158. * @return {number} The clear stencil.
  36159. */
  36160. getClearStencil() {
  36161. return this._clearStencil;
  36162. }
  36163. /**
  36164. * Defines the clear stencil.
  36165. *
  36166. * @param {number} stencil - The clear stencil.
  36167. */
  36168. setClearStencil( stencil ) {
  36169. this._clearStencil = stencil;
  36170. }
  36171. /**
  36172. * This method performs an occlusion query for the given 3D object.
  36173. * It returns `true` if the given 3D object is fully occluded by other
  36174. * 3D objects in the scene.
  36175. *
  36176. * @param {Object3D} object - The 3D object to test.
  36177. * @return {boolean} Whether the 3D object is fully occluded or not.
  36178. */
  36179. isOccluded( object ) {
  36180. const renderContext = this._currentRenderContext;
  36181. return renderContext && this.backend.isOccluded( renderContext, object );
  36182. }
  36183. /**
  36184. * Performs a manual clear operation. This method ignores `autoClear` properties.
  36185. *
  36186. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36187. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36188. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36189. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36190. * Only returned when the renderer has not been initialized.
  36191. */
  36192. clear( color = true, depth = true, stencil = true ) {
  36193. if ( this._initialized === false ) {
  36194. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36195. return this.clearAsync( color, depth, stencil );
  36196. }
  36197. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36198. let renderContext = null;
  36199. if ( renderTarget !== null ) {
  36200. this._textures.updateRenderTarget( renderTarget );
  36201. const renderTargetData = this._textures.get( renderTarget );
  36202. renderContext = this._renderContexts.getForClear( renderTarget );
  36203. renderContext.textures = renderTargetData.textures;
  36204. renderContext.depthTexture = renderTargetData.depthTexture;
  36205. renderContext.width = renderTargetData.width;
  36206. renderContext.height = renderTargetData.height;
  36207. renderContext.renderTarget = renderTarget;
  36208. renderContext.depth = renderTarget.depthBuffer;
  36209. renderContext.stencil = renderTarget.stencilBuffer;
  36210. // #30329
  36211. renderContext.clearColorValue = this.backend.getClearColor();
  36212. }
  36213. this.backend.clear( color, depth, stencil, renderContext );
  36214. if ( renderTarget !== null && this._renderTarget === null ) {
  36215. this._renderOutput( renderTarget );
  36216. }
  36217. }
  36218. /**
  36219. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  36220. *
  36221. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36222. * Only returned when the renderer has not been initialized.
  36223. */
  36224. clearColor() {
  36225. return this.clear( true, false, false );
  36226. }
  36227. /**
  36228. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  36229. *
  36230. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36231. * Only returned when the renderer has not been initialized.
  36232. */
  36233. clearDepth() {
  36234. return this.clear( false, true, false );
  36235. }
  36236. /**
  36237. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  36238. *
  36239. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36240. * Only returned when the renderer has not been initialized.
  36241. */
  36242. clearStencil() {
  36243. return this.clear( false, false, true );
  36244. }
  36245. /**
  36246. * Async version of {@link Renderer#clear}.
  36247. *
  36248. * @async
  36249. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36250. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36251. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36252. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36253. */
  36254. async clearAsync( color = true, depth = true, stencil = true ) {
  36255. if ( this._initialized === false ) await this.init();
  36256. this.clear( color, depth, stencil );
  36257. }
  36258. /**
  36259. * Async version of {@link Renderer#clearColor}.
  36260. *
  36261. * @async
  36262. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36263. */
  36264. async clearColorAsync() {
  36265. this.clearAsync( true, false, false );
  36266. }
  36267. /**
  36268. * Async version of {@link Renderer#clearDepth}.
  36269. *
  36270. * @async
  36271. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36272. */
  36273. async clearDepthAsync() {
  36274. this.clearAsync( false, true, false );
  36275. }
  36276. /**
  36277. * Async version of {@link Renderer#clearStencil}.
  36278. *
  36279. * @async
  36280. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36281. */
  36282. async clearStencilAsync() {
  36283. this.clearAsync( false, false, true );
  36284. }
  36285. /**
  36286. * The current output tone mapping of the renderer. When a render target is set,
  36287. * the output tone mapping is always `NoToneMapping`.
  36288. *
  36289. * @type {number}
  36290. */
  36291. get currentToneMapping() {
  36292. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  36293. }
  36294. /**
  36295. * The current output color space of the renderer. When a render target is set,
  36296. * the output color space is always `LinearSRGBColorSpace`.
  36297. *
  36298. * @type {string}
  36299. */
  36300. get currentColorSpace() {
  36301. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  36302. }
  36303. /**
  36304. * Returns `true` if the rendering settings are set to screen output.
  36305. *
  36306. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  36307. */
  36308. get isOutputTarget() {
  36309. return this._renderTarget === this._outputRenderTarget;
  36310. }
  36311. /**
  36312. * Frees all internal resources of the renderer. Call this method if the renderer
  36313. * is no longer in use by your app.
  36314. */
  36315. dispose() {
  36316. this.info.dispose();
  36317. this.backend.dispose();
  36318. this._animation.dispose();
  36319. this._objects.dispose();
  36320. this._pipelines.dispose();
  36321. this._nodes.dispose();
  36322. this._bindings.dispose();
  36323. this._renderLists.dispose();
  36324. this._renderContexts.dispose();
  36325. this._textures.dispose();
  36326. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  36327. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  36328. if ( queryPool !== null ) queryPool.dispose();
  36329. } );
  36330. this.setRenderTarget( null );
  36331. this.setAnimationLoop( null );
  36332. }
  36333. /**
  36334. * Sets the given render target. Calling this method means the renderer does not
  36335. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  36336. * Use `null` as the first argument to reset the state.
  36337. *
  36338. * @param {?RenderTarget} renderTarget - The render target to set.
  36339. * @param {number} [activeCubeFace=0] - The active cube face.
  36340. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  36341. */
  36342. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36343. this._renderTarget = renderTarget;
  36344. this._activeCubeFace = activeCubeFace;
  36345. this._activeMipmapLevel = activeMipmapLevel;
  36346. }
  36347. /**
  36348. * Returns the current render target.
  36349. *
  36350. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  36351. */
  36352. getRenderTarget() {
  36353. return this._renderTarget;
  36354. }
  36355. /**
  36356. * Sets the output render target for the renderer.
  36357. *
  36358. * @param {Object} renderTarget - The render target to set as the output target.
  36359. */
  36360. setOutputRenderTarget( renderTarget ) {
  36361. this._outputRenderTarget = renderTarget;
  36362. }
  36363. /**
  36364. * Returns the current output target.
  36365. *
  36366. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  36367. */
  36368. getOutputRenderTarget() {
  36369. return this._outputRenderTarget;
  36370. }
  36371. /**
  36372. * Callback for {@link Renderer#setRenderObjectFunction}.
  36373. *
  36374. * @callback renderObjectFunction
  36375. * @param {Object3D} object - The 3D object.
  36376. * @param {Scene} scene - The scene the 3D object belongs to.
  36377. * @param {Camera} camera - The camera the object should be rendered with.
  36378. * @param {BufferGeometry} geometry - The object's geometry.
  36379. * @param {Material} material - The object's material.
  36380. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36381. * @param {LightsNode} lightsNode - The current lights node.
  36382. * @param {ClippingContext} clippingContext - The clipping context.
  36383. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36384. */
  36385. /**
  36386. * Sets the given render object function. Calling this method overwrites the default implementation
  36387. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  36388. * if you want to modify the way objects are rendered. For example you can define things like "every
  36389. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  36390. * The custom function must always call `renderObject()` in its implementation.
  36391. *
  36392. * Use `null` as the first argument to reset the state.
  36393. *
  36394. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  36395. */
  36396. setRenderObjectFunction( renderObjectFunction ) {
  36397. this._renderObjectFunction = renderObjectFunction;
  36398. }
  36399. /**
  36400. * Returns the current render object function.
  36401. *
  36402. * @return {?Function} The current render object function. Returns `null` if no function is set.
  36403. */
  36404. getRenderObjectFunction() {
  36405. return this._renderObjectFunction;
  36406. }
  36407. /**
  36408. * Execute a single or an array of compute nodes. This method can only be called
  36409. * if the renderer has been initialized.
  36410. *
  36411. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36412. * @return {?Promise} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  36413. */
  36414. compute( computeNodes ) {
  36415. if ( this._isDeviceLost === true ) return;
  36416. if ( this._initialized === false ) {
  36417. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  36418. return this.computeAsync( computeNodes );
  36419. }
  36420. //
  36421. const nodeFrame = this._nodes.nodeFrame;
  36422. const previousRenderId = nodeFrame.renderId;
  36423. //
  36424. this.info.calls ++;
  36425. this.info.compute.calls ++;
  36426. this.info.compute.frameCalls ++;
  36427. nodeFrame.renderId = this.info.calls;
  36428. //
  36429. const backend = this.backend;
  36430. const pipelines = this._pipelines;
  36431. const bindings = this._bindings;
  36432. const nodes = this._nodes;
  36433. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36434. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36435. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36436. }
  36437. backend.beginCompute( computeNodes );
  36438. for ( const computeNode of computeList ) {
  36439. // onInit
  36440. if ( pipelines.has( computeNode ) === false ) {
  36441. const dispose = () => {
  36442. computeNode.removeEventListener( 'dispose', dispose );
  36443. pipelines.delete( computeNode );
  36444. bindings.delete( computeNode );
  36445. nodes.delete( computeNode );
  36446. };
  36447. computeNode.addEventListener( 'dispose', dispose );
  36448. //
  36449. const onInitFn = computeNode.onInitFunction;
  36450. if ( onInitFn !== null ) {
  36451. onInitFn.call( computeNode, { renderer: this } );
  36452. }
  36453. }
  36454. nodes.updateForCompute( computeNode );
  36455. bindings.updateForCompute( computeNode );
  36456. const computeBindings = bindings.getForCompute( computeNode );
  36457. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36458. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36459. }
  36460. backend.finishCompute( computeNodes );
  36461. //
  36462. nodeFrame.renderId = previousRenderId;
  36463. }
  36464. /**
  36465. * Execute a single or an array of compute nodes.
  36466. *
  36467. * @async
  36468. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36469. * @return {Promise} A Promise that resolve when the compute has finished.
  36470. */
  36471. async computeAsync( computeNodes ) {
  36472. if ( this._initialized === false ) await this.init();
  36473. this.compute( computeNodes );
  36474. }
  36475. /**
  36476. * Checks if the given feature is supported by the selected backend.
  36477. *
  36478. * @async
  36479. * @param {string} name - The feature's name.
  36480. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  36481. */
  36482. async hasFeatureAsync( name ) {
  36483. if ( this._initialized === false ) await this.init();
  36484. return this.backend.hasFeature( name );
  36485. }
  36486. async resolveTimestampsAsync( type = 'render' ) {
  36487. if ( this._initialized === false ) await this.init();
  36488. return this.backend.resolveTimestampsAsync( type );
  36489. }
  36490. /**
  36491. * Checks if the given feature is supported by the selected backend. If the
  36492. * renderer has not been initialized, this method always returns `false`.
  36493. *
  36494. * @param {string} name - The feature's name.
  36495. * @return {boolean} Whether the feature is supported or not.
  36496. */
  36497. hasFeature( name ) {
  36498. if ( this._initialized === false ) {
  36499. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36500. return false;
  36501. }
  36502. return this.backend.hasFeature( name );
  36503. }
  36504. /**
  36505. * Returns `true` when the renderer has been initialized.
  36506. *
  36507. * @return {boolean} Whether the renderer has been initialized or not.
  36508. */
  36509. hasInitialized() {
  36510. return this._initialized;
  36511. }
  36512. /**
  36513. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  36514. * (which can cause noticeable lags due to decode and GPU upload overhead).
  36515. *
  36516. * @async
  36517. * @param {Texture} texture - The texture.
  36518. * @return {Promise} A Promise that resolves when the texture has been initialized.
  36519. */
  36520. async initTextureAsync( texture ) {
  36521. if ( this._initialized === false ) await this.init();
  36522. this._textures.updateTexture( texture );
  36523. }
  36524. /**
  36525. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  36526. * (which can cause noticeable lags due to decode and GPU upload overhead).
  36527. *
  36528. * This method can only be used if the renderer has been initialized.
  36529. *
  36530. * @param {Texture} texture - The texture.
  36531. */
  36532. initTexture( texture ) {
  36533. if ( this._initialized === false ) {
  36534. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  36535. }
  36536. this._textures.updateTexture( texture );
  36537. }
  36538. /**
  36539. * Copies the current bound framebuffer into the given texture.
  36540. *
  36541. * @param {FramebufferTexture} framebufferTexture - The texture.
  36542. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  36543. */
  36544. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  36545. if ( rectangle !== null ) {
  36546. if ( rectangle.isVector2 ) {
  36547. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  36548. } else if ( rectangle.isVector4 ) {
  36549. rectangle = _vector4.copy( rectangle ).floor();
  36550. } else {
  36551. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  36552. return;
  36553. }
  36554. } else {
  36555. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  36556. }
  36557. //
  36558. let renderContext = this._currentRenderContext;
  36559. let renderTarget;
  36560. if ( renderContext !== null ) {
  36561. renderTarget = renderContext.renderTarget;
  36562. } else {
  36563. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36564. if ( renderTarget !== null ) {
  36565. this._textures.updateRenderTarget( renderTarget );
  36566. renderContext = this._textures.get( renderTarget );
  36567. }
  36568. }
  36569. //
  36570. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  36571. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  36572. }
  36573. /**
  36574. * Copies data of source texture into a destination texture.
  36575. *
  36576. * @param {Texture} srcTexture - The source texture.
  36577. * @param {Texture} dstTexture - The destination texture.
  36578. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  36579. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  36580. * @param {number} level - The mipmap level to copy.
  36581. */
  36582. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36583. this._textures.updateTexture( srcTexture );
  36584. this._textures.updateTexture( dstTexture );
  36585. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36586. }
  36587. /**
  36588. * Reads pixel data from the given render target.
  36589. *
  36590. * @async
  36591. * @param {RenderTarget} renderTarget - The render target to read from.
  36592. * @param {number} x - The `x` coordinate of the copy region's origin.
  36593. * @param {number} y - The `y` coordinate of the copy region's origin.
  36594. * @param {number} width - The width of the copy region.
  36595. * @param {number} height - The height of the copy region.
  36596. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  36597. * @param {number} [faceIndex=0] - The active cube face index.
  36598. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  36599. */
  36600. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  36601. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  36602. }
  36603. /**
  36604. * Analyzes the given 3D object's hierarchy and builds render lists from the
  36605. * processed hierarchy.
  36606. *
  36607. * @param {Object3D} object - The 3D object to process (usually a scene).
  36608. * @param {Camera} camera - The camera the object is rendered with.
  36609. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  36610. * @param {RenderList} renderList - The current render list.
  36611. * @param {ClippingContext} clippingContext - The current clipping context.
  36612. */
  36613. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  36614. if ( object.visible === false ) return;
  36615. const visible = object.layers.test( camera.layers );
  36616. if ( visible ) {
  36617. if ( object.isGroup ) {
  36618. groupOrder = object.renderOrder;
  36619. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  36620. } else if ( object.isLOD ) {
  36621. if ( object.autoUpdate === true ) object.update( camera );
  36622. } else if ( object.isLight ) {
  36623. renderList.pushLight( object );
  36624. } else if ( object.isSprite ) {
  36625. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36626. if ( this.sortObjects === true ) {
  36627. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36628. }
  36629. const { geometry, material } = object;
  36630. if ( material.visible ) {
  36631. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  36632. }
  36633. }
  36634. } else if ( object.isLineLoop ) {
  36635. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36636. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36637. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36638. const { geometry, material } = object;
  36639. if ( this.sortObjects === true ) {
  36640. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36641. _vector4
  36642. .copy( geometry.boundingSphere.center )
  36643. .applyMatrix4( object.matrixWorld )
  36644. .applyMatrix4( _projScreenMatrix );
  36645. }
  36646. if ( Array.isArray( material ) ) {
  36647. const groups = geometry.groups;
  36648. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36649. const group = groups[ i ];
  36650. const groupMaterial = material[ group.materialIndex ];
  36651. if ( groupMaterial && groupMaterial.visible ) {
  36652. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  36653. }
  36654. }
  36655. } else if ( material.visible ) {
  36656. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  36657. }
  36658. }
  36659. }
  36660. }
  36661. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  36662. const baseRenderList = renderList;
  36663. // replace render list
  36664. renderList = this._renderLists.get( object, camera );
  36665. renderList.begin();
  36666. baseRenderList.pushBundle( {
  36667. bundleGroup: object,
  36668. camera,
  36669. renderList,
  36670. } );
  36671. renderList.finish();
  36672. }
  36673. const children = object.children;
  36674. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36675. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  36676. }
  36677. }
  36678. /**
  36679. * Renders the given render bundles.
  36680. *
  36681. * @private
  36682. * @param {Array<Object>} bundles - Array with render bundle data.
  36683. * @param {Scene} sceneRef - The scene the render bundles belong to.
  36684. * @param {LightsNode} lightsNode - The current lights node.
  36685. */
  36686. _renderBundles( bundles, sceneRef, lightsNode ) {
  36687. for ( const bundle of bundles ) {
  36688. this._renderBundle( bundle, sceneRef, lightsNode );
  36689. }
  36690. }
  36691. /**
  36692. * Renders the transparent objects from the given render lists.
  36693. *
  36694. * @private
  36695. * @param {Array<Object>} renderList - The transparent render list.
  36696. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  36697. * @param {Camera} camera - The camera the render list should be rendered with.
  36698. * @param {Scene} scene - The scene the render list belongs to.
  36699. * @param {LightsNode} lightsNode - The current lights node.
  36700. */
  36701. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  36702. if ( doublePassList.length > 0 ) {
  36703. // render back side
  36704. for ( const { material } of doublePassList ) {
  36705. material.side = BackSide;
  36706. }
  36707. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  36708. // render front side
  36709. for ( const { material } of doublePassList ) {
  36710. material.side = FrontSide;
  36711. }
  36712. this._renderObjects( renderList, camera, scene, lightsNode );
  36713. // restore
  36714. for ( const { material } of doublePassList ) {
  36715. material.side = DoubleSide;
  36716. }
  36717. } else {
  36718. this._renderObjects( renderList, camera, scene, lightsNode );
  36719. }
  36720. }
  36721. /**
  36722. * Renders the objects from the given render list.
  36723. *
  36724. * @private
  36725. * @param {Array<Object>} renderList - The render list.
  36726. * @param {Camera} camera - The camera the render list should be rendered with.
  36727. * @param {Scene} scene - The scene the render list belongs to.
  36728. * @param {LightsNode} lightsNode - The current lights node.
  36729. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36730. */
  36731. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  36732. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36733. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  36734. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  36735. }
  36736. }
  36737. /**
  36738. * This method represents the default render object function that manages the render lifecycle
  36739. * of the object.
  36740. *
  36741. * @param {Object3D} object - The 3D object.
  36742. * @param {Scene} scene - The scene the 3D object belongs to.
  36743. * @param {Camera} camera - The camera the object should be rendered with.
  36744. * @param {BufferGeometry} geometry - The object's geometry.
  36745. * @param {Material} material - The object's material.
  36746. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36747. * @param {LightsNode} lightsNode - The current lights node.
  36748. * @param {ClippingContext} clippingContext - The clipping context.
  36749. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36750. */
  36751. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  36752. let overridePositionNode;
  36753. let overrideColorNode;
  36754. let overrideDepthNode;
  36755. //
  36756. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36757. //
  36758. if ( scene.overrideMaterial !== null ) {
  36759. const overrideMaterial = scene.overrideMaterial;
  36760. if ( material.positionNode && material.positionNode.isNode ) {
  36761. overridePositionNode = overrideMaterial.positionNode;
  36762. overrideMaterial.positionNode = material.positionNode;
  36763. }
  36764. overrideMaterial.alphaTest = material.alphaTest;
  36765. overrideMaterial.alphaMap = material.alphaMap;
  36766. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  36767. if ( overrideMaterial.isShadowPassMaterial ) {
  36768. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36769. if ( material.depthNode && material.depthNode.isNode ) {
  36770. overrideDepthNode = overrideMaterial.depthNode;
  36771. overrideMaterial.depthNode = material.depthNode;
  36772. }
  36773. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  36774. overrideColorNode = overrideMaterial.colorNode;
  36775. overrideMaterial.colorNode = material.castShadowNode;
  36776. }
  36777. }
  36778. material = overrideMaterial;
  36779. }
  36780. //
  36781. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36782. material.side = BackSide;
  36783. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  36784. material.side = FrontSide;
  36785. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  36786. material.side = DoubleSide;
  36787. } else {
  36788. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  36789. }
  36790. //
  36791. if ( overridePositionNode !== undefined ) {
  36792. scene.overrideMaterial.positionNode = overridePositionNode;
  36793. }
  36794. if ( overrideDepthNode !== undefined ) {
  36795. scene.overrideMaterial.depthNode = overrideDepthNode;
  36796. }
  36797. if ( overrideColorNode !== undefined ) {
  36798. scene.overrideMaterial.colorNode = overrideColorNode;
  36799. }
  36800. //
  36801. object.onAfterRender( this, scene, camera, geometry, material, group );
  36802. }
  36803. /**
  36804. * This method represents the default `_handleObjectFunction` implementation which creates
  36805. * a render object from the given data and performs the draw command with the selected backend.
  36806. *
  36807. * @private
  36808. * @param {Object3D} object - The 3D object.
  36809. * @param {Material} material - The object's material.
  36810. * @param {Scene} scene - The scene the 3D object belongs to.
  36811. * @param {Camera} camera - The camera the object should be rendered with.
  36812. * @param {LightsNode} lightsNode - The current lights node.
  36813. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36814. * @param {ClippingContext} clippingContext - The clipping context.
  36815. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36816. */
  36817. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36818. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36819. renderObject.drawRange = object.geometry.drawRange;
  36820. renderObject.group = group;
  36821. //
  36822. const needsRefresh = this._nodes.needsRefresh( renderObject );
  36823. if ( needsRefresh ) {
  36824. this._nodes.updateBefore( renderObject );
  36825. this._geometries.updateForRender( renderObject );
  36826. this._nodes.updateForRender( renderObject );
  36827. this._bindings.updateForRender( renderObject );
  36828. }
  36829. this._pipelines.updateForRender( renderObject );
  36830. //
  36831. if ( this._currentRenderBundle !== null ) {
  36832. const renderBundleData = this.backend.get( this._currentRenderBundle );
  36833. renderBundleData.renderObjects.push( renderObject );
  36834. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  36835. }
  36836. this.backend.draw( renderObject, this.info );
  36837. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  36838. }
  36839. /**
  36840. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  36841. * Used in `compileAsync()`.
  36842. *
  36843. * @private
  36844. * @param {Object3D} object - The 3D object.
  36845. * @param {Material} material - The object's material.
  36846. * @param {Scene} scene - The scene the 3D object belongs to.
  36847. * @param {Camera} camera - The camera the object should be rendered with.
  36848. * @param {LightsNode} lightsNode - The current lights node.
  36849. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36850. * @param {ClippingContext} clippingContext - The clipping context.
  36851. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36852. */
  36853. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36854. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36855. renderObject.drawRange = object.geometry.drawRange;
  36856. renderObject.group = group;
  36857. //
  36858. this._nodes.updateBefore( renderObject );
  36859. this._geometries.updateForRender( renderObject );
  36860. this._nodes.updateForRender( renderObject );
  36861. this._bindings.updateForRender( renderObject );
  36862. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36863. this._nodes.updateAfter( renderObject );
  36864. }
  36865. /**
  36866. * Alias for `compileAsync()`.
  36867. *
  36868. * @method
  36869. * @param {Object3D} scene - The scene or 3D object to precompile.
  36870. * @param {Camera} camera - The camera that is used to render the scene.
  36871. * @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.
  36872. * @return {Promise} A Promise that resolves when the compile has been finished.
  36873. */
  36874. get compile() {
  36875. return this.compileAsync;
  36876. }
  36877. }
  36878. /**
  36879. * A binding represents the connection between a resource (like a texture, sampler
  36880. * or uniform buffer) and the resource definition in a shader stage.
  36881. *
  36882. * This module is an abstract base class for all concrete bindings types.
  36883. *
  36884. * @abstract
  36885. * @private
  36886. */
  36887. class Binding {
  36888. /**
  36889. * Constructs a new binding.
  36890. *
  36891. * @param {string} [name=''] - The binding's name.
  36892. */
  36893. constructor( name = '' ) {
  36894. /**
  36895. * The binding's name.
  36896. *
  36897. * @type {string}
  36898. */
  36899. this.name = name;
  36900. /**
  36901. * A bitmask that defines in what shader stages the
  36902. * binding's resource is accessible.
  36903. *
  36904. * @type {number}
  36905. */
  36906. this.visibility = 0;
  36907. }
  36908. /**
  36909. * Makes sure binding's resource is visible for the given shader stage.
  36910. *
  36911. * @param {number} visibility - The shader stage.
  36912. */
  36913. setVisibility( visibility ) {
  36914. this.visibility |= visibility;
  36915. }
  36916. /**
  36917. * Clones the binding.
  36918. *
  36919. * @return {Binding} The cloned binding.
  36920. */
  36921. clone() {
  36922. return Object.assign( new this.constructor(), this );
  36923. }
  36924. }
  36925. /**
  36926. * This function is usually called with the length in bytes of an array buffer.
  36927. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  36928. *
  36929. * @function
  36930. * @param {number} floatLength - The buffer length.
  36931. * @return {number} The padded length.
  36932. */
  36933. function getFloatLength( floatLength ) {
  36934. // ensure chunk size alignment (STD140 layout)
  36935. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36936. }
  36937. /**
  36938. * Represents a buffer binding type.
  36939. *
  36940. * @private
  36941. * @abstract
  36942. * @augments Binding
  36943. */
  36944. class Buffer extends Binding {
  36945. /**
  36946. * Constructs a new buffer.
  36947. *
  36948. * @param {string} name - The buffer's name.
  36949. * @param {TypedArray} [buffer=null] - The buffer.
  36950. */
  36951. constructor( name, buffer = null ) {
  36952. super( name );
  36953. /**
  36954. * This flag can be used for type testing.
  36955. *
  36956. * @type {boolean}
  36957. * @readonly
  36958. * @default true
  36959. */
  36960. this.isBuffer = true;
  36961. /**
  36962. * The bytes per element.
  36963. *
  36964. * @type {number}
  36965. */
  36966. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36967. /**
  36968. * A reference to the internal buffer.
  36969. *
  36970. * @private
  36971. * @type {TypedArray}
  36972. */
  36973. this._buffer = buffer;
  36974. }
  36975. /**
  36976. * The buffer's byte length.
  36977. *
  36978. * @type {number}
  36979. * @readonly
  36980. */
  36981. get byteLength() {
  36982. return getFloatLength( this._buffer.byteLength );
  36983. }
  36984. /**
  36985. * A reference to the internal buffer.
  36986. *
  36987. * @type {Float32Array}
  36988. * @readonly
  36989. */
  36990. get buffer() {
  36991. return this._buffer;
  36992. }
  36993. /**
  36994. * Updates the binding.
  36995. *
  36996. * @return {boolean} Whether the buffer has been updated and must be
  36997. * uploaded to the GPU.
  36998. */
  36999. update() {
  37000. return true;
  37001. }
  37002. }
  37003. /**
  37004. * Represents a uniform buffer binding type.
  37005. *
  37006. * @private
  37007. * @augments Buffer
  37008. */
  37009. class UniformBuffer extends Buffer {
  37010. /**
  37011. * Constructs a new uniform buffer.
  37012. *
  37013. * @param {string} name - The buffer's name.
  37014. * @param {TypedArray} [buffer=null] - The buffer.
  37015. */
  37016. constructor( name, buffer = null ) {
  37017. super( name, buffer );
  37018. /**
  37019. * This flag can be used for type testing.
  37020. *
  37021. * @type {boolean}
  37022. * @readonly
  37023. * @default true
  37024. */
  37025. this.isUniformBuffer = true;
  37026. }
  37027. }
  37028. let _id$4 = 0;
  37029. /**
  37030. * A special form of uniform buffer binding type.
  37031. * It's buffer value is managed by a node object.
  37032. *
  37033. * @private
  37034. * @augments UniformBuffer
  37035. */
  37036. class NodeUniformBuffer extends UniformBuffer {
  37037. /**
  37038. * Constructs a new node-based uniform buffer.
  37039. *
  37040. * @param {BufferNode} nodeUniform - The uniform buffer node.
  37041. * @param {UniformGroupNode} groupNode - The uniform group node.
  37042. */
  37043. constructor( nodeUniform, groupNode ) {
  37044. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  37045. /**
  37046. * The uniform buffer node.
  37047. *
  37048. * @type {BufferNode}
  37049. */
  37050. this.nodeUniform = nodeUniform;
  37051. /**
  37052. * The uniform group node.
  37053. *
  37054. * @type {UniformGroupNode}
  37055. */
  37056. this.groupNode = groupNode;
  37057. }
  37058. /**
  37059. * The uniform buffer.
  37060. *
  37061. * @type {Float32Array}
  37062. */
  37063. get buffer() {
  37064. return this.nodeUniform.value;
  37065. }
  37066. }
  37067. /**
  37068. * This class represents a uniform buffer binding but with
  37069. * an API that allows to maintain individual uniform objects.
  37070. *
  37071. * @private
  37072. * @augments UniformBuffer
  37073. */
  37074. class UniformsGroup extends UniformBuffer {
  37075. /**
  37076. * Constructs a new uniforms group.
  37077. *
  37078. * @param {string} name - The group's name.
  37079. */
  37080. constructor( name ) {
  37081. super( name );
  37082. /**
  37083. * This flag can be used for type testing.
  37084. *
  37085. * @type {boolean}
  37086. * @readonly
  37087. * @default true
  37088. */
  37089. this.isUniformsGroup = true;
  37090. /**
  37091. * An array with the raw uniform values.
  37092. *
  37093. * @private
  37094. * @type {?Array<number>}
  37095. * @default null
  37096. */
  37097. this._values = null;
  37098. /**
  37099. * An array of uniform objects.
  37100. *
  37101. * The order of uniforms in this array must match the order of uniforms in the shader.
  37102. *
  37103. * @type {Array<Uniform>}
  37104. */
  37105. this.uniforms = [];
  37106. }
  37107. /**
  37108. * Adds a uniform to this group.
  37109. *
  37110. * @param {Uniform} uniform - The uniform to add.
  37111. * @return {UniformsGroup} A reference to this group.
  37112. */
  37113. addUniform( uniform ) {
  37114. this.uniforms.push( uniform );
  37115. return this;
  37116. }
  37117. /**
  37118. * Removes a uniform from this group.
  37119. *
  37120. * @param {Uniform} uniform - The uniform to remove.
  37121. * @return {UniformsGroup} A reference to this group.
  37122. */
  37123. removeUniform( uniform ) {
  37124. const index = this.uniforms.indexOf( uniform );
  37125. if ( index !== -1 ) {
  37126. this.uniforms.splice( index, 1 );
  37127. }
  37128. return this;
  37129. }
  37130. /**
  37131. * An array with the raw uniform values.
  37132. *
  37133. * @type {Array<number>}
  37134. */
  37135. get values() {
  37136. if ( this._values === null ) {
  37137. this._values = Array.from( this.buffer );
  37138. }
  37139. return this._values;
  37140. }
  37141. /**
  37142. * A Float32 array buffer with the uniform values.
  37143. *
  37144. * @type {Float32Array}
  37145. */
  37146. get buffer() {
  37147. let buffer = this._buffer;
  37148. if ( buffer === null ) {
  37149. const byteLength = this.byteLength;
  37150. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  37151. this._buffer = buffer;
  37152. }
  37153. return buffer;
  37154. }
  37155. /**
  37156. * The byte length of the buffer with correct buffer alignment.
  37157. *
  37158. * @type {number}
  37159. */
  37160. get byteLength() {
  37161. let offset = 0; // global buffer offset in bytes
  37162. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  37163. const uniform = this.uniforms[ i ];
  37164. const { boundary, itemSize } = uniform;
  37165. // offset within a single chunk in bytes
  37166. const chunkOffset = offset % GPU_CHUNK_BYTES;
  37167. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  37168. // conformance tests
  37169. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  37170. // check for chunk overflow
  37171. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  37172. } else if ( chunkOffset % boundary !== 0 ) {
  37173. // check for correct alignment
  37174. offset += ( chunkOffset % boundary );
  37175. }
  37176. uniform.offset = ( offset / this.bytesPerElement );
  37177. offset += ( itemSize * this.bytesPerElement );
  37178. }
  37179. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  37180. }
  37181. /**
  37182. * Updates this group by updating each uniform object of
  37183. * the internal uniform list. The uniform objects check if their
  37184. * values has actually changed so this method only returns
  37185. * `true` if there is a real value change.
  37186. *
  37187. * @return {boolean} Whether the uniforms have been updated and
  37188. * must be uploaded to the GPU.
  37189. */
  37190. update() {
  37191. let updated = false;
  37192. for ( const uniform of this.uniforms ) {
  37193. if ( this.updateByType( uniform ) === true ) {
  37194. updated = true;
  37195. }
  37196. }
  37197. return updated;
  37198. }
  37199. /**
  37200. * Updates a given uniform by calling an update method matching
  37201. * the uniforms type.
  37202. *
  37203. * @param {Uniform} uniform - The uniform to update.
  37204. * @return {boolean} Whether the uniform has been updated or not.
  37205. */
  37206. updateByType( uniform ) {
  37207. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  37208. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  37209. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  37210. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  37211. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  37212. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  37213. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  37214. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  37215. }
  37216. /**
  37217. * Updates a given Number uniform.
  37218. *
  37219. * @param {NumberUniform} uniform - The Number uniform.
  37220. * @return {boolean} Whether the uniform has been updated or not.
  37221. */
  37222. updateNumber( uniform ) {
  37223. let updated = false;
  37224. const a = this.values;
  37225. const v = uniform.getValue();
  37226. const offset = uniform.offset;
  37227. const type = uniform.getType();
  37228. if ( a[ offset ] !== v ) {
  37229. const b = this._getBufferForType( type );
  37230. b[ offset ] = a[ offset ] = v;
  37231. updated = true;
  37232. }
  37233. return updated;
  37234. }
  37235. /**
  37236. * Updates a given Vector2 uniform.
  37237. *
  37238. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  37239. * @return {boolean} Whether the uniform has been updated or not.
  37240. */
  37241. updateVector2( uniform ) {
  37242. let updated = false;
  37243. const a = this.values;
  37244. const v = uniform.getValue();
  37245. const offset = uniform.offset;
  37246. const type = uniform.getType();
  37247. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  37248. const b = this._getBufferForType( type );
  37249. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37250. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37251. updated = true;
  37252. }
  37253. return updated;
  37254. }
  37255. /**
  37256. * Updates a given Vector3 uniform.
  37257. *
  37258. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  37259. * @return {boolean} Whether the uniform has been updated or not.
  37260. */
  37261. updateVector3( uniform ) {
  37262. let updated = false;
  37263. const a = this.values;
  37264. const v = uniform.getValue();
  37265. const offset = uniform.offset;
  37266. const type = uniform.getType();
  37267. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  37268. const b = this._getBufferForType( type );
  37269. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37270. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37271. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37272. updated = true;
  37273. }
  37274. return updated;
  37275. }
  37276. /**
  37277. * Updates a given Vector4 uniform.
  37278. *
  37279. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  37280. * @return {boolean} Whether the uniform has been updated or not.
  37281. */
  37282. updateVector4( uniform ) {
  37283. let updated = false;
  37284. const a = this.values;
  37285. const v = uniform.getValue();
  37286. const offset = uniform.offset;
  37287. const type = uniform.getType();
  37288. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  37289. const b = this._getBufferForType( type );
  37290. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37291. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37292. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37293. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  37294. updated = true;
  37295. }
  37296. return updated;
  37297. }
  37298. /**
  37299. * Updates a given Color uniform.
  37300. *
  37301. * @param {ColorUniform} uniform - The Color uniform.
  37302. * @return {boolean} Whether the uniform has been updated or not.
  37303. */
  37304. updateColor( uniform ) {
  37305. let updated = false;
  37306. const a = this.values;
  37307. const c = uniform.getValue();
  37308. const offset = uniform.offset;
  37309. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  37310. const b = this.buffer;
  37311. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  37312. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  37313. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  37314. updated = true;
  37315. }
  37316. return updated;
  37317. }
  37318. /**
  37319. * Updates a given Matrix3 uniform.
  37320. *
  37321. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  37322. * @return {boolean} Whether the uniform has been updated or not.
  37323. */
  37324. updateMatrix3( uniform ) {
  37325. let updated = false;
  37326. const a = this.values;
  37327. const e = uniform.getValue().elements;
  37328. const offset = uniform.offset;
  37329. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  37330. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  37331. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  37332. const b = this.buffer;
  37333. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  37334. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  37335. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  37336. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  37337. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  37338. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  37339. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  37340. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  37341. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  37342. updated = true;
  37343. }
  37344. return updated;
  37345. }
  37346. /**
  37347. * Updates a given Matrix4 uniform.
  37348. *
  37349. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  37350. * @return {boolean} Whether the uniform has been updated or not.
  37351. */
  37352. updateMatrix4( uniform ) {
  37353. let updated = false;
  37354. const a = this.values;
  37355. const e = uniform.getValue().elements;
  37356. const offset = uniform.offset;
  37357. if ( arraysEqual( a, e, offset ) === false ) {
  37358. const b = this.buffer;
  37359. b.set( e, offset );
  37360. setArray( a, e, offset );
  37361. updated = true;
  37362. }
  37363. return updated;
  37364. }
  37365. /**
  37366. * Returns a typed array that matches the given data type.
  37367. *
  37368. * @param {string} type - The data type.
  37369. * @return {TypedArray} The typed array.
  37370. */
  37371. _getBufferForType( type ) {
  37372. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  37373. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  37374. return this.buffer;
  37375. }
  37376. }
  37377. /**
  37378. * Sets the values of the second array to the first array.
  37379. *
  37380. * @private
  37381. * @param {TypedArray} a - The first array.
  37382. * @param {TypedArray} b - The second array.
  37383. * @param {number} offset - An index offset for the first array.
  37384. */
  37385. function setArray( a, b, offset ) {
  37386. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37387. a[ offset + i ] = b[ i ];
  37388. }
  37389. }
  37390. /**
  37391. * Returns `true` if the given arrays are equal.
  37392. *
  37393. * @private
  37394. * @param {TypedArray} a - The first array.
  37395. * @param {TypedArray} b - The second array.
  37396. * @param {number} offset - An index offset for the first array.
  37397. * @return {boolean} Whether the given arrays are equal or not.
  37398. */
  37399. function arraysEqual( a, b, offset ) {
  37400. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37401. if ( a[ offset + i ] !== b[ i ] ) return false;
  37402. }
  37403. return true;
  37404. }
  37405. let _id$3 = 0;
  37406. /**
  37407. * A special form of uniforms group that represents
  37408. * the individual uniforms as node-based uniforms.
  37409. *
  37410. * @private
  37411. * @augments UniformsGroup
  37412. */
  37413. class NodeUniformsGroup extends UniformsGroup {
  37414. /**
  37415. * Constructs a new node-based uniforms group.
  37416. *
  37417. * @param {string} name - The group's name.
  37418. * @param {UniformGroupNode} groupNode - The uniform group node.
  37419. */
  37420. constructor( name, groupNode ) {
  37421. super( name );
  37422. /**
  37423. * The group's ID.
  37424. *
  37425. * @type {number}
  37426. */
  37427. this.id = _id$3 ++;
  37428. /**
  37429. * The uniform group node.
  37430. *
  37431. * @type {UniformGroupNode}
  37432. */
  37433. this.groupNode = groupNode;
  37434. /**
  37435. * This flag can be used for type testing.
  37436. *
  37437. * @type {boolean}
  37438. * @readonly
  37439. * @default true
  37440. */
  37441. this.isNodeUniformsGroup = true;
  37442. }
  37443. }
  37444. let _id$2 = 0;
  37445. /**
  37446. * Represents a sampled texture binding type.
  37447. *
  37448. * @private
  37449. * @augments Binding
  37450. */
  37451. class SampledTexture extends Binding {
  37452. /**
  37453. * Constructs a new sampled texture.
  37454. *
  37455. * @param {string} name - The sampled texture's name.
  37456. * @param {?Texture} texture - The texture this binding is referring to.
  37457. */
  37458. constructor( name, texture ) {
  37459. super( name );
  37460. /**
  37461. * This identifier.
  37462. *
  37463. * @type {number}
  37464. */
  37465. this.id = _id$2 ++;
  37466. /**
  37467. * The texture this binding is referring to.
  37468. *
  37469. * @type {?Texture}
  37470. */
  37471. this.texture = texture;
  37472. /**
  37473. * The binding's version.
  37474. *
  37475. * @type {number}
  37476. */
  37477. this.version = texture ? texture.version : 0;
  37478. /**
  37479. * Whether the texture is a storage texture or not.
  37480. *
  37481. * @type {boolean}
  37482. * @default false
  37483. */
  37484. this.store = false;
  37485. /**
  37486. * The binding's generation which is an additional version
  37487. * qualifier.
  37488. *
  37489. * @type {?number}
  37490. * @default null
  37491. */
  37492. this.generation = null;
  37493. /**
  37494. * This flag can be used for type testing.
  37495. *
  37496. * @type {boolean}
  37497. * @readonly
  37498. * @default true
  37499. */
  37500. this.isSampledTexture = true;
  37501. }
  37502. /**
  37503. * Returns `true` whether this binding requires an update for the
  37504. * given generation.
  37505. *
  37506. * @param {number} generation - The generation.
  37507. * @return {boolean} Whether an update is required or not.
  37508. */
  37509. needsBindingsUpdate( generation ) {
  37510. const { texture } = this;
  37511. if ( generation !== this.generation ) {
  37512. this.generation = generation;
  37513. return true;
  37514. }
  37515. return texture.isVideoTexture;
  37516. }
  37517. /**
  37518. * Updates the binding.
  37519. *
  37520. * @return {boolean} Whether the texture has been updated and must be
  37521. * uploaded to the GPU.
  37522. */
  37523. update() {
  37524. const { texture, version } = this;
  37525. if ( version !== texture.version ) {
  37526. this.version = texture.version;
  37527. return true;
  37528. }
  37529. return false;
  37530. }
  37531. }
  37532. /**
  37533. * A special form of sampled texture binding type.
  37534. * It's texture value is managed by a node object.
  37535. *
  37536. * @private
  37537. * @augments SampledTexture
  37538. */
  37539. class NodeSampledTexture extends SampledTexture {
  37540. /**
  37541. * Constructs a new node-based sampled texture.
  37542. *
  37543. * @param {string} name - The textures's name.
  37544. * @param {TextureNode} textureNode - The texture node.
  37545. * @param {UniformGroupNode} groupNode - The uniform group node.
  37546. * @param {?string} [access=null] - The access type.
  37547. */
  37548. constructor( name, textureNode, groupNode, access = null ) {
  37549. super( name, textureNode ? textureNode.value : null );
  37550. /**
  37551. * The texture node.
  37552. *
  37553. * @type {TextureNode}
  37554. */
  37555. this.textureNode = textureNode;
  37556. /**
  37557. * The uniform group node.
  37558. *
  37559. * @type {UniformGroupNode}
  37560. */
  37561. this.groupNode = groupNode;
  37562. /**
  37563. * The access type.
  37564. *
  37565. * @type {?string}
  37566. * @default null
  37567. */
  37568. this.access = access;
  37569. }
  37570. /**
  37571. * Overwrites the default to additionally check if the node value has changed.
  37572. *
  37573. * @param {number} generation - The generation.
  37574. * @return {boolean} Whether an update is required or not.
  37575. */
  37576. needsBindingsUpdate( generation ) {
  37577. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  37578. }
  37579. /**
  37580. * Updates the binding.
  37581. *
  37582. * @return {boolean} Whether the texture has been updated and must be
  37583. * uploaded to the GPU.
  37584. */
  37585. update() {
  37586. const { textureNode } = this;
  37587. if ( this.texture !== textureNode.value ) {
  37588. this.texture = textureNode.value;
  37589. return true;
  37590. }
  37591. return super.update();
  37592. }
  37593. }
  37594. /**
  37595. * A special form of sampled cube texture binding type.
  37596. * It's texture value is managed by a node object.
  37597. *
  37598. * @private
  37599. * @augments NodeSampledTexture
  37600. */
  37601. class NodeSampledCubeTexture extends NodeSampledTexture {
  37602. /**
  37603. * Constructs a new node-based sampled cube texture.
  37604. *
  37605. * @param {string} name - The textures's name.
  37606. * @param {TextureNode} textureNode - The texture node.
  37607. * @param {UniformGroupNode} groupNode - The uniform group node.
  37608. * @param {?string} [access=null] - The access type.
  37609. */
  37610. constructor( name, textureNode, groupNode, access = null ) {
  37611. super( name, textureNode, groupNode, access );
  37612. /**
  37613. * This flag can be used for type testing.
  37614. *
  37615. * @type {boolean}
  37616. * @readonly
  37617. * @default true
  37618. */
  37619. this.isSampledCubeTexture = true;
  37620. }
  37621. }
  37622. /**
  37623. * A special form of sampled 3D texture binding type.
  37624. * It's texture value is managed by a node object.
  37625. *
  37626. * @private
  37627. * @augments NodeSampledTexture
  37628. */
  37629. class NodeSampledTexture3D extends NodeSampledTexture {
  37630. /**
  37631. * Constructs a new node-based sampled 3D texture.
  37632. *
  37633. * @param {string} name - The textures's name.
  37634. * @param {TextureNode} textureNode - The texture node.
  37635. * @param {UniformGroupNode} groupNode - The uniform group node.
  37636. * @param {?string} [access=null] - The access type.
  37637. */
  37638. constructor( name, textureNode, groupNode, access = null ) {
  37639. super( name, textureNode, groupNode, access );
  37640. /**
  37641. * This flag can be used for type testing.
  37642. *
  37643. * @type {boolean}
  37644. * @readonly
  37645. * @default true
  37646. */
  37647. this.isSampledTexture3D = true;
  37648. }
  37649. }
  37650. const glslMethods = {
  37651. textureDimensions: 'textureSize',
  37652. equals: 'equal'
  37653. };
  37654. const precisionLib = {
  37655. low: 'lowp',
  37656. medium: 'mediump',
  37657. high: 'highp'
  37658. };
  37659. const supports$1 = {
  37660. swizzleAssign: true,
  37661. storageBuffer: false
  37662. };
  37663. const defaultPrecisions = `
  37664. precision highp float;
  37665. precision highp int;
  37666. precision highp sampler2D;
  37667. precision highp sampler3D;
  37668. precision highp samplerCube;
  37669. precision highp sampler2DArray;
  37670. precision highp usampler2D;
  37671. precision highp usampler3D;
  37672. precision highp usamplerCube;
  37673. precision highp usampler2DArray;
  37674. precision highp isampler2D;
  37675. precision highp isampler3D;
  37676. precision highp isamplerCube;
  37677. precision highp isampler2DArray;
  37678. precision lowp sampler2DShadow;
  37679. `;
  37680. /**
  37681. * A node builder targeting GLSL.
  37682. *
  37683. * This module generates GLSL shader code from node materials and also
  37684. * generates the respective bindings and vertex buffer definitions. These
  37685. * data are later used by the renderer to create render and compute pipelines
  37686. * for render objects.
  37687. *
  37688. * @augments NodeBuilder
  37689. */
  37690. class GLSLNodeBuilder extends NodeBuilder {
  37691. /**
  37692. * Constructs a new GLSL node builder renderer.
  37693. *
  37694. * @param {Object3D} object - The 3D object.
  37695. * @param {Renderer} renderer - The renderer.
  37696. */
  37697. constructor( object, renderer ) {
  37698. super( object, renderer, new GLSLNodeParser() );
  37699. /**
  37700. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  37701. * another dictionary which manages UBOs per group ('render','frame','object').
  37702. *
  37703. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  37704. */
  37705. this.uniformGroups = {};
  37706. /**
  37707. * An array that holds objects defining the varying and attribute data in
  37708. * context of Transform Feedback.
  37709. *
  37710. * @type {Object<string,Map<string,Object>>}
  37711. */
  37712. this.transforms = [];
  37713. /**
  37714. * A dictionary that holds for each shader stage a Map of used extensions.
  37715. *
  37716. * @type {Object<string,Map<string,Object>>}
  37717. */
  37718. this.extensions = {};
  37719. /**
  37720. * A dictionary that holds for each shader stage an Array of used builtins.
  37721. *
  37722. * @type {Object<string,Array<string>>}
  37723. */
  37724. this.builtins = { vertex: [], fragment: [], compute: [] };
  37725. /**
  37726. * Whether comparison in shader code are generated with methods or not.
  37727. *
  37728. * @type {boolean}
  37729. * @default true
  37730. */
  37731. this.useComparisonMethod = true;
  37732. }
  37733. /**
  37734. * Checks if the given texture requires a manual conversion to the working color space.
  37735. *
  37736. * @param {Texture} texture - The texture to check.
  37737. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  37738. */
  37739. needsToWorkingColorSpace( texture ) {
  37740. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  37741. }
  37742. /**
  37743. * Returns the native shader method name for a given generic name.
  37744. *
  37745. * @param {string} method - The method name to resolve.
  37746. * @return {string} The resolved GLSL method name.
  37747. */
  37748. getMethod( method ) {
  37749. return glslMethods[ method ] || method;
  37750. }
  37751. /**
  37752. * Returns the output struct name. Not relevant for GLSL.
  37753. *
  37754. * @return {string}
  37755. */
  37756. getOutputStructName() {
  37757. return '';
  37758. }
  37759. /**
  37760. * Builds the given shader node.
  37761. *
  37762. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37763. * @return {string} The GLSL function code.
  37764. */
  37765. buildFunctionCode( shaderNode ) {
  37766. const layout = shaderNode.layout;
  37767. const flowData = this.flowShaderNode( shaderNode );
  37768. const parameters = [];
  37769. for ( const input of layout.inputs ) {
  37770. parameters.push( this.getType( input.type ) + ' ' + input.name );
  37771. }
  37772. //
  37773. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  37774. ${ flowData.vars }
  37775. ${ flowData.code }
  37776. return ${ flowData.result };
  37777. }`;
  37778. //
  37779. return code;
  37780. }
  37781. /**
  37782. * Setups the Pixel Buffer Object (PBO) for the given storage
  37783. * buffer node.
  37784. *
  37785. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  37786. */
  37787. setupPBO( storageBufferNode ) {
  37788. const attribute = storageBufferNode.value;
  37789. if ( attribute.pbo === undefined ) {
  37790. const originalArray = attribute.array;
  37791. const numElements = attribute.count * attribute.itemSize;
  37792. const { itemSize } = attribute;
  37793. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  37794. let format = isInteger ? RedIntegerFormat : RedFormat;
  37795. if ( itemSize === 2 ) {
  37796. format = isInteger ? RGIntegerFormat : RGFormat;
  37797. } else if ( itemSize === 3 ) {
  37798. format = isInteger ? RGBIntegerFormat : RGBFormat;
  37799. } else if ( itemSize === 4 ) {
  37800. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  37801. }
  37802. const typeMap = {
  37803. Float32Array: FloatType,
  37804. Uint8Array: UnsignedByteType,
  37805. Uint16Array: UnsignedShortType,
  37806. Uint32Array: UnsignedIntType,
  37807. Int8Array: ByteType,
  37808. Int16Array: ShortType,
  37809. Int32Array: IntType,
  37810. Uint8ClampedArray: UnsignedByteType,
  37811. };
  37812. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  37813. let height = Math.ceil( ( numElements / itemSize ) / width );
  37814. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  37815. const newSize = width * height * itemSize;
  37816. const newArray = new originalArray.constructor( newSize );
  37817. newArray.set( originalArray, 0 );
  37818. attribute.array = newArray;
  37819. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  37820. pboTexture.needsUpdate = true;
  37821. pboTexture.isPBOTexture = true;
  37822. const pbo = new TextureNode( pboTexture, null, null );
  37823. pbo.setPrecision( 'high' );
  37824. attribute.pboNode = pbo;
  37825. attribute.pbo = pbo.value;
  37826. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37827. }
  37828. }
  37829. /**
  37830. * Returns a GLSL snippet that represents the property name of the given node.
  37831. *
  37832. * @param {Node} node - The node.
  37833. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37834. * @return {string} The property name.
  37835. */
  37836. getPropertyName( node, shaderStage = this.shaderStage ) {
  37837. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  37838. return shaderStage.charAt( 0 ) + '_' + node.name;
  37839. }
  37840. return super.getPropertyName( node, shaderStage );
  37841. }
  37842. /**
  37843. * Setups the Pixel Buffer Object (PBO) for the given storage
  37844. * buffer node.
  37845. *
  37846. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  37847. * @return {string} The property name.
  37848. */
  37849. generatePBO( storageArrayElementNode ) {
  37850. const { node, indexNode } = storageArrayElementNode;
  37851. const attribute = node.value;
  37852. if ( this.renderer.backend.has( attribute ) ) {
  37853. const attributeData = this.renderer.backend.get( attribute );
  37854. attributeData.pbo = attribute.pbo;
  37855. }
  37856. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37857. const textureName = this.getPropertyName( nodeUniform );
  37858. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  37859. const indexSnippet = indexNode.build( this, 'uint' );
  37860. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  37861. let propertyName = elementNodeData.propertyName;
  37862. if ( propertyName === undefined ) {
  37863. // property element
  37864. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  37865. propertyName = this.getPropertyName( nodeVar );
  37866. // property size
  37867. const bufferNodeData = this.getDataFromNode( node );
  37868. let propertySizeName = bufferNodeData.propertySizeName;
  37869. if ( propertySizeName === undefined ) {
  37870. propertySizeName = propertyName + 'Size';
  37871. this.getVarFromNode( node, propertySizeName, 'uint' );
  37872. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  37873. bufferNodeData.propertySizeName = propertySizeName;
  37874. }
  37875. //
  37876. const { itemSize } = attribute;
  37877. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  37878. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  37879. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  37880. //
  37881. let prefix = 'vec4';
  37882. if ( attribute.pbo.type === UnsignedIntType ) {
  37883. prefix = 'uvec4';
  37884. } else if ( attribute.pbo.type === IntType ) {
  37885. prefix = 'ivec4';
  37886. }
  37887. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  37888. elementNodeData.propertyName = propertyName;
  37889. }
  37890. return propertyName;
  37891. }
  37892. /**
  37893. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  37894. *
  37895. * @param {Texture} texture - The texture.
  37896. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37897. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37898. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37899. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37900. * @return {string} The GLSL snippet.
  37901. */
  37902. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  37903. if ( depthSnippet ) {
  37904. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  37905. } else {
  37906. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  37907. }
  37908. }
  37909. /**
  37910. * Generates the GLSL snippet for sampling/loading the given texture.
  37911. *
  37912. * @param {Texture} texture - The texture.
  37913. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37914. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37915. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37916. * @return {string} The GLSL snippet.
  37917. */
  37918. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  37919. if ( texture.isDepthTexture ) {
  37920. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  37921. } else {
  37922. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  37923. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  37924. }
  37925. }
  37926. /**
  37927. * Generates the GLSL snippet when sampling textures with explicit mip level.
  37928. *
  37929. * @param {Texture} texture - The texture.
  37930. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37931. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37932. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37933. * @return {string} The GLSL snippet.
  37934. */
  37935. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  37936. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  37937. }
  37938. /**
  37939. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  37940. *
  37941. * @param {Texture} texture - The texture.
  37942. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37943. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37944. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  37945. * @return {string} The GLSL snippet.
  37946. */
  37947. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  37948. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  37949. }
  37950. /**
  37951. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  37952. *
  37953. * @param {Texture} texture - The texture.
  37954. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37955. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37956. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  37957. * @return {string} The GLSL snippet.
  37958. */
  37959. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  37960. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  37961. }
  37962. /**
  37963. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  37964. * against a reference value.
  37965. *
  37966. * @param {Texture} texture - The texture.
  37967. * @param {string} textureProperty - The name of the texture uniform in the shader.
  37968. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37969. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  37970. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  37971. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37972. * @return {string} The GLSL snippet.
  37973. */
  37974. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37975. if ( shaderStage === 'fragment' ) {
  37976. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37977. } else {
  37978. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37979. }
  37980. }
  37981. /**
  37982. * Returns the variables of the given shader stage as a GLSL string.
  37983. *
  37984. * @param {string} shaderStage - The shader stage.
  37985. * @return {string} The GLSL snippet that defines the variables.
  37986. */
  37987. getVars( shaderStage ) {
  37988. const snippets = [];
  37989. const vars = this.vars[ shaderStage ];
  37990. if ( vars !== undefined ) {
  37991. for ( const variable of vars ) {
  37992. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  37993. }
  37994. }
  37995. return snippets.join( '\n\t' );
  37996. }
  37997. /**
  37998. * Returns the uniforms of the given shader stage as a GLSL string.
  37999. *
  38000. * @param {string} shaderStage - The shader stage.
  38001. * @return {string} The GLSL snippet that defines the uniforms.
  38002. */
  38003. getUniforms( shaderStage ) {
  38004. const uniforms = this.uniforms[ shaderStage ];
  38005. const bindingSnippets = [];
  38006. const uniformGroups = {};
  38007. for ( const uniform of uniforms ) {
  38008. let snippet = null;
  38009. let group = false;
  38010. if ( uniform.type === 'texture' ) {
  38011. const texture = uniform.node.value;
  38012. let typePrefix = '';
  38013. if ( texture.isDataTexture === true ) {
  38014. if ( texture.type === UnsignedIntType ) {
  38015. typePrefix = 'u';
  38016. } else if ( texture.type === IntType ) {
  38017. typePrefix = 'i';
  38018. }
  38019. }
  38020. if ( texture.compareFunction ) {
  38021. snippet = `sampler2DShadow ${ uniform.name };`;
  38022. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38023. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38024. } else {
  38025. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38026. }
  38027. } else if ( uniform.type === 'cubeTexture' ) {
  38028. snippet = `samplerCube ${ uniform.name };`;
  38029. } else if ( uniform.type === 'texture3D' ) {
  38030. snippet = `sampler3D ${ uniform.name };`;
  38031. } else if ( uniform.type === 'buffer' ) {
  38032. const bufferNode = uniform.node;
  38033. const bufferType = this.getType( bufferNode.bufferType );
  38034. const bufferCount = bufferNode.bufferCount;
  38035. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38036. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38037. } else {
  38038. const vectorType = this.getVectorType( uniform.type );
  38039. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38040. group = true;
  38041. }
  38042. const precision = uniform.node.precision;
  38043. if ( precision !== null ) {
  38044. snippet = precisionLib[ precision ] + ' ' + snippet;
  38045. }
  38046. if ( group ) {
  38047. snippet = '\t' + snippet;
  38048. const groupName = uniform.groupNode.name;
  38049. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38050. groupSnippets.push( snippet );
  38051. } else {
  38052. snippet = 'uniform ' + snippet;
  38053. bindingSnippets.push( snippet );
  38054. }
  38055. }
  38056. let output = '';
  38057. for ( const name in uniformGroups ) {
  38058. const groupSnippets = uniformGroups[ name ];
  38059. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38060. }
  38061. output += bindingSnippets.join( '\n' );
  38062. return output;
  38063. }
  38064. /**
  38065. * Returns the type for a given buffer attribute.
  38066. *
  38067. * @param {BufferAttribute} attribute - The buffer attribute.
  38068. * @return {string} The type.
  38069. */
  38070. getTypeFromAttribute( attribute ) {
  38071. let nodeType = super.getTypeFromAttribute( attribute );
  38072. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38073. let dataAttribute = attribute;
  38074. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38075. const array = dataAttribute.array;
  38076. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38077. nodeType = nodeType.slice( 1 );
  38078. }
  38079. }
  38080. return nodeType;
  38081. }
  38082. /**
  38083. * Returns the shader attributes of the given shader stage as a GLSL string.
  38084. *
  38085. * @param {string} shaderStage - The shader stage.
  38086. * @return {string} The GLSL snippet that defines the shader attributes.
  38087. */
  38088. getAttributes( shaderStage ) {
  38089. let snippet = '';
  38090. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38091. const attributes = this.getAttributesArray();
  38092. let location = 0;
  38093. for ( const attribute of attributes ) {
  38094. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38095. }
  38096. }
  38097. return snippet;
  38098. }
  38099. /**
  38100. * Returns the members of the given struct type node as a GLSL string.
  38101. *
  38102. * @param {StructTypeNode} struct - The struct type node.
  38103. * @return {string} The GLSL snippet that defines the struct members.
  38104. */
  38105. getStructMembers( struct ) {
  38106. const snippets = [];
  38107. for ( const member of struct.members ) {
  38108. snippets.push( `\t${ member.type } ${ member.name };` );
  38109. }
  38110. return snippets.join( '\n' );
  38111. }
  38112. /**
  38113. * Returns the structs of the given shader stage as a GLSL string.
  38114. *
  38115. * @param {string} shaderStage - The shader stage.
  38116. * @return {string} The GLSL snippet that defines the structs.
  38117. */
  38118. getStructs( shaderStage ) {
  38119. const snippets = [];
  38120. const structs = this.structs[ shaderStage ];
  38121. const outputSnippet = [];
  38122. for ( const struct of structs ) {
  38123. if ( struct.output ) {
  38124. for ( const member of struct.members ) {
  38125. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  38126. }
  38127. } else {
  38128. let snippet = 'struct ' + struct.name + ' {\n';
  38129. snippet += this.getStructMembers( struct );
  38130. snippet += '\n};\n';
  38131. snippets.push( snippet );
  38132. }
  38133. }
  38134. if ( outputSnippet.length === 0 ) {
  38135. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  38136. }
  38137. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  38138. }
  38139. /**
  38140. * Returns the varyings of the given shader stage as a GLSL string.
  38141. *
  38142. * @param {string} shaderStage - The shader stage.
  38143. * @return {string} The GLSL snippet that defines the varyings.
  38144. */
  38145. getVaryings( shaderStage ) {
  38146. let snippet = '';
  38147. const varyings = this.varyings;
  38148. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38149. for ( const varying of varyings ) {
  38150. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38151. const type = this.getType( varying.type );
  38152. if ( varying.needsInterpolation ) {
  38153. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38154. snippet += `${flat} out ${type} ${varying.name};\n`;
  38155. } else {
  38156. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  38157. }
  38158. }
  38159. } else if ( shaderStage === 'fragment' ) {
  38160. for ( const varying of varyings ) {
  38161. if ( varying.needsInterpolation ) {
  38162. const type = this.getType( varying.type );
  38163. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38164. snippet += `${flat}in ${type} ${varying.name};\n`;
  38165. }
  38166. }
  38167. }
  38168. for ( const builtin of this.builtins[ shaderStage ] ) {
  38169. snippet += `${builtin};\n`;
  38170. }
  38171. return snippet;
  38172. }
  38173. /**
  38174. * Returns the vertex index builtin.
  38175. *
  38176. * @return {string} The vertex index.
  38177. */
  38178. getVertexIndex() {
  38179. return 'uint( gl_VertexID )';
  38180. }
  38181. /**
  38182. * Returns the instance index builtin.
  38183. *
  38184. * @return {string} The instance index.
  38185. */
  38186. getInstanceIndex() {
  38187. return 'uint( gl_InstanceID )';
  38188. }
  38189. /**
  38190. * Returns the invocation local index builtin.
  38191. *
  38192. * @return {string} The invocation local index.
  38193. */
  38194. getInvocationLocalIndex() {
  38195. const workgroupSize = this.object.workgroupSize;
  38196. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  38197. return `uint( gl_InstanceID ) % ${size}u`;
  38198. }
  38199. /**
  38200. * Returns the draw index builtin.
  38201. *
  38202. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  38203. */
  38204. getDrawIndex() {
  38205. const extensions = this.renderer.backend.extensions;
  38206. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38207. return 'uint( gl_DrawID )';
  38208. }
  38209. return null;
  38210. }
  38211. /**
  38212. * Returns the front facing builtin.
  38213. *
  38214. * @return {string} The front facing builtin.
  38215. */
  38216. getFrontFacing() {
  38217. return 'gl_FrontFacing';
  38218. }
  38219. /**
  38220. * Returns the frag coord builtin.
  38221. *
  38222. * @return {string} The frag coord builtin.
  38223. */
  38224. getFragCoord() {
  38225. return 'gl_FragCoord.xy';
  38226. }
  38227. /**
  38228. * Returns the frag depth builtin.
  38229. *
  38230. * @return {string} The frag depth builtin.
  38231. */
  38232. getFragDepth() {
  38233. return 'gl_FragDepth';
  38234. }
  38235. /**
  38236. * Enables the given extension.
  38237. *
  38238. * @param {string} name - The extension name.
  38239. * @param {string} behavior - The extension behavior.
  38240. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  38241. */
  38242. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38243. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38244. if ( map.has( name ) === false ) {
  38245. map.set( name, {
  38246. name,
  38247. behavior
  38248. } );
  38249. }
  38250. }
  38251. /**
  38252. * Returns the enabled extensions of the given shader stage as a GLSL string.
  38253. *
  38254. * @param {string} shaderStage - The shader stage.
  38255. * @return {string} The GLSL snippet that defines the enabled extensions.
  38256. */
  38257. getExtensions( shaderStage ) {
  38258. const snippets = [];
  38259. if ( shaderStage === 'vertex' ) {
  38260. const ext = this.renderer.backend.extensions;
  38261. const isBatchedMesh = this.object.isBatchedMesh;
  38262. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38263. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  38264. }
  38265. }
  38266. const extensions = this.extensions[ shaderStage ];
  38267. if ( extensions !== undefined ) {
  38268. for ( const { name, behavior } of extensions.values() ) {
  38269. snippets.push( `#extension ${name} : ${behavior}` );
  38270. }
  38271. }
  38272. return snippets.join( '\n' );
  38273. }
  38274. /**
  38275. * Returns the clip distances builtin.
  38276. *
  38277. * @return {string} The clip distances builtin.
  38278. */
  38279. getClipDistance() {
  38280. return 'gl_ClipDistance';
  38281. }
  38282. /**
  38283. * Whether the requested feature is available or not.
  38284. *
  38285. * @param {string} name - The requested feature.
  38286. * @return {boolean} Whether the requested feature is supported or not.
  38287. */
  38288. isAvailable( name ) {
  38289. let result = supports$1[ name ];
  38290. if ( result === undefined ) {
  38291. let extensionName;
  38292. result = false;
  38293. switch ( name ) {
  38294. case 'float32Filterable':
  38295. extensionName = 'OES_texture_float_linear';
  38296. break;
  38297. case 'clipDistance':
  38298. extensionName = 'WEBGL_clip_cull_distance';
  38299. break;
  38300. }
  38301. if ( extensionName !== undefined ) {
  38302. const extensions = this.renderer.backend.extensions;
  38303. if ( extensions.has( extensionName ) ) {
  38304. extensions.get( extensionName );
  38305. result = true;
  38306. }
  38307. }
  38308. supports$1[ name ] = result;
  38309. }
  38310. return result;
  38311. }
  38312. /**
  38313. * Whether to flip texture data along its vertical axis or not.
  38314. *
  38315. * @return {boolean} Returns always `true` in context of GLSL.
  38316. */
  38317. isFlipY() {
  38318. return true;
  38319. }
  38320. /**
  38321. * Enables hardware clipping.
  38322. *
  38323. * @param {string} planeCount - The clipping plane count.
  38324. */
  38325. enableHardwareClipping( planeCount ) {
  38326. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  38327. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  38328. }
  38329. /**
  38330. * Registers a transform in context of Transform Feedback.
  38331. *
  38332. * @param {string} varyingName - The varying name.
  38333. * @param {AttributeNode} attributeNode - The attribute node.
  38334. */
  38335. registerTransform( varyingName, attributeNode ) {
  38336. this.transforms.push( { varyingName, attributeNode } );
  38337. }
  38338. /**
  38339. * Returns the transforms of the given shader stage as a GLSL string.
  38340. *
  38341. * @param {string} shaderStage - The shader stage.
  38342. * @return {string} The GLSL snippet that defines the transforms.
  38343. */
  38344. getTransforms( /* shaderStage */ ) {
  38345. const transforms = this.transforms;
  38346. let snippet = '';
  38347. for ( let i = 0; i < transforms.length; i ++ ) {
  38348. const transform = transforms[ i ];
  38349. const attributeName = this.getPropertyName( transform.attributeNode );
  38350. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38351. }
  38352. return snippet;
  38353. }
  38354. /**
  38355. * Returns a GLSL struct based on the given name and variables.
  38356. *
  38357. * @private
  38358. * @param {string} name - The struct name.
  38359. * @param {string} vars - The struct variables.
  38360. * @return {string} The GLSL snippet representing a struct.
  38361. */
  38362. _getGLSLUniformStruct( name, vars ) {
  38363. return `
  38364. layout( std140 ) uniform ${name} {
  38365. ${vars}
  38366. };`;
  38367. }
  38368. /**
  38369. * Returns a GLSL vertex shader based on the given shader data.
  38370. *
  38371. * @private
  38372. * @param {Object} shaderData - The shader data.
  38373. * @return {string} The vertex shader.
  38374. */
  38375. _getGLSLVertexCode( shaderData ) {
  38376. return `#version 300 es
  38377. ${ this.getSignature() }
  38378. // extensions
  38379. ${shaderData.extensions}
  38380. // precision
  38381. ${ defaultPrecisions }
  38382. // uniforms
  38383. ${shaderData.uniforms}
  38384. // varyings
  38385. ${shaderData.varyings}
  38386. // attributes
  38387. ${shaderData.attributes}
  38388. // codes
  38389. ${shaderData.codes}
  38390. void main() {
  38391. // vars
  38392. ${shaderData.vars}
  38393. // transforms
  38394. ${shaderData.transforms}
  38395. // flow
  38396. ${shaderData.flow}
  38397. gl_PointSize = 1.0;
  38398. }
  38399. `;
  38400. }
  38401. /**
  38402. * Returns a GLSL fragment shader based on the given shader data.
  38403. *
  38404. * @private
  38405. * @param {Object} shaderData - The shader data.
  38406. * @return {string} The vertex shader.
  38407. */
  38408. _getGLSLFragmentCode( shaderData ) {
  38409. return `#version 300 es
  38410. ${ this.getSignature() }
  38411. // precision
  38412. ${ defaultPrecisions }
  38413. // uniforms
  38414. ${shaderData.uniforms}
  38415. // varyings
  38416. ${shaderData.varyings}
  38417. // codes
  38418. ${shaderData.codes}
  38419. // structs
  38420. ${shaderData.structs}
  38421. void main() {
  38422. // vars
  38423. ${shaderData.vars}
  38424. // flow
  38425. ${shaderData.flow}
  38426. }
  38427. `;
  38428. }
  38429. /**
  38430. * Controls the code build of the shader stages.
  38431. */
  38432. buildCode() {
  38433. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38434. this.sortBindingGroups();
  38435. for ( const shaderStage in shadersData ) {
  38436. let flow = '// code\n\n';
  38437. flow += this.flowCode[ shaderStage ];
  38438. const flowNodes = this.flowNodes[ shaderStage ];
  38439. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38440. for ( const node of flowNodes ) {
  38441. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38442. const slotName = node.name;
  38443. if ( slotName ) {
  38444. if ( flow.length > 0 ) flow += '\n';
  38445. flow += `\t// flow -> ${ slotName }\n\t`;
  38446. }
  38447. flow += `${ flowSlotData.code }\n\t`;
  38448. if ( node === mainNode && shaderStage !== 'compute' ) {
  38449. flow += '// result\n\t';
  38450. if ( shaderStage === 'vertex' ) {
  38451. flow += 'gl_Position = ';
  38452. flow += `${ flowSlotData.result };`;
  38453. } else if ( shaderStage === 'fragment' ) {
  38454. if ( ! node.outputNode.isOutputStructNode ) {
  38455. flow += 'fragColor = ';
  38456. flow += `${ flowSlotData.result };`;
  38457. }
  38458. }
  38459. }
  38460. }
  38461. const stageData = shadersData[ shaderStage ];
  38462. stageData.extensions = this.getExtensions( shaderStage );
  38463. stageData.uniforms = this.getUniforms( shaderStage );
  38464. stageData.attributes = this.getAttributes( shaderStage );
  38465. stageData.varyings = this.getVaryings( shaderStage );
  38466. stageData.vars = this.getVars( shaderStage );
  38467. stageData.structs = this.getStructs( shaderStage );
  38468. stageData.codes = this.getCodes( shaderStage );
  38469. stageData.transforms = this.getTransforms( shaderStage );
  38470. stageData.flow = flow;
  38471. }
  38472. if ( this.material !== null ) {
  38473. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  38474. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  38475. } else {
  38476. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  38477. }
  38478. }
  38479. /**
  38480. * This method is one of the more important ones since it's responsible
  38481. * for generating a matching binding instance for the given uniform node.
  38482. *
  38483. * These bindings are later used in the renderer to create bind groups
  38484. * and layouts.
  38485. *
  38486. * @param {UniformNode} node - The uniform node.
  38487. * @param {string} type - The node data type.
  38488. * @param {string} shaderStage - The shader stage.
  38489. * @param {?string} [name=null] - An optional uniform name.
  38490. * @return {NodeUniform} The node uniform object.
  38491. */
  38492. getUniformFromNode( node, type, shaderStage, name = null ) {
  38493. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  38494. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  38495. let uniformGPU = nodeData.uniformGPU;
  38496. if ( uniformGPU === undefined ) {
  38497. const group = node.groupNode;
  38498. const groupName = group.name;
  38499. const bindings = this.getBindGroupArray( groupName, shaderStage );
  38500. if ( type === 'texture' ) {
  38501. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  38502. bindings.push( uniformGPU );
  38503. } else if ( type === 'cubeTexture' ) {
  38504. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  38505. bindings.push( uniformGPU );
  38506. } else if ( type === 'texture3D' ) {
  38507. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  38508. bindings.push( uniformGPU );
  38509. } else if ( type === 'buffer' ) {
  38510. node.name = `NodeBuffer_${ node.id }`;
  38511. uniformNode.name = `buffer${ node.id }`;
  38512. const buffer = new NodeUniformBuffer( node, group );
  38513. buffer.name = node.name;
  38514. bindings.push( buffer );
  38515. uniformGPU = buffer;
  38516. } else {
  38517. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  38518. let uniformsGroup = uniformsStage[ groupName ];
  38519. if ( uniformsGroup === undefined ) {
  38520. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  38521. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  38522. uniformsStage[ groupName ] = uniformsGroup;
  38523. bindings.push( uniformsGroup );
  38524. }
  38525. uniformGPU = this.getNodeUniform( uniformNode, type );
  38526. uniformsGroup.addUniform( uniformGPU );
  38527. }
  38528. nodeData.uniformGPU = uniformGPU;
  38529. }
  38530. return uniformNode;
  38531. }
  38532. }
  38533. let _vector2 = null;
  38534. let _color4 = null;
  38535. /**
  38536. * Most of the rendering related logic is implemented in the
  38537. * {@link Renderer} module and related management components.
  38538. * Sometimes it is required though to execute commands which are
  38539. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  38540. * This abstract base class defines an interface that encapsulates
  38541. * all backend-related logic. Derived classes for each backend must
  38542. * implement the interface.
  38543. *
  38544. * @abstract
  38545. * @private
  38546. */
  38547. class Backend {
  38548. /**
  38549. * Constructs a new backend.
  38550. *
  38551. * @param {Object} parameters - An object holding parameters for the backend.
  38552. */
  38553. constructor( parameters = {} ) {
  38554. /**
  38555. * The parameters of the backend.
  38556. *
  38557. * @type {Object}
  38558. */
  38559. this.parameters = Object.assign( {}, parameters );
  38560. /**
  38561. * This weak map holds backend-specific data of objects
  38562. * like textures, attributes or render targets.
  38563. *
  38564. * @type {WeakMap}
  38565. */
  38566. this.data = new WeakMap();
  38567. /**
  38568. * A reference to the renderer.
  38569. *
  38570. * @type {?Renderer}
  38571. * @default null
  38572. */
  38573. this.renderer = null;
  38574. /**
  38575. * A reference to the canvas element the renderer is drawing to.
  38576. *
  38577. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  38578. * @default null
  38579. */
  38580. this.domElement = null;
  38581. /**
  38582. * A reference to the timestamp query pool.
  38583. *
  38584. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  38585. */
  38586. this.timestampQueryPool = {
  38587. 'render': null,
  38588. 'compute': null
  38589. };
  38590. }
  38591. /**
  38592. * Initializes the backend so it is ready for usage. Concrete backends
  38593. * are supposed to implement their rendering context creation and related
  38594. * operations in this method.
  38595. *
  38596. * @async
  38597. * @param {Renderer} renderer - The renderer.
  38598. * @return {Promise} A Promise that resolves when the backend has been initialized.
  38599. */
  38600. async init( renderer ) {
  38601. this.renderer = renderer;
  38602. }
  38603. /**
  38604. * The coordinate system of the backend.
  38605. *
  38606. * @abstract
  38607. * @type {number}
  38608. * @readonly
  38609. */
  38610. get coordinateSystem() {}
  38611. // render context
  38612. /**
  38613. * This method is executed at the beginning of a render call and
  38614. * can be used by the backend to prepare the state for upcoming
  38615. * draw calls.
  38616. *
  38617. * @abstract
  38618. * @param {RenderContext} renderContext - The render context.
  38619. */
  38620. beginRender( /*renderContext*/ ) {}
  38621. /**
  38622. * This method is executed at the end of a render call and
  38623. * can be used by the backend to finalize work after draw
  38624. * calls.
  38625. *
  38626. * @abstract
  38627. * @param {RenderContext} renderContext - The render context.
  38628. */
  38629. finishRender( /*renderContext*/ ) {}
  38630. /**
  38631. * This method is executed at the beginning of a compute call and
  38632. * can be used by the backend to prepare the state for upcoming
  38633. * compute tasks.
  38634. *
  38635. * @abstract
  38636. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38637. */
  38638. beginCompute( /*computeGroup*/ ) {}
  38639. /**
  38640. * This method is executed at the end of a compute call and
  38641. * can be used by the backend to finalize work after compute
  38642. * tasks.
  38643. *
  38644. * @abstract
  38645. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38646. */
  38647. finishCompute( /*computeGroup*/ ) {}
  38648. // render object
  38649. /**
  38650. * Executes a draw command for the given render object.
  38651. *
  38652. * @abstract
  38653. * @param {RenderObject} renderObject - The render object to draw.
  38654. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  38655. */
  38656. draw( /*renderObject, info*/ ) { }
  38657. // compute node
  38658. /**
  38659. * Executes a compute command for the given compute node.
  38660. *
  38661. * @abstract
  38662. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  38663. * @param {Node} computeNode - The compute node.
  38664. * @param {Array<BindGroup>} bindings - The bindings.
  38665. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38666. */
  38667. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  38668. // program
  38669. /**
  38670. * Creates a shader program from the given programmable stage.
  38671. *
  38672. * @abstract
  38673. * @param {ProgrammableStage} program - The programmable stage.
  38674. */
  38675. createProgram( /*program*/ ) { }
  38676. /**
  38677. * Destroys the shader program of the given programmable stage.
  38678. *
  38679. * @abstract
  38680. * @param {ProgrammableStage} program - The programmable stage.
  38681. */
  38682. destroyProgram( /*program*/ ) { }
  38683. // bindings
  38684. /**
  38685. * Creates bindings from the given bind group definition.
  38686. *
  38687. * @abstract
  38688. * @param {BindGroup} bindGroup - The bind group.
  38689. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38690. * @param {number} cacheIndex - The cache index.
  38691. * @param {number} version - The version.
  38692. */
  38693. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38694. /**
  38695. * Updates the given bind group definition.
  38696. *
  38697. * @abstract
  38698. * @param {BindGroup} bindGroup - The bind group.
  38699. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38700. * @param {number} cacheIndex - The cache index.
  38701. * @param {number} version - The version.
  38702. */
  38703. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38704. /**
  38705. * Updates a buffer binding.
  38706. *
  38707. * @abstract
  38708. * @param {Buffer} binding - The buffer binding to update.
  38709. */
  38710. updateBinding( /*binding*/ ) { }
  38711. // pipeline
  38712. /**
  38713. * Creates a render pipeline for the given render object.
  38714. *
  38715. * @abstract
  38716. * @param {RenderObject} renderObject - The render object.
  38717. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  38718. */
  38719. createRenderPipeline( /*renderObject, promises*/ ) { }
  38720. /**
  38721. * Creates a compute pipeline for the given compute node.
  38722. *
  38723. * @abstract
  38724. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38725. * @param {Array<BindGroup>} bindings - The bindings.
  38726. */
  38727. createComputePipeline( /*computePipeline, bindings*/ ) { }
  38728. // cache key
  38729. /**
  38730. * Returns `true` if the render pipeline requires an update.
  38731. *
  38732. * @abstract
  38733. * @param {RenderObject} renderObject - The render object.
  38734. * @return {boolean} Whether the render pipeline requires an update or not.
  38735. */
  38736. needsRenderUpdate( /*renderObject*/ ) { }
  38737. /**
  38738. * Returns a cache key that is used to identify render pipelines.
  38739. *
  38740. * @abstract
  38741. * @param {RenderObject} renderObject - The render object.
  38742. * @return {string} The cache key.
  38743. */
  38744. getRenderCacheKey( /*renderObject*/ ) { }
  38745. // node builder
  38746. /**
  38747. * Returns a node builder for the given render object.
  38748. *
  38749. * @abstract
  38750. * @param {RenderObject} renderObject - The render object.
  38751. * @param {Renderer} renderer - The renderer.
  38752. * @return {NodeBuilder} The node builder.
  38753. */
  38754. createNodeBuilder( /*renderObject, renderer*/ ) { }
  38755. // textures
  38756. /**
  38757. * Creates a GPU sampler for the given texture.
  38758. *
  38759. * @abstract
  38760. * @param {Texture} texture - The texture to create the sampler for.
  38761. */
  38762. createSampler( /*texture*/ ) { }
  38763. /**
  38764. * Destroys the GPU sampler for the given texture.
  38765. *
  38766. * @abstract
  38767. * @param {Texture} texture - The texture to destroy the sampler for.
  38768. */
  38769. destroySampler( /*texture*/ ) {}
  38770. /**
  38771. * Creates a default texture for the given texture that can be used
  38772. * as a placeholder until the actual texture is ready for usage.
  38773. *
  38774. * @abstract
  38775. * @param {Texture} texture - The texture to create a default texture for.
  38776. */
  38777. createDefaultTexture( /*texture*/ ) { }
  38778. /**
  38779. * Defines a texture on the GPU for the given texture object.
  38780. *
  38781. * @abstract
  38782. * @param {Texture} texture - The texture.
  38783. * @param {Object} [options={}] - Optional configuration parameter.
  38784. */
  38785. createTexture( /*texture, options={}*/ ) { }
  38786. /**
  38787. * Uploads the updated texture data to the GPU.
  38788. *
  38789. * @abstract
  38790. * @param {Texture} texture - The texture.
  38791. * @param {Object} [options={}] - Optional configuration parameter.
  38792. */
  38793. updateTexture( /*texture, options = {}*/ ) { }
  38794. /**
  38795. * Generates mipmaps for the given texture.
  38796. *
  38797. * @abstract
  38798. * @param {Texture} texture - The texture.
  38799. */
  38800. generateMipmaps( /*texture*/ ) { }
  38801. /**
  38802. * Destroys the GPU data for the given texture object.
  38803. *
  38804. * @abstract
  38805. * @param {Texture} texture - The texture.
  38806. */
  38807. destroyTexture( /*texture*/ ) { }
  38808. /**
  38809. * Returns texture data as a typed array.
  38810. *
  38811. * @abstract
  38812. * @async
  38813. * @param {Texture} texture - The texture to copy.
  38814. * @param {number} x - The x coordinate of the copy origin.
  38815. * @param {number} y - The y coordinate of the copy origin.
  38816. * @param {number} width - The width of the copy.
  38817. * @param {number} height - The height of the copy.
  38818. * @param {number} faceIndex - The face index.
  38819. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  38820. */
  38821. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  38822. /**
  38823. * Copies data of the given source texture to the given destination texture.
  38824. *
  38825. * @abstract
  38826. * @param {Texture} srcTexture - The source texture.
  38827. * @param {Texture} dstTexture - The destination texture.
  38828. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  38829. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  38830. * @param {number} [level=0] - The mip level to copy.
  38831. */
  38832. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  38833. /**
  38834. * Copies the current bound framebuffer to the given texture.
  38835. *
  38836. * @abstract
  38837. * @param {Texture} texture - The destination texture.
  38838. * @param {RenderContext} renderContext - The render context.
  38839. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  38840. */
  38841. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  38842. // attributes
  38843. /**
  38844. * Creates the GPU buffer of a shader attribute.
  38845. *
  38846. * @abstract
  38847. * @param {BufferAttribute} attribute - The buffer attribute.
  38848. */
  38849. createAttribute( /*attribute*/ ) { }
  38850. /**
  38851. * Creates the GPU buffer of an indexed shader attribute.
  38852. *
  38853. * @abstract
  38854. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  38855. */
  38856. createIndexAttribute( /*attribute*/ ) { }
  38857. /**
  38858. * Creates the GPU buffer of a storage attribute.
  38859. *
  38860. * @abstract
  38861. * @param {BufferAttribute} attribute - The buffer attribute.
  38862. */
  38863. createStorageAttribute( /*attribute*/ ) { }
  38864. /**
  38865. * Updates the GPU buffer of a shader attribute.
  38866. *
  38867. * @abstract
  38868. * @param {BufferAttribute} attribute - The buffer attribute to update.
  38869. */
  38870. updateAttribute( /*attribute*/ ) { }
  38871. /**
  38872. * Destroys the GPU buffer of a shader attribute.
  38873. *
  38874. * @abstract
  38875. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  38876. */
  38877. destroyAttribute( /*attribute*/ ) { }
  38878. // canvas
  38879. /**
  38880. * Returns the backend's rendering context.
  38881. *
  38882. * @abstract
  38883. * @return {Object} The rendering context.
  38884. */
  38885. getContext() { }
  38886. /**
  38887. * Backends can use this method if they have to run
  38888. * logic when the renderer gets resized.
  38889. *
  38890. * @abstract
  38891. */
  38892. updateSize() { }
  38893. /**
  38894. * Updates the viewport with the values from the given render context.
  38895. *
  38896. * @abstract
  38897. * @param {RenderContext} renderContext - The render context.
  38898. */
  38899. updateViewport( /*renderContext*/ ) {}
  38900. // utils
  38901. /**
  38902. * Returns `true` if the given 3D object is fully occluded by other
  38903. * 3D objects in the scene. Backends must implement this method by using
  38904. * a Occlusion Query API.
  38905. *
  38906. * @abstract
  38907. * @param {RenderContext} renderContext - The render context.
  38908. * @param {Object3D} object - The 3D object to test.
  38909. * @return {boolean} Whether the 3D object is fully occluded or not.
  38910. */
  38911. isOccluded( /*renderContext, object*/ ) {}
  38912. /**
  38913. * Resolves the time stamp for the given render context and type.
  38914. *
  38915. * @async
  38916. * @abstract
  38917. * @param {string} [type='render'] - The type of the time stamp.
  38918. * @return {Promise<number>} A Promise that resolves with the time stamp.
  38919. */
  38920. async resolveTimestampsAsync( type = 'render' ) {
  38921. if ( ! this.trackTimestamp ) {
  38922. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  38923. return;
  38924. }
  38925. const queryPool = this.timestampQueryPool[ type ];
  38926. if ( ! queryPool ) {
  38927. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  38928. return;
  38929. }
  38930. const duration = await queryPool.resolveQueriesAsync();
  38931. this.renderer.info[ type ].timestamp = duration;
  38932. return duration;
  38933. }
  38934. /**
  38935. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38936. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38937. *
  38938. * @async
  38939. * @abstract
  38940. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38941. */
  38942. async waitForGPU() {}
  38943. /**
  38944. * This method performs a readback operation by moving buffer data from
  38945. * a storage buffer attribute from the GPU to the CPU.
  38946. *
  38947. * @async
  38948. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38949. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38950. */
  38951. async getArrayBufferAsync( /* attribute */ ) {}
  38952. /**
  38953. * Checks if the given feature is supported by the backend.
  38954. *
  38955. * @async
  38956. * @abstract
  38957. * @param {string} name - The feature's name.
  38958. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38959. */
  38960. async hasFeatureAsync( /*name*/ ) { }
  38961. /**
  38962. * Checks if the given feature is supported by the backend.
  38963. *
  38964. * @abstract
  38965. * @param {string} name - The feature's name.
  38966. * @return {boolean} Whether the feature is supported or not.
  38967. */
  38968. hasFeature( /*name*/ ) {}
  38969. /**
  38970. * Returns the maximum anisotropy texture filtering value.
  38971. *
  38972. * @abstract
  38973. * @return {number} The maximum anisotropy texture filtering value.
  38974. */
  38975. getMaxAnisotropy() {}
  38976. /**
  38977. * Returns the drawing buffer size.
  38978. *
  38979. * @return {Vector2} The drawing buffer size.
  38980. */
  38981. getDrawingBufferSize() {
  38982. _vector2 = _vector2 || new Vector2();
  38983. return this.renderer.getDrawingBufferSize( _vector2 );
  38984. }
  38985. /**
  38986. * Defines the scissor test.
  38987. *
  38988. * @abstract
  38989. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  38990. */
  38991. setScissorTest( /*boolean*/ ) { }
  38992. /**
  38993. * Returns the clear color and alpha into a single
  38994. * color object.
  38995. *
  38996. * @return {Color4} The clear color.
  38997. */
  38998. getClearColor() {
  38999. const renderer = this.renderer;
  39000. _color4 = _color4 || new Color4();
  39001. renderer.getClearColor( _color4 );
  39002. _color4.getRGB( _color4 );
  39003. return _color4;
  39004. }
  39005. /**
  39006. * Returns the DOM element. If no DOM element exists, the backend
  39007. * creates a new one.
  39008. *
  39009. * @return {HTMLCanvasElement} The DOM element.
  39010. */
  39011. getDomElement() {
  39012. let domElement = this.domElement;
  39013. if ( domElement === null ) {
  39014. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39015. // OffscreenCanvas does not have setAttribute, see #22811
  39016. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39017. this.domElement = domElement;
  39018. }
  39019. return domElement;
  39020. }
  39021. /**
  39022. * Sets a dictionary for the given object into the
  39023. * internal data structure.
  39024. *
  39025. * @param {Object} object - The object.
  39026. * @param {Object} value - The dictionary to set.
  39027. */
  39028. set( object, value ) {
  39029. this.data.set( object, value );
  39030. }
  39031. /**
  39032. * Returns the dictionary for the given object.
  39033. *
  39034. * @param {Object} object - The object.
  39035. * @return {Object} The object's dictionary.
  39036. */
  39037. get( object ) {
  39038. let map = this.data.get( object );
  39039. if ( map === undefined ) {
  39040. map = {};
  39041. this.data.set( object, map );
  39042. }
  39043. return map;
  39044. }
  39045. /**
  39046. * Checks if the given object has a dictionary
  39047. * with data defined.
  39048. *
  39049. * @param {Object} object - The object.
  39050. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  39051. */
  39052. has( object ) {
  39053. return this.data.has( object );
  39054. }
  39055. /**
  39056. * Deletes an object from the internal data structure.
  39057. *
  39058. * @param {Object} object - The object to delete.
  39059. */
  39060. delete( object ) {
  39061. this.data.delete( object );
  39062. }
  39063. /**
  39064. * Frees internal resources.
  39065. *
  39066. * @abstract
  39067. */
  39068. dispose() { }
  39069. }
  39070. let _id$1 = 0;
  39071. /**
  39072. * This module is internally used in context of compute shaders.
  39073. * This type of shader is not natively supported in WebGL 2 and
  39074. * thus implemented via Transform Feedback. `DualAttributeData`
  39075. * manages the related data.
  39076. *
  39077. * @private
  39078. */
  39079. class DualAttributeData {
  39080. constructor( attributeData, dualBuffer ) {
  39081. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39082. this.type = attributeData.type;
  39083. this.bufferType = attributeData.bufferType;
  39084. this.pbo = attributeData.pbo;
  39085. this.byteLength = attributeData.byteLength;
  39086. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39087. this.version = attributeData.version;
  39088. this.isInteger = attributeData.isInteger;
  39089. this.activeBufferIndex = 0;
  39090. this.baseId = attributeData.id;
  39091. }
  39092. get id() {
  39093. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39094. }
  39095. get bufferGPU() {
  39096. return this.buffers[ this.activeBufferIndex ];
  39097. }
  39098. get transformBuffer() {
  39099. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39100. }
  39101. switchBuffers() {
  39102. this.activeBufferIndex ^= 1;
  39103. }
  39104. }
  39105. /**
  39106. * A WebGL 2 backend utility module for managing shader attributes.
  39107. *
  39108. * @private
  39109. */
  39110. class WebGLAttributeUtils {
  39111. /**
  39112. * Constructs a new utility object.
  39113. *
  39114. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39115. */
  39116. constructor( backend ) {
  39117. /**
  39118. * A reference to the WebGL 2 backend.
  39119. *
  39120. * @type {WebGLBackend}
  39121. */
  39122. this.backend = backend;
  39123. }
  39124. /**
  39125. * Creates the GPU buffer for the given buffer attribute.
  39126. *
  39127. * @param {BufferAttribute} attribute - The buffer attribute.
  39128. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39129. */
  39130. createAttribute( attribute, bufferType ) {
  39131. const backend = this.backend;
  39132. const { gl } = backend;
  39133. const array = attribute.array;
  39134. const usage = attribute.usage || gl.STATIC_DRAW;
  39135. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39136. const bufferData = backend.get( bufferAttribute );
  39137. let bufferGPU = bufferData.bufferGPU;
  39138. if ( bufferGPU === undefined ) {
  39139. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39140. bufferData.bufferGPU = bufferGPU;
  39141. bufferData.bufferType = bufferType;
  39142. bufferData.version = bufferAttribute.version;
  39143. }
  39144. //attribute.onUploadCallback();
  39145. let type;
  39146. if ( array instanceof Float32Array ) {
  39147. type = gl.FLOAT;
  39148. } else if ( array instanceof Uint16Array ) {
  39149. if ( attribute.isFloat16BufferAttribute ) {
  39150. type = gl.HALF_FLOAT;
  39151. } else {
  39152. type = gl.UNSIGNED_SHORT;
  39153. }
  39154. } else if ( array instanceof Int16Array ) {
  39155. type = gl.SHORT;
  39156. } else if ( array instanceof Uint32Array ) {
  39157. type = gl.UNSIGNED_INT;
  39158. } else if ( array instanceof Int32Array ) {
  39159. type = gl.INT;
  39160. } else if ( array instanceof Int8Array ) {
  39161. type = gl.BYTE;
  39162. } else if ( array instanceof Uint8Array ) {
  39163. type = gl.UNSIGNED_BYTE;
  39164. } else if ( array instanceof Uint8ClampedArray ) {
  39165. type = gl.UNSIGNED_BYTE;
  39166. } else {
  39167. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39168. }
  39169. let attributeData = {
  39170. bufferGPU,
  39171. bufferType,
  39172. type,
  39173. byteLength: array.byteLength,
  39174. bytesPerElement: array.BYTES_PER_ELEMENT,
  39175. version: attribute.version,
  39176. pbo: attribute.pbo,
  39177. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39178. id: _id$1 ++
  39179. };
  39180. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39181. // create buffer for transform feedback use
  39182. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39183. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39184. }
  39185. backend.set( attribute, attributeData );
  39186. }
  39187. /**
  39188. * Updates the GPU buffer of the given buffer attribute.
  39189. *
  39190. * @param {BufferAttribute} attribute - The buffer attribute.
  39191. */
  39192. updateAttribute( attribute ) {
  39193. const backend = this.backend;
  39194. const { gl } = backend;
  39195. const array = attribute.array;
  39196. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39197. const bufferData = backend.get( bufferAttribute );
  39198. const bufferType = bufferData.bufferType;
  39199. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39200. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39201. if ( updateRanges.length === 0 ) {
  39202. // Not using update ranges
  39203. gl.bufferSubData( bufferType, 0, array );
  39204. } else {
  39205. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39206. const range = updateRanges[ i ];
  39207. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39208. array, range.start, range.count );
  39209. }
  39210. bufferAttribute.clearUpdateRanges();
  39211. }
  39212. gl.bindBuffer( bufferType, null );
  39213. bufferData.version = bufferAttribute.version;
  39214. }
  39215. /**
  39216. * Destroys the GPU buffer of the given buffer attribute.
  39217. *
  39218. * @param {BufferAttribute} attribute - The buffer attribute.
  39219. */
  39220. destroyAttribute( attribute ) {
  39221. const backend = this.backend;
  39222. const { gl } = backend;
  39223. if ( attribute.isInterleavedBufferAttribute ) {
  39224. backend.delete( attribute.data );
  39225. }
  39226. const attributeData = backend.get( attribute );
  39227. gl.deleteBuffer( attributeData.bufferGPU );
  39228. backend.delete( attribute );
  39229. }
  39230. /**
  39231. * This method performs a readback operation by moving buffer data from
  39232. * a storage buffer attribute from the GPU to the CPU.
  39233. *
  39234. * @async
  39235. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39236. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39237. */
  39238. async getArrayBufferAsync( attribute ) {
  39239. const backend = this.backend;
  39240. const { gl } = backend;
  39241. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39242. const { bufferGPU } = backend.get( bufferAttribute );
  39243. const array = attribute.array;
  39244. const byteLength = array.byteLength;
  39245. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39246. const writeBuffer = gl.createBuffer();
  39247. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39248. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39249. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39250. await backend.utils._clientWaitAsync();
  39251. const dstBuffer = new attribute.array.constructor( array.length );
  39252. // Ensure the buffer is bound before reading
  39253. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39254. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39255. gl.deleteBuffer( writeBuffer );
  39256. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39257. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39258. return dstBuffer.buffer;
  39259. }
  39260. /**
  39261. * Creates a WebGL buffer with the given data.
  39262. *
  39263. * @private
  39264. * @param {WebGL2RenderingContext} gl - The rendering context.
  39265. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39266. * @param {TypedArray} array - The array of the buffer attribute.
  39267. * @param {GLenum} usage - The usage.
  39268. * @return {WebGLBuffer} The WebGL buffer.
  39269. */
  39270. _createBuffer( gl, bufferType, array, usage ) {
  39271. const bufferGPU = gl.createBuffer();
  39272. gl.bindBuffer( bufferType, bufferGPU );
  39273. gl.bufferData( bufferType, array, usage );
  39274. gl.bindBuffer( bufferType, null );
  39275. return bufferGPU;
  39276. }
  39277. }
  39278. let equationToGL, factorToGL;
  39279. /**
  39280. * A WebGL 2 backend utility module for managing the WebGL state.
  39281. *
  39282. * The major goal of this module is to reduce the number of state changes
  39283. * by caching the WEbGL state with a series of variables. In this way, the
  39284. * renderer only executes state change commands when necessary which
  39285. * improves the overall performance.
  39286. *
  39287. * @private
  39288. */
  39289. class WebGLState {
  39290. /**
  39291. * Constructs a new utility object.
  39292. *
  39293. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39294. */
  39295. constructor( backend ) {
  39296. /**
  39297. * A reference to the WebGL 2 backend.
  39298. *
  39299. * @type {WebGLBackend}
  39300. */
  39301. this.backend = backend;
  39302. /**
  39303. * A reference to the rendering context.
  39304. *
  39305. * @type {WebGL2RenderingContext}
  39306. */
  39307. this.gl = this.backend.gl;
  39308. // Below properties are intended to cache
  39309. // the WebGL state and are not explicitly
  39310. // documented for convenience reasons.
  39311. this.enabled = {};
  39312. this.currentFlipSided = null;
  39313. this.currentCullFace = null;
  39314. this.currentProgram = null;
  39315. this.currentBlendingEnabled = false;
  39316. this.currentBlending = null;
  39317. this.currentBlendSrc = null;
  39318. this.currentBlendDst = null;
  39319. this.currentBlendSrcAlpha = null;
  39320. this.currentBlendDstAlpha = null;
  39321. this.currentPremultipledAlpha = null;
  39322. this.currentPolygonOffsetFactor = null;
  39323. this.currentPolygonOffsetUnits = null;
  39324. this.currentColorMask = null;
  39325. this.currentDepthFunc = null;
  39326. this.currentDepthMask = null;
  39327. this.currentStencilFunc = null;
  39328. this.currentStencilRef = null;
  39329. this.currentStencilFuncMask = null;
  39330. this.currentStencilFail = null;
  39331. this.currentStencilZFail = null;
  39332. this.currentStencilZPass = null;
  39333. this.currentStencilMask = null;
  39334. this.currentLineWidth = null;
  39335. this.currentClippingPlanes = 0;
  39336. this.currentBoundFramebuffers = {};
  39337. this.currentDrawbuffers = new WeakMap();
  39338. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39339. this.currentTextureSlot = null;
  39340. this.currentBoundTextures = {};
  39341. this.currentBoundBufferBases = {};
  39342. this._init();
  39343. }
  39344. /**
  39345. * Inits the state of the utility.
  39346. *
  39347. * @private
  39348. */
  39349. _init() {
  39350. const gl = this.gl;
  39351. // Store only WebGL constants here.
  39352. equationToGL = {
  39353. [ AddEquation ]: gl.FUNC_ADD,
  39354. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39355. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39356. };
  39357. factorToGL = {
  39358. [ ZeroFactor ]: gl.ZERO,
  39359. [ OneFactor ]: gl.ONE,
  39360. [ SrcColorFactor ]: gl.SRC_COLOR,
  39361. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39362. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39363. [ DstColorFactor ]: gl.DST_COLOR,
  39364. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39365. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39366. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39367. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39368. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39369. };
  39370. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  39371. const viewportParam = gl.getParameter( gl.VIEWPORT );
  39372. this.currentScissor = new Vector4().fromArray( scissorParam );
  39373. this.currentViewport = new Vector4().fromArray( viewportParam );
  39374. this._tempVec4 = new Vector4();
  39375. }
  39376. /**
  39377. * Enables the given WebGL capability.
  39378. *
  39379. * This method caches the capability state so
  39380. * `gl.enable()` is only called when necessary.
  39381. *
  39382. * @param {GLenum} id - The capability to enable.
  39383. */
  39384. enable( id ) {
  39385. const { enabled } = this;
  39386. if ( enabled[ id ] !== true ) {
  39387. this.gl.enable( id );
  39388. enabled[ id ] = true;
  39389. }
  39390. }
  39391. /**
  39392. * Disables the given WebGL capability.
  39393. *
  39394. * This method caches the capability state so
  39395. * `gl.disable()` is only called when necessary.
  39396. *
  39397. * @param {GLenum} id - The capability to enable.
  39398. */
  39399. disable( id ) {
  39400. const { enabled } = this;
  39401. if ( enabled[ id ] !== false ) {
  39402. this.gl.disable( id );
  39403. enabled[ id ] = false;
  39404. }
  39405. }
  39406. /**
  39407. * Specifies whether polygons are front- or back-facing
  39408. * by setting the winding orientation.
  39409. *
  39410. * This method caches the state so `gl.frontFace()` is only
  39411. * called when necessary.
  39412. *
  39413. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  39414. */
  39415. setFlipSided( flipSided ) {
  39416. if ( this.currentFlipSided !== flipSided ) {
  39417. const { gl } = this;
  39418. if ( flipSided ) {
  39419. gl.frontFace( gl.CW );
  39420. } else {
  39421. gl.frontFace( gl.CCW );
  39422. }
  39423. this.currentFlipSided = flipSided;
  39424. }
  39425. }
  39426. /**
  39427. * Specifies whether or not front- and/or back-facing
  39428. * polygons can be culled.
  39429. *
  39430. * This method caches the state so `gl.cullFace()` is only
  39431. * called when necessary.
  39432. *
  39433. * @param {number} cullFace - Defines which polygons are candidates for culling.
  39434. */
  39435. setCullFace( cullFace ) {
  39436. const { gl } = this;
  39437. if ( cullFace !== CullFaceNone ) {
  39438. this.enable( gl.CULL_FACE );
  39439. if ( cullFace !== this.currentCullFace ) {
  39440. if ( cullFace === CullFaceBack ) {
  39441. gl.cullFace( gl.BACK );
  39442. } else if ( cullFace === CullFaceFront ) {
  39443. gl.cullFace( gl.FRONT );
  39444. } else {
  39445. gl.cullFace( gl.FRONT_AND_BACK );
  39446. }
  39447. }
  39448. } else {
  39449. this.disable( gl.CULL_FACE );
  39450. }
  39451. this.currentCullFace = cullFace;
  39452. }
  39453. /**
  39454. * Specifies the width of line primitives.
  39455. *
  39456. * This method caches the state so `gl.lineWidth()` is only
  39457. * called when necessary.
  39458. *
  39459. * @param {number} width - The line width.
  39460. */
  39461. setLineWidth( width ) {
  39462. const { currentLineWidth, gl } = this;
  39463. if ( width !== currentLineWidth ) {
  39464. gl.lineWidth( width );
  39465. this.currentLineWidth = width;
  39466. }
  39467. }
  39468. /**
  39469. * Defines the blending.
  39470. *
  39471. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  39472. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  39473. *
  39474. * @param {number} blending - The blending type.
  39475. * @param {number} blendEquation - The blending equation.
  39476. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  39477. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  39478. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  39479. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  39480. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  39481. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  39482. */
  39483. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39484. const { gl } = this;
  39485. if ( blending === NoBlending ) {
  39486. if ( this.currentBlendingEnabled === true ) {
  39487. this.disable( gl.BLEND );
  39488. this.currentBlendingEnabled = false;
  39489. }
  39490. return;
  39491. }
  39492. if ( this.currentBlendingEnabled === false ) {
  39493. this.enable( gl.BLEND );
  39494. this.currentBlendingEnabled = true;
  39495. }
  39496. if ( blending !== CustomBlending ) {
  39497. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39498. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39499. gl.blendEquation( gl.FUNC_ADD );
  39500. this.currentBlendEquation = AddEquation;
  39501. this.currentBlendEquationAlpha = AddEquation;
  39502. }
  39503. if ( premultipliedAlpha ) {
  39504. switch ( blending ) {
  39505. case NormalBlending:
  39506. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39507. break;
  39508. case AdditiveBlending:
  39509. gl.blendFunc( gl.ONE, gl.ONE );
  39510. break;
  39511. case SubtractiveBlending:
  39512. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39513. break;
  39514. case MultiplyBlending:
  39515. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39516. break;
  39517. default:
  39518. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39519. break;
  39520. }
  39521. } else {
  39522. switch ( blending ) {
  39523. case NormalBlending:
  39524. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39525. break;
  39526. case AdditiveBlending:
  39527. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39528. break;
  39529. case SubtractiveBlending:
  39530. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39531. break;
  39532. case MultiplyBlending:
  39533. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39534. break;
  39535. default:
  39536. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39537. break;
  39538. }
  39539. }
  39540. this.currentBlendSrc = null;
  39541. this.currentBlendDst = null;
  39542. this.currentBlendSrcAlpha = null;
  39543. this.currentBlendDstAlpha = null;
  39544. this.currentBlending = blending;
  39545. this.currentPremultipledAlpha = premultipliedAlpha;
  39546. }
  39547. return;
  39548. }
  39549. // custom blending
  39550. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39551. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39552. blendDstAlpha = blendDstAlpha || blendDst;
  39553. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39554. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39555. this.currentBlendEquation = blendEquation;
  39556. this.currentBlendEquationAlpha = blendEquationAlpha;
  39557. }
  39558. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39559. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39560. this.currentBlendSrc = blendSrc;
  39561. this.currentBlendDst = blendDst;
  39562. this.currentBlendSrcAlpha = blendSrcAlpha;
  39563. this.currentBlendDstAlpha = blendDstAlpha;
  39564. }
  39565. this.currentBlending = blending;
  39566. this.currentPremultipledAlpha = false;
  39567. }
  39568. /**
  39569. * Specifies whether colors can be written when rendering
  39570. * into a framebuffer or not.
  39571. *
  39572. * This method caches the state so `gl.colorMask()` is only
  39573. * called when necessary.
  39574. *
  39575. * @param {boolean} colorMask - The color mask.
  39576. */
  39577. setColorMask( colorMask ) {
  39578. if ( this.currentColorMask !== colorMask ) {
  39579. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39580. this.currentColorMask = colorMask;
  39581. }
  39582. }
  39583. /**
  39584. * Specifies whether the depth test is enabled or not.
  39585. *
  39586. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  39587. */
  39588. setDepthTest( depthTest ) {
  39589. const { gl } = this;
  39590. if ( depthTest ) {
  39591. this.enable( gl.DEPTH_TEST );
  39592. } else {
  39593. this.disable( gl.DEPTH_TEST );
  39594. }
  39595. }
  39596. /**
  39597. * Specifies whether depth values can be written when rendering
  39598. * into a framebuffer or not.
  39599. *
  39600. * This method caches the state so `gl.depthMask()` is only
  39601. * called when necessary.
  39602. *
  39603. * @param {boolean} depthMask - The depth mask.
  39604. */
  39605. setDepthMask( depthMask ) {
  39606. if ( this.currentDepthMask !== depthMask ) {
  39607. this.gl.depthMask( depthMask );
  39608. this.currentDepthMask = depthMask;
  39609. }
  39610. }
  39611. /**
  39612. * Specifies the depth compare function.
  39613. *
  39614. * This method caches the state so `gl.depthFunc()` is only
  39615. * called when necessary.
  39616. *
  39617. * @param {number} depthFunc - The depth compare function.
  39618. */
  39619. setDepthFunc( depthFunc ) {
  39620. if ( this.currentDepthFunc !== depthFunc ) {
  39621. const { gl } = this;
  39622. switch ( depthFunc ) {
  39623. case NeverDepth:
  39624. gl.depthFunc( gl.NEVER );
  39625. break;
  39626. case AlwaysDepth:
  39627. gl.depthFunc( gl.ALWAYS );
  39628. break;
  39629. case LessDepth:
  39630. gl.depthFunc( gl.LESS );
  39631. break;
  39632. case LessEqualDepth:
  39633. gl.depthFunc( gl.LEQUAL );
  39634. break;
  39635. case EqualDepth:
  39636. gl.depthFunc( gl.EQUAL );
  39637. break;
  39638. case GreaterEqualDepth:
  39639. gl.depthFunc( gl.GEQUAL );
  39640. break;
  39641. case GreaterDepth:
  39642. gl.depthFunc( gl.GREATER );
  39643. break;
  39644. case NotEqualDepth:
  39645. gl.depthFunc( gl.NOTEQUAL );
  39646. break;
  39647. default:
  39648. gl.depthFunc( gl.LEQUAL );
  39649. }
  39650. this.currentDepthFunc = depthFunc;
  39651. }
  39652. }
  39653. /**
  39654. * Specifies the scissor box.
  39655. *
  39656. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  39657. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  39658. * @param {number} width - The width of the viewport.
  39659. * @param {number} height - The height of the viewport.
  39660. *
  39661. */
  39662. scissor( x, y, width, height ) {
  39663. const scissor = this._tempVec4.set( x, y, width, height );
  39664. if ( this.currentScissor.equals( scissor ) === false ) {
  39665. const { gl } = this;
  39666. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  39667. this.currentScissor.copy( scissor );
  39668. }
  39669. }
  39670. /**
  39671. * Specifies the viewport.
  39672. *
  39673. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  39674. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  39675. * @param {number} width - The width of the viewport.
  39676. * @param {number} height - The height of the viewport.
  39677. *
  39678. */
  39679. viewport( x, y, width, height ) {
  39680. const viewport = this._tempVec4.set( x, y, width, height );
  39681. if ( this.currentViewport.equals( viewport ) === false ) {
  39682. const { gl } = this;
  39683. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  39684. this.currentViewport.copy( viewport );
  39685. }
  39686. }
  39687. /**
  39688. * Defines the scissor test.
  39689. *
  39690. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39691. */
  39692. setScissorTest( boolean ) {
  39693. const gl = this.gl;
  39694. if ( boolean ) {
  39695. gl.enable( gl.SCISSOR_TEST );
  39696. } else {
  39697. gl.disable( gl.SCISSOR_TEST );
  39698. }
  39699. }
  39700. /**
  39701. * Specifies whether the stencil test is enabled or not.
  39702. *
  39703. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  39704. */
  39705. setStencilTest( stencilTest ) {
  39706. const { gl } = this;
  39707. if ( stencilTest ) {
  39708. this.enable( gl.STENCIL_TEST );
  39709. } else {
  39710. this.disable( gl.STENCIL_TEST );
  39711. }
  39712. }
  39713. /**
  39714. * Specifies whether stencil values can be written when rendering
  39715. * into a framebuffer or not.
  39716. *
  39717. * This method caches the state so `gl.stencilMask()` is only
  39718. * called when necessary.
  39719. *
  39720. * @param {boolean} stencilMask - The stencil mask.
  39721. */
  39722. setStencilMask( stencilMask ) {
  39723. if ( this.currentStencilMask !== stencilMask ) {
  39724. this.gl.stencilMask( stencilMask );
  39725. this.currentStencilMask = stencilMask;
  39726. }
  39727. }
  39728. /**
  39729. * Specifies whether the stencil test functions.
  39730. *
  39731. * This method caches the state so `gl.stencilFunc()` is only
  39732. * called when necessary.
  39733. *
  39734. * @param {number} stencilFunc - The stencil compare function.
  39735. * @param {number} stencilRef - The reference value for the stencil test.
  39736. * @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.
  39737. */
  39738. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39739. if ( this.currentStencilFunc !== stencilFunc ||
  39740. this.currentStencilRef !== stencilRef ||
  39741. this.currentStencilFuncMask !== stencilMask ) {
  39742. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39743. this.currentStencilFunc = stencilFunc;
  39744. this.currentStencilRef = stencilRef;
  39745. this.currentStencilFuncMask = stencilMask;
  39746. }
  39747. }
  39748. /**
  39749. * Specifies whether the stencil test operation.
  39750. *
  39751. * This method caches the state so `gl.stencilOp()` is only
  39752. * called when necessary.
  39753. *
  39754. * @param {number} stencilFail - The function to use when the stencil test fails.
  39755. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  39756. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  39757. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  39758. */
  39759. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39760. if ( this.currentStencilFail !== stencilFail ||
  39761. this.currentStencilZFail !== stencilZFail ||
  39762. this.currentStencilZPass !== stencilZPass ) {
  39763. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39764. this.currentStencilFail = stencilFail;
  39765. this.currentStencilZFail = stencilZFail;
  39766. this.currentStencilZPass = stencilZPass;
  39767. }
  39768. }
  39769. /**
  39770. * Configures the WebGL state for the given material.
  39771. *
  39772. * @param {Material} material - The material to configure the state for.
  39773. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  39774. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  39775. */
  39776. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  39777. const { gl } = this;
  39778. material.side === DoubleSide
  39779. ? this.disable( gl.CULL_FACE )
  39780. : this.enable( gl.CULL_FACE );
  39781. let flipSided = ( material.side === BackSide );
  39782. if ( frontFaceCW ) flipSided = ! flipSided;
  39783. this.setFlipSided( flipSided );
  39784. ( material.blending === NormalBlending && material.transparent === false )
  39785. ? this.setBlending( NoBlending )
  39786. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39787. this.setDepthFunc( material.depthFunc );
  39788. this.setDepthTest( material.depthTest );
  39789. this.setDepthMask( material.depthWrite );
  39790. this.setColorMask( material.colorWrite );
  39791. const stencilWrite = material.stencilWrite;
  39792. this.setStencilTest( stencilWrite );
  39793. if ( stencilWrite ) {
  39794. this.setStencilMask( material.stencilWriteMask );
  39795. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39796. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39797. }
  39798. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39799. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39800. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39801. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39802. if ( hardwareClippingPlanes > 0 ) {
  39803. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  39804. const CLIP_DISTANCE0_WEBGL = 0x3000;
  39805. for ( let i = 0; i < 8; i ++ ) {
  39806. if ( i < hardwareClippingPlanes ) {
  39807. this.enable( CLIP_DISTANCE0_WEBGL + i );
  39808. } else {
  39809. this.disable( CLIP_DISTANCE0_WEBGL + i );
  39810. }
  39811. }
  39812. }
  39813. }
  39814. }
  39815. /**
  39816. * Specifies the polygon offset.
  39817. *
  39818. * This method caches the state so `gl.polygonOffset()` is only
  39819. * called when necessary.
  39820. *
  39821. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  39822. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  39823. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  39824. */
  39825. setPolygonOffset( polygonOffset, factor, units ) {
  39826. const { gl } = this;
  39827. if ( polygonOffset ) {
  39828. this.enable( gl.POLYGON_OFFSET_FILL );
  39829. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39830. gl.polygonOffset( factor, units );
  39831. this.currentPolygonOffsetFactor = factor;
  39832. this.currentPolygonOffsetUnits = units;
  39833. }
  39834. } else {
  39835. this.disable( gl.POLYGON_OFFSET_FILL );
  39836. }
  39837. }
  39838. /**
  39839. * Defines the usage of the given WebGL program.
  39840. *
  39841. * This method caches the state so `gl.useProgram()` is only
  39842. * called when necessary.
  39843. *
  39844. * @param {WebGLProgram} program - The WebGL program to use.
  39845. * @return {boolean} Whether a program change has been executed or not.
  39846. */
  39847. useProgram( program ) {
  39848. if ( this.currentProgram !== program ) {
  39849. this.gl.useProgram( program );
  39850. this.currentProgram = program;
  39851. return true;
  39852. }
  39853. return false;
  39854. }
  39855. // framebuffer
  39856. /**
  39857. * Binds the given framebuffer.
  39858. *
  39859. * This method caches the state so `gl.bindFramebuffer()` is only
  39860. * called when necessary.
  39861. *
  39862. * @param {number} target - The binding point (target).
  39863. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  39864. * @return {boolean} Whether a bind has been executed or not.
  39865. */
  39866. bindFramebuffer( target, framebuffer ) {
  39867. const { gl, currentBoundFramebuffers } = this;
  39868. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39869. gl.bindFramebuffer( target, framebuffer );
  39870. currentBoundFramebuffers[ target ] = framebuffer;
  39871. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39872. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39873. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39874. }
  39875. if ( target === gl.FRAMEBUFFER ) {
  39876. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39877. }
  39878. return true;
  39879. }
  39880. return false;
  39881. }
  39882. /**
  39883. * Defines draw buffers to which fragment colors are written into.
  39884. * Configures the MRT setup of custom framebuffers.
  39885. *
  39886. * This method caches the state so `gl.drawBuffers()` is only
  39887. * called when necessary.
  39888. *
  39889. * @param {RenderContext} renderContext - The render context.
  39890. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  39891. */
  39892. drawBuffers( renderContext, framebuffer ) {
  39893. const { gl } = this;
  39894. let drawBuffers = [];
  39895. let needsUpdate = false;
  39896. if ( renderContext.textures !== null ) {
  39897. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39898. if ( drawBuffers === undefined ) {
  39899. drawBuffers = [];
  39900. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39901. }
  39902. const textures = renderContext.textures;
  39903. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39904. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39905. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39906. }
  39907. drawBuffers.length = textures.length;
  39908. needsUpdate = true;
  39909. }
  39910. } else {
  39911. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39912. drawBuffers[ 0 ] = gl.BACK;
  39913. needsUpdate = true;
  39914. }
  39915. }
  39916. if ( needsUpdate ) {
  39917. gl.drawBuffers( drawBuffers );
  39918. }
  39919. }
  39920. // texture
  39921. /**
  39922. * Makes the given texture unit active.
  39923. *
  39924. * This method caches the state so `gl.activeTexture()` is only
  39925. * called when necessary.
  39926. *
  39927. * @param {number} webglSlot - The texture unit to make active.
  39928. */
  39929. activeTexture( webglSlot ) {
  39930. const { gl, currentTextureSlot, maxTextures } = this;
  39931. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39932. if ( currentTextureSlot !== webglSlot ) {
  39933. gl.activeTexture( webglSlot );
  39934. this.currentTextureSlot = webglSlot;
  39935. }
  39936. }
  39937. /**
  39938. * Binds the given WebGL texture to a target.
  39939. *
  39940. * This method caches the state so `gl.bindTexture()` is only
  39941. * called when necessary.
  39942. *
  39943. * @param {number} webglType - The binding point (target).
  39944. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  39945. * @param {number} webglSlot - The texture.
  39946. */
  39947. bindTexture( webglType, webglTexture, webglSlot ) {
  39948. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39949. if ( webglSlot === undefined ) {
  39950. if ( currentTextureSlot === null ) {
  39951. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39952. } else {
  39953. webglSlot = currentTextureSlot;
  39954. }
  39955. }
  39956. let boundTexture = currentBoundTextures[ webglSlot ];
  39957. if ( boundTexture === undefined ) {
  39958. boundTexture = { type: undefined, texture: undefined };
  39959. currentBoundTextures[ webglSlot ] = boundTexture;
  39960. }
  39961. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39962. if ( currentTextureSlot !== webglSlot ) {
  39963. gl.activeTexture( webglSlot );
  39964. this.currentTextureSlot = webglSlot;
  39965. }
  39966. gl.bindTexture( webglType, webglTexture );
  39967. boundTexture.type = webglType;
  39968. boundTexture.texture = webglTexture;
  39969. }
  39970. }
  39971. /**
  39972. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  39973. *
  39974. * This method caches the state so `gl.bindBufferBase()` is only
  39975. * called when necessary.
  39976. *
  39977. * @param {number} target - The target for the bind operation.
  39978. * @param {number} index - The index of the target.
  39979. * @param {WebGLBuffer} buffer - The WebGL buffer.
  39980. * @return {boolean} Whether a bind has been executed or not.
  39981. */
  39982. bindBufferBase( target, index, buffer ) {
  39983. const { gl } = this;
  39984. const key = `${target}-${index}`;
  39985. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39986. gl.bindBufferBase( target, index, buffer );
  39987. this.currentBoundBufferBases[ key ] = buffer;
  39988. return true;
  39989. }
  39990. return false;
  39991. }
  39992. /**
  39993. * Unbinds the current bound texture.
  39994. *
  39995. * This method caches the state so `gl.bindTexture()` is only
  39996. * called when necessary.
  39997. */
  39998. unbindTexture() {
  39999. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40000. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40001. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40002. gl.bindTexture( boundTexture.type, null );
  40003. boundTexture.type = undefined;
  40004. boundTexture.texture = undefined;
  40005. }
  40006. }
  40007. }
  40008. /**
  40009. * A WebGL 2 backend utility module with common helpers.
  40010. *
  40011. * @private
  40012. */
  40013. class WebGLUtils {
  40014. /**
  40015. * Constructs a new utility object.
  40016. *
  40017. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40018. */
  40019. constructor( backend ) {
  40020. /**
  40021. * A reference to the WebGL 2 backend.
  40022. *
  40023. * @type {WebGLBackend}
  40024. */
  40025. this.backend = backend;
  40026. /**
  40027. * A reference to the rendering context.
  40028. *
  40029. * @type {WebGL2RenderingContext}
  40030. */
  40031. this.gl = this.backend.gl;
  40032. /**
  40033. * A reference to a backend module holding extension-related
  40034. * utility functions.
  40035. *
  40036. * @type {WebGLExtensions}
  40037. */
  40038. this.extensions = backend.extensions;
  40039. }
  40040. /**
  40041. * Converts the given three.js constant into a WebGL constant.
  40042. * The method currently supports the conversion of texture formats
  40043. * and types.
  40044. *
  40045. * @param {number} p - The three.js constant.
  40046. * @param {string} [colorSpace=NoColorSpace] - The color space.
  40047. * @return {number} The corresponding WebGL constant.
  40048. */
  40049. convert( p, colorSpace = NoColorSpace ) {
  40050. const { gl, extensions } = this;
  40051. let extension;
  40052. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40053. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40054. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40055. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40056. if ( p === ByteType ) return gl.BYTE;
  40057. if ( p === ShortType ) return gl.SHORT;
  40058. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40059. if ( p === IntType ) return gl.INT;
  40060. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40061. if ( p === FloatType ) return gl.FLOAT;
  40062. if ( p === HalfFloatType ) {
  40063. return gl.HALF_FLOAT;
  40064. }
  40065. if ( p === AlphaFormat ) return gl.ALPHA;
  40066. if ( p === RGBFormat ) return gl.RGB;
  40067. if ( p === RGBAFormat ) return gl.RGBA;
  40068. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40069. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40070. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40071. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40072. // WebGL2 formats.
  40073. if ( p === RedFormat ) return gl.RED;
  40074. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40075. if ( p === RGFormat ) return gl.RG;
  40076. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40077. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40078. // S3TC
  40079. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40080. if ( colorSpace === SRGBColorSpace ) {
  40081. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40082. if ( extension !== null ) {
  40083. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40084. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40085. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40086. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40087. } else {
  40088. return null;
  40089. }
  40090. } else {
  40091. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40092. if ( extension !== null ) {
  40093. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40094. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40095. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40096. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40097. } else {
  40098. return null;
  40099. }
  40100. }
  40101. }
  40102. // PVRTC
  40103. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40104. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40105. if ( extension !== null ) {
  40106. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40107. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40108. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40109. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40110. } else {
  40111. return null;
  40112. }
  40113. }
  40114. // ETC
  40115. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40116. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40117. if ( extension !== null ) {
  40118. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40119. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40120. } else {
  40121. return null;
  40122. }
  40123. }
  40124. // ASTC
  40125. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40126. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40127. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40128. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40129. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40130. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40131. if ( extension !== null ) {
  40132. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40133. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40134. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40135. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40136. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40137. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40138. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40139. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40140. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40141. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40142. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40143. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40144. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40145. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40146. } else {
  40147. return null;
  40148. }
  40149. }
  40150. // BPTC
  40151. if ( p === RGBA_BPTC_Format ) {
  40152. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40153. if ( extension !== null ) {
  40154. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40155. } else {
  40156. return null;
  40157. }
  40158. }
  40159. // RGTC
  40160. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40161. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40162. if ( extension !== null ) {
  40163. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40164. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40165. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40166. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40167. } else {
  40168. return null;
  40169. }
  40170. }
  40171. //
  40172. if ( p === UnsignedInt248Type ) {
  40173. return gl.UNSIGNED_INT_24_8;
  40174. }
  40175. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40176. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40177. }
  40178. /**
  40179. * This method can be used to synchronize the CPU with the GPU by waiting until
  40180. * ongoing GPU commands have been completed.
  40181. *
  40182. * @private
  40183. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  40184. */
  40185. _clientWaitAsync() {
  40186. const { gl } = this;
  40187. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40188. gl.flush();
  40189. return new Promise( ( resolve, reject ) => {
  40190. function test() {
  40191. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40192. if ( res === gl.WAIT_FAILED ) {
  40193. gl.deleteSync( sync );
  40194. reject();
  40195. return;
  40196. }
  40197. if ( res === gl.TIMEOUT_EXPIRED ) {
  40198. requestAnimationFrame( test );
  40199. return;
  40200. }
  40201. gl.deleteSync( sync );
  40202. resolve();
  40203. }
  40204. test();
  40205. } );
  40206. }
  40207. }
  40208. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40209. /**
  40210. * A WebGL 2 backend utility module for managing textures.
  40211. *
  40212. * @private
  40213. */
  40214. class WebGLTextureUtils {
  40215. /**
  40216. * Constructs a new utility object.
  40217. *
  40218. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40219. */
  40220. constructor( backend ) {
  40221. /**
  40222. * A reference to the WebGL 2 backend.
  40223. *
  40224. * @type {WebGLBackend}
  40225. */
  40226. this.backend = backend;
  40227. /**
  40228. * A reference to the rendering context.
  40229. *
  40230. * @type {WebGL2RenderingContext}
  40231. */
  40232. this.gl = backend.gl;
  40233. /**
  40234. * A reference to a backend module holding extension-related
  40235. * utility functions.
  40236. *
  40237. * @type {WebGLExtensions}
  40238. */
  40239. this.extensions = backend.extensions;
  40240. /**
  40241. * A dictionary for managing default textures. The key
  40242. * is the binding point (target), the value the WEbGL texture object.
  40243. *
  40244. * @type {Object<GLenum,WebGLTexture>}
  40245. */
  40246. this.defaultTextures = {};
  40247. if ( initialized === false ) {
  40248. this._init();
  40249. initialized = true;
  40250. }
  40251. }
  40252. /**
  40253. * Inits the state of the utility.
  40254. *
  40255. * @private
  40256. */
  40257. _init() {
  40258. const gl = this.gl;
  40259. // Store only WebGL constants here.
  40260. wrappingToGL = {
  40261. [ RepeatWrapping ]: gl.REPEAT,
  40262. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40263. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40264. };
  40265. filterToGL = {
  40266. [ NearestFilter ]: gl.NEAREST,
  40267. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40268. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40269. [ LinearFilter ]: gl.LINEAR,
  40270. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40271. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40272. };
  40273. compareToGL = {
  40274. [ NeverCompare ]: gl.NEVER,
  40275. [ AlwaysCompare ]: gl.ALWAYS,
  40276. [ LessCompare ]: gl.LESS,
  40277. [ LessEqualCompare ]: gl.LEQUAL,
  40278. [ EqualCompare ]: gl.EQUAL,
  40279. [ GreaterEqualCompare ]: gl.GEQUAL,
  40280. [ GreaterCompare ]: gl.GREATER,
  40281. [ NotEqualCompare ]: gl.NOTEQUAL
  40282. };
  40283. }
  40284. /**
  40285. * Returns the native texture type for the given texture.
  40286. *
  40287. * @param {Texture} texture - The texture.
  40288. * @return {GLenum} The native texture type.
  40289. */
  40290. getGLTextureType( texture ) {
  40291. const { gl } = this;
  40292. let glTextureType;
  40293. if ( texture.isCubeTexture === true ) {
  40294. glTextureType = gl.TEXTURE_CUBE_MAP;
  40295. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40296. glTextureType = gl.TEXTURE_2D_ARRAY;
  40297. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40298. glTextureType = gl.TEXTURE_3D;
  40299. } else {
  40300. glTextureType = gl.TEXTURE_2D;
  40301. }
  40302. return glTextureType;
  40303. }
  40304. /**
  40305. * Returns the native texture type for the given texture.
  40306. *
  40307. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  40308. * @param {GLenum} glFormat - The WebGL format.
  40309. * @param {GLenum} glType - The WebGL type.
  40310. * @param {string} colorSpace - The texture's color space.
  40311. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  40312. * @return {GLenum} The internal format.
  40313. */
  40314. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40315. const { gl, extensions } = this;
  40316. if ( internalFormatName !== null ) {
  40317. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40318. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40319. }
  40320. let internalFormat = glFormat;
  40321. if ( glFormat === gl.RED ) {
  40322. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40323. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40324. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40325. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40326. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40327. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40328. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40329. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40330. }
  40331. if ( glFormat === gl.RED_INTEGER ) {
  40332. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40333. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40334. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40335. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40336. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40337. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40338. }
  40339. if ( glFormat === gl.RG ) {
  40340. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40341. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40342. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40343. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40344. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40345. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40346. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40347. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40348. }
  40349. if ( glFormat === gl.RG_INTEGER ) {
  40350. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40351. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40352. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40353. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40354. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40355. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40356. }
  40357. if ( glFormat === gl.RGB ) {
  40358. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40359. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40360. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40361. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40362. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40363. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40364. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40365. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40366. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40367. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40368. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40369. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40370. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40371. }
  40372. if ( glFormat === gl.RGB_INTEGER ) {
  40373. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40374. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40375. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40376. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40377. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40378. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40379. }
  40380. if ( glFormat === gl.RGBA ) {
  40381. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40382. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40383. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40384. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40385. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40386. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40387. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40388. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40389. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40390. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40391. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40392. }
  40393. if ( glFormat === gl.RGBA_INTEGER ) {
  40394. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40395. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40396. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40397. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40398. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40399. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40400. }
  40401. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40402. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  40403. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  40404. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40405. }
  40406. if ( glFormat === gl.DEPTH_STENCIL ) {
  40407. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40408. }
  40409. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40410. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40411. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40412. extensions.get( 'EXT_color_buffer_float' );
  40413. }
  40414. return internalFormat;
  40415. }
  40416. /**
  40417. * Sets the texture parameters for the given texture.
  40418. *
  40419. * @param {GLenum} textureType - The texture type.
  40420. * @param {Texture} texture - The texture.
  40421. */
  40422. setTextureParameters( textureType, texture ) {
  40423. const { gl, extensions, backend } = this;
  40424. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40425. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40426. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40427. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40428. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40429. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40430. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40431. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40432. }
  40433. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40434. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40435. // follow WebGPU backend mapping for texture filtering
  40436. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40437. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40438. if ( texture.compareFunction ) {
  40439. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40440. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40441. }
  40442. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40443. if ( texture.magFilter === NearestFilter ) return;
  40444. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40445. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40446. if ( texture.anisotropy > 1 ) {
  40447. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40448. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40449. }
  40450. }
  40451. }
  40452. /**
  40453. * Creates a default texture for the given texture that can be used
  40454. * as a placeholder until the actual texture is ready for usage.
  40455. *
  40456. * @param {Texture} texture - The texture to create a default texture for.
  40457. */
  40458. createDefaultTexture( texture ) {
  40459. const { gl, backend, defaultTextures } = this;
  40460. const glTextureType = this.getGLTextureType( texture );
  40461. let textureGPU = defaultTextures[ glTextureType ];
  40462. if ( textureGPU === undefined ) {
  40463. textureGPU = gl.createTexture();
  40464. backend.state.bindTexture( glTextureType, textureGPU );
  40465. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40466. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40467. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40468. defaultTextures[ glTextureType ] = textureGPU;
  40469. }
  40470. backend.set( texture, {
  40471. textureGPU,
  40472. glTextureType,
  40473. isDefault: true
  40474. } );
  40475. }
  40476. /**
  40477. * Defines a texture on the GPU for the given texture object.
  40478. *
  40479. * @param {Texture} texture - The texture.
  40480. * @param {Object} [options={}] - Optional configuration parameter.
  40481. * @return {undefined}
  40482. */
  40483. createTexture( texture, options ) {
  40484. const { gl, backend } = this;
  40485. const { levels, width, height, depth } = options;
  40486. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40487. const glType = backend.utils.convert( texture.type );
  40488. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40489. const textureGPU = gl.createTexture();
  40490. const glTextureType = this.getGLTextureType( texture );
  40491. backend.state.bindTexture( glTextureType, textureGPU );
  40492. this.setTextureParameters( glTextureType, texture );
  40493. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40494. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40495. } else if ( texture.isData3DTexture ) {
  40496. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40497. } else if ( ! texture.isVideoTexture ) {
  40498. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40499. }
  40500. backend.set( texture, {
  40501. textureGPU,
  40502. glTextureType,
  40503. glFormat,
  40504. glType,
  40505. glInternalFormat
  40506. } );
  40507. }
  40508. /**
  40509. * Uploads texture buffer data to the GPU memory.
  40510. *
  40511. * @param {WebGLBuffer} buffer - The buffer data.
  40512. * @param {Texture} texture - The texture,
  40513. */
  40514. copyBufferToTexture( buffer, texture ) {
  40515. const { gl, backend } = this;
  40516. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40517. const { width, height } = texture.source.data;
  40518. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40519. backend.state.bindTexture( glTextureType, textureGPU );
  40520. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40521. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40522. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40523. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40524. backend.state.unbindTexture();
  40525. // debug
  40526. // const framebuffer = gl.createFramebuffer();
  40527. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40528. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40529. // const readout = new Float32Array( width * height * 4 );
  40530. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40531. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40532. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40533. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40534. // console.log( readout );
  40535. }
  40536. /**
  40537. * Uploads the updated texture data to the GPU.
  40538. *
  40539. * @param {Texture} texture - The texture.
  40540. * @param {Object} [options={}] - Optional configuration parameter.
  40541. */
  40542. updateTexture( texture, options ) {
  40543. const { gl } = this;
  40544. const { width, height } = options;
  40545. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40546. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40547. return;
  40548. const getImage = ( source ) => {
  40549. if ( source.isDataTexture ) {
  40550. return source.image.data;
  40551. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  40552. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  40553. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  40554. source instanceof OffscreenCanvas ) {
  40555. return source;
  40556. }
  40557. return source.data;
  40558. };
  40559. this.backend.state.bindTexture( glTextureType, textureGPU );
  40560. this.setTextureParameters( glTextureType, texture );
  40561. if ( texture.isCompressedTexture ) {
  40562. const mipmaps = texture.mipmaps;
  40563. const image = options.image;
  40564. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40565. const mipmap = mipmaps[ i ];
  40566. if ( texture.isCompressedArrayTexture ) {
  40567. if ( texture.format !== gl.RGBA ) {
  40568. if ( glFormat !== null ) {
  40569. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40570. } else {
  40571. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40572. }
  40573. } else {
  40574. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40575. }
  40576. } else {
  40577. if ( glFormat !== null ) {
  40578. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40579. } else {
  40580. console.warn( 'Unsupported compressed texture format' );
  40581. }
  40582. }
  40583. }
  40584. } else if ( texture.isCubeTexture ) {
  40585. const images = options.images;
  40586. for ( let i = 0; i < 6; i ++ ) {
  40587. const image = getImage( images[ i ] );
  40588. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40589. }
  40590. } else if ( texture.isDataArrayTexture ) {
  40591. const image = options.image;
  40592. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40593. } else if ( texture.isData3DTexture ) {
  40594. const image = options.image;
  40595. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40596. } else if ( texture.isVideoTexture ) {
  40597. texture.update();
  40598. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40599. } else {
  40600. const image = getImage( options.image );
  40601. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40602. }
  40603. }
  40604. /**
  40605. * Generates mipmaps for the given texture.
  40606. *
  40607. * @param {Texture} texture - The texture.
  40608. */
  40609. generateMipmaps( texture ) {
  40610. const { gl, backend } = this;
  40611. const { textureGPU, glTextureType } = backend.get( texture );
  40612. backend.state.bindTexture( glTextureType, textureGPU );
  40613. gl.generateMipmap( glTextureType );
  40614. }
  40615. /**
  40616. * Deallocates the render buffers of the given render target.
  40617. *
  40618. * @param {RenderTarget} renderTarget - The render target.
  40619. */
  40620. deallocateRenderBuffers( renderTarget ) {
  40621. const { gl, backend } = this;
  40622. // remove framebuffer reference
  40623. if ( renderTarget ) {
  40624. const renderContextData = backend.get( renderTarget );
  40625. renderContextData.renderBufferStorageSetup = undefined;
  40626. if ( renderContextData.framebuffers ) {
  40627. for ( const cacheKey in renderContextData.framebuffers ) {
  40628. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40629. }
  40630. delete renderContextData.framebuffers;
  40631. }
  40632. if ( renderContextData.depthRenderbuffer ) {
  40633. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40634. delete renderContextData.depthRenderbuffer;
  40635. }
  40636. if ( renderContextData.stencilRenderbuffer ) {
  40637. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40638. delete renderContextData.stencilRenderbuffer;
  40639. }
  40640. if ( renderContextData.msaaFrameBuffer ) {
  40641. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40642. delete renderContextData.msaaFrameBuffer;
  40643. }
  40644. if ( renderContextData.msaaRenderbuffers ) {
  40645. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40646. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40647. }
  40648. delete renderContextData.msaaRenderbuffers;
  40649. }
  40650. }
  40651. }
  40652. /**
  40653. * Destroys the GPU data for the given texture object.
  40654. *
  40655. * @param {Texture} texture - The texture.
  40656. */
  40657. destroyTexture( texture ) {
  40658. const { gl, backend } = this;
  40659. const { textureGPU, renderTarget } = backend.get( texture );
  40660. this.deallocateRenderBuffers( renderTarget );
  40661. gl.deleteTexture( textureGPU );
  40662. backend.delete( texture );
  40663. }
  40664. /**
  40665. * Copies data of the given source texture to the given destination texture.
  40666. *
  40667. * @param {Texture} srcTexture - The source texture.
  40668. * @param {Texture} dstTexture - The destination texture.
  40669. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  40670. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  40671. * @param {number} [level=0] - The mip level to copy.
  40672. */
  40673. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40674. const { gl, backend } = this;
  40675. const { state } = this.backend;
  40676. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40677. let width, height, minX, minY;
  40678. let dstX, dstY;
  40679. if ( srcRegion !== null ) {
  40680. width = srcRegion.max.x - srcRegion.min.x;
  40681. height = srcRegion.max.y - srcRegion.min.y;
  40682. minX = srcRegion.min.x;
  40683. minY = srcRegion.min.y;
  40684. } else {
  40685. width = srcTexture.image.width;
  40686. height = srcTexture.image.height;
  40687. minX = 0;
  40688. minY = 0;
  40689. }
  40690. if ( dstPosition !== null ) {
  40691. dstX = dstPosition.x;
  40692. dstY = dstPosition.y;
  40693. } else {
  40694. dstX = 0;
  40695. dstY = 0;
  40696. }
  40697. state.bindTexture( glTextureType, dstTextureGPU );
  40698. // As another texture upload may have changed pixelStorei
  40699. // parameters, make sure they are correct for the dstTexture
  40700. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40701. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40702. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40703. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40704. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40705. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40706. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40707. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40708. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40709. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40710. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40711. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40712. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40713. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40714. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40715. const srcTextureData = backend.get( srcTexture );
  40716. const dstTextureData = backend.get( dstTexture );
  40717. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40718. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40719. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40720. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40721. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40722. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40723. let mask = gl.COLOR_BUFFER_BIT;
  40724. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40725. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40726. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40727. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40728. } else {
  40729. if ( srcTexture.isDataTexture ) {
  40730. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40731. } else {
  40732. if ( srcTexture.isCompressedTexture ) {
  40733. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40734. } else {
  40735. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40736. }
  40737. }
  40738. }
  40739. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40740. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40741. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40742. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40743. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40744. // Generate mipmaps only when copying level 0
  40745. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40746. state.unbindTexture();
  40747. }
  40748. /**
  40749. * Copies the current bound framebuffer to the given texture.
  40750. *
  40751. * @param {Texture} texture - The destination texture.
  40752. * @param {RenderContext} renderContext - The render context.
  40753. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40754. */
  40755. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40756. const { gl } = this;
  40757. const { state } = this.backend;
  40758. const { textureGPU } = this.backend.get( texture );
  40759. const { x, y, z: width, w: height } = rectangle;
  40760. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40761. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  40762. if ( requireDrawFrameBuffer ) {
  40763. const partial = ( x !== 0 || y !== 0 );
  40764. let mask;
  40765. let attachment;
  40766. if ( texture.isDepthTexture === true ) {
  40767. mask = gl.DEPTH_BUFFER_BIT;
  40768. attachment = gl.DEPTH_ATTACHMENT;
  40769. if ( renderContext.stencil ) {
  40770. mask |= gl.STENCIL_BUFFER_BIT;
  40771. }
  40772. } else {
  40773. mask = gl.COLOR_BUFFER_BIT;
  40774. attachment = gl.COLOR_ATTACHMENT0;
  40775. }
  40776. if ( partial ) {
  40777. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40778. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40779. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40780. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40781. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40782. const flippedY = srcHeight - y - height;
  40783. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40784. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40785. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40786. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40787. state.unbindTexture();
  40788. } else {
  40789. const fb = gl.createFramebuffer();
  40790. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40791. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40792. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40793. gl.deleteFramebuffer( fb );
  40794. }
  40795. } else {
  40796. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40797. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40798. state.unbindTexture();
  40799. }
  40800. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40801. this.backend._setFramebuffer( renderContext );
  40802. }
  40803. /**
  40804. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  40805. *
  40806. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  40807. * @param {RenderContext} renderContext - The render context.
  40808. * @param {number} samples - The MSAA sample count.
  40809. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  40810. */
  40811. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  40812. const { gl } = this;
  40813. const renderTarget = renderContext.renderTarget;
  40814. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40815. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40816. if ( depthBuffer && ! stencilBuffer ) {
  40817. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40818. if ( useMultisampledRTT === true ) {
  40819. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40820. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  40821. } else if ( samples > 0 ) {
  40822. if ( depthTexture && depthTexture.isDepthTexture ) {
  40823. if ( depthTexture.type === gl.FLOAT ) {
  40824. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40825. }
  40826. }
  40827. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40828. } else {
  40829. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40830. }
  40831. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40832. } else if ( depthBuffer && stencilBuffer ) {
  40833. if ( samples > 0 ) {
  40834. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40835. } else {
  40836. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40837. }
  40838. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40839. }
  40840. }
  40841. /**
  40842. * Returns texture data as a typed array.
  40843. *
  40844. * @async
  40845. * @param {Texture} texture - The texture to copy.
  40846. * @param {number} x - The x coordinate of the copy origin.
  40847. * @param {number} y - The y coordinate of the copy origin.
  40848. * @param {number} width - The width of the copy.
  40849. * @param {number} height - The height of the copy.
  40850. * @param {number} faceIndex - The face index.
  40851. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40852. */
  40853. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40854. const { backend, gl } = this;
  40855. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40856. const fb = gl.createFramebuffer();
  40857. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40858. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40859. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40860. const typedArrayType = this._getTypedArrayType( glType );
  40861. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40862. const elementCount = width * height;
  40863. const byteLength = elementCount * bytesPerTexel;
  40864. const buffer = gl.createBuffer();
  40865. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40866. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40867. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40868. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40869. await backend.utils._clientWaitAsync();
  40870. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40871. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40872. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40873. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40874. gl.deleteFramebuffer( fb );
  40875. return dstBuffer;
  40876. }
  40877. /**
  40878. * Returns the corresponding typed array type for the given WebGL data type.
  40879. *
  40880. * @private
  40881. * @param {GLenum} glType - The WebGL data type.
  40882. * @return {TypedArray.constructor} The typed array type.
  40883. */
  40884. _getTypedArrayType( glType ) {
  40885. const { gl } = this;
  40886. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40887. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40888. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40889. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40890. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40891. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40892. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40893. if ( glType === gl.FLOAT ) return Float32Array;
  40894. throw new Error( `Unsupported WebGL type: ${glType}` );
  40895. }
  40896. /**
  40897. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  40898. *
  40899. * @private
  40900. * @param {GLenum} glType - The WebGL data type.
  40901. * @param {GLenum} glFormat - The WebGL texture format.
  40902. * @return {number} The bytes-per-texel.
  40903. */
  40904. _getBytesPerTexel( glType, glFormat ) {
  40905. const { gl } = this;
  40906. let bytesPerComponent = 0;
  40907. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40908. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40909. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40910. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40911. glType === gl.UNSIGNED_SHORT ||
  40912. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40913. if ( glType === gl.UNSIGNED_INT ||
  40914. glType === gl.FLOAT ) bytesPerComponent = 4;
  40915. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40916. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40917. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40918. }
  40919. }
  40920. /**
  40921. * A WebGL 2 backend utility module for managing extensions.
  40922. *
  40923. * @private
  40924. */
  40925. class WebGLExtensions {
  40926. /**
  40927. * Constructs a new utility object.
  40928. *
  40929. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40930. */
  40931. constructor( backend ) {
  40932. /**
  40933. * A reference to the WebGL 2 backend.
  40934. *
  40935. * @type {WebGLBackend}
  40936. */
  40937. this.backend = backend;
  40938. /**
  40939. * A reference to the rendering context.
  40940. *
  40941. * @type {WebGL2RenderingContext}
  40942. */
  40943. this.gl = this.backend.gl;
  40944. /**
  40945. * A list with all the supported WebGL extensions.
  40946. *
  40947. * @type {Array<string>}
  40948. */
  40949. this.availableExtensions = this.gl.getSupportedExtensions();
  40950. /**
  40951. * A dictionary with requested WebGL extensions.
  40952. * The key is the name of the extension, the value
  40953. * the requested extension object.
  40954. *
  40955. * @type {Object<string,Object>}
  40956. */
  40957. this.extensions = {};
  40958. }
  40959. /**
  40960. * Returns the extension object for the given extension name.
  40961. *
  40962. * @param {string} name - The extension name.
  40963. * @return {Object} The extension object.
  40964. */
  40965. get( name ) {
  40966. let extension = this.extensions[ name ];
  40967. if ( extension === undefined ) {
  40968. extension = this.gl.getExtension( name );
  40969. this.extensions[ name ] = extension;
  40970. }
  40971. return extension;
  40972. }
  40973. /**
  40974. * Returns `true` if the requested extension is available.
  40975. *
  40976. * @param {string} name - The extension name.
  40977. * @return {boolean} Whether the given extension is available or not.
  40978. */
  40979. has( name ) {
  40980. return this.availableExtensions.includes( name );
  40981. }
  40982. }
  40983. /**
  40984. * A WebGL 2 backend utility module for managing the device's capabilities.
  40985. *
  40986. * @private
  40987. */
  40988. class WebGLCapabilities {
  40989. /**
  40990. * Constructs a new utility object.
  40991. *
  40992. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40993. */
  40994. constructor( backend ) {
  40995. /**
  40996. * A reference to the WebGL 2 backend.
  40997. *
  40998. * @type {WebGLBackend}
  40999. */
  41000. this.backend = backend;
  41001. /**
  41002. * This value holds the cached max anisotropy value.
  41003. *
  41004. * @type {?number}
  41005. * @default null
  41006. */
  41007. this.maxAnisotropy = null;
  41008. }
  41009. /**
  41010. * Returns the maximum anisotropy texture filtering value. This value
  41011. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  41012. * WebGL extension.
  41013. *
  41014. * @return {number} The maximum anisotropy texture filtering value.
  41015. */
  41016. getMaxAnisotropy() {
  41017. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  41018. const gl = this.backend.gl;
  41019. const extensions = this.backend.extensions;
  41020. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41021. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41022. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  41023. } else {
  41024. this.maxAnisotropy = 0;
  41025. }
  41026. return this.maxAnisotropy;
  41027. }
  41028. }
  41029. const GLFeatureName = {
  41030. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  41031. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  41032. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  41033. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  41034. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41035. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41036. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  41037. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  41038. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  41039. };
  41040. class WebGLBufferRenderer {
  41041. constructor( backend ) {
  41042. this.gl = backend.gl;
  41043. this.extensions = backend.extensions;
  41044. this.info = backend.renderer.info;
  41045. this.mode = null;
  41046. this.index = 0;
  41047. this.type = null;
  41048. this.object = null;
  41049. }
  41050. render( start, count ) {
  41051. const { gl, mode, object, type, info, index } = this;
  41052. if ( index !== 0 ) {
  41053. gl.drawElements( mode, count, type, start );
  41054. } else {
  41055. gl.drawArrays( mode, start, count );
  41056. }
  41057. info.update( object, count, 1 );
  41058. }
  41059. renderInstances( start, count, primcount ) {
  41060. const { gl, mode, type, index, object, info } = this;
  41061. if ( primcount === 0 ) return;
  41062. if ( index !== 0 ) {
  41063. gl.drawElementsInstanced( mode, count, type, start, primcount );
  41064. } else {
  41065. gl.drawArraysInstanced( mode, start, count, primcount );
  41066. }
  41067. info.update( object, count, primcount );
  41068. }
  41069. renderMultiDraw( starts, counts, drawCount ) {
  41070. const { extensions, mode, object, info } = this;
  41071. if ( drawCount === 0 ) return;
  41072. const extension = extensions.get( 'WEBGL_multi_draw' );
  41073. if ( extension === null ) {
  41074. for ( let i = 0; i < drawCount; i ++ ) {
  41075. this.render( starts[ i ], counts[ i ] );
  41076. }
  41077. } else {
  41078. if ( this.index !== 0 ) {
  41079. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  41080. } else {
  41081. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  41082. }
  41083. let elementCount = 0;
  41084. for ( let i = 0; i < drawCount; i ++ ) {
  41085. elementCount += counts[ i ];
  41086. }
  41087. info.update( object, elementCount, 1 );
  41088. }
  41089. }
  41090. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  41091. const { extensions, mode, object, info } = this;
  41092. if ( drawCount === 0 ) return;
  41093. const extension = extensions.get( 'WEBGL_multi_draw' );
  41094. if ( extension === null ) {
  41095. for ( let i = 0; i < drawCount; i ++ ) {
  41096. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  41097. }
  41098. } else {
  41099. if ( this.index !== 0 ) {
  41100. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  41101. } else {
  41102. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  41103. }
  41104. let elementCount = 0;
  41105. for ( let i = 0; i < drawCount; i ++ ) {
  41106. elementCount += counts[ i ] * primcount[ i ];
  41107. }
  41108. info.update( object, elementCount, 1 );
  41109. }
  41110. }
  41111. //
  41112. }
  41113. /**
  41114. * Abstract base class of a timestamp query pool.
  41115. *
  41116. * @abstract
  41117. */
  41118. class TimestampQueryPool {
  41119. /**
  41120. * Creates a new timestamp query pool.
  41121. *
  41122. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  41123. */
  41124. constructor( maxQueries = 256 ) {
  41125. /**
  41126. * Whether to track timestamps or not.
  41127. *
  41128. * @type {boolean}
  41129. * @default true
  41130. */
  41131. this.trackTimestamp = true;
  41132. /**
  41133. * Maximum number of queries this pool can hold.
  41134. *
  41135. * @type {number}
  41136. * @default 256
  41137. */
  41138. this.maxQueries = maxQueries;
  41139. /**
  41140. * How many queries allocated so far.
  41141. *
  41142. * @type {number}
  41143. * @default 0
  41144. */
  41145. this.currentQueryIndex = 0;
  41146. /**
  41147. * Tracks offsets for different contexts.
  41148. *
  41149. * @type {Map}
  41150. */
  41151. this.queryOffsets = new Map();
  41152. /**
  41153. * Whether the pool has been disposed or not.
  41154. *
  41155. * @type {boolean}
  41156. * @default false
  41157. */
  41158. this.isDisposed = false;
  41159. /**
  41160. * TODO
  41161. *
  41162. * @type {number}
  41163. * @default 0
  41164. */
  41165. this.lastValue = 0;
  41166. /**
  41167. * TODO
  41168. *
  41169. * @type {boolean}
  41170. * @default false
  41171. */
  41172. this.pendingResolve = false;
  41173. }
  41174. /**
  41175. * Allocate queries for a specific renderContext.
  41176. *
  41177. * @abstract
  41178. * @param {Object} renderContext - The render context to allocate queries for.
  41179. */
  41180. allocateQueriesForContext( /* renderContext */ ) {}
  41181. /**
  41182. * Resolve all timestamps and return data (or process them).
  41183. *
  41184. * @abstract
  41185. * @async
  41186. * @returns {Promise<number>|number} The resolved timestamp value.
  41187. */
  41188. async resolveQueriesAsync() {}
  41189. /**
  41190. * Dispose of the query pool.
  41191. *
  41192. * @abstract
  41193. */
  41194. dispose() {}
  41195. }
  41196. /**
  41197. * Manages a pool of WebGL timestamp queries for performance measurement.
  41198. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  41199. *
  41200. * @augments TimestampQueryPool
  41201. */
  41202. class WebGLTimestampQueryPool extends TimestampQueryPool {
  41203. /**
  41204. * Creates a new WebGL timestamp query pool.
  41205. *
  41206. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  41207. * @param {string} type - The type identifier for this query pool.
  41208. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  41209. */
  41210. constructor( gl, type, maxQueries = 2048 ) {
  41211. super( maxQueries );
  41212. this.gl = gl;
  41213. this.type = type;
  41214. // Check for timer query extensions
  41215. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  41216. gl.getExtension( 'EXT_disjoint_timer_query' );
  41217. if ( ! this.ext ) {
  41218. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  41219. this.trackTimestamp = false;
  41220. return;
  41221. }
  41222. // Create query objects
  41223. this.queries = [];
  41224. for ( let i = 0; i < this.maxQueries; i ++ ) {
  41225. this.queries.push( gl.createQuery() );
  41226. }
  41227. this.activeQuery = null;
  41228. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  41229. }
  41230. /**
  41231. * Allocates a pair of queries for a given render context.
  41232. *
  41233. * @param {Object} renderContext - The render context to allocate queries for.
  41234. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  41235. */
  41236. allocateQueriesForContext( renderContext ) {
  41237. if ( ! this.trackTimestamp ) return null;
  41238. // Check if we have enough space for a new query pair
  41239. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  41240. 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() } ).` );
  41241. return null;
  41242. }
  41243. const baseOffset = this.currentQueryIndex;
  41244. this.currentQueryIndex += 2;
  41245. // Initialize query states
  41246. this.queryStates.set( baseOffset, 'inactive' );
  41247. this.queryOffsets.set( renderContext.id, baseOffset );
  41248. return baseOffset;
  41249. }
  41250. /**
  41251. * Begins a timestamp query for the specified render context.
  41252. *
  41253. * @param {Object} renderContext - The render context to begin timing for.
  41254. */
  41255. beginQuery( renderContext ) {
  41256. if ( ! this.trackTimestamp || this.isDisposed ) {
  41257. return;
  41258. }
  41259. const baseOffset = this.queryOffsets.get( renderContext.id );
  41260. if ( baseOffset == null ) {
  41261. return;
  41262. }
  41263. // Don't start a new query if there's an active one
  41264. if ( this.activeQuery !== null ) {
  41265. return;
  41266. }
  41267. const query = this.queries[ baseOffset ];
  41268. if ( ! query ) {
  41269. return;
  41270. }
  41271. try {
  41272. // Only begin if query is inactive
  41273. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  41274. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  41275. this.activeQuery = baseOffset;
  41276. this.queryStates.set( baseOffset, 'started' );
  41277. }
  41278. } catch ( error ) {
  41279. console.error( 'Error in beginQuery:', error );
  41280. this.activeQuery = null;
  41281. this.queryStates.set( baseOffset, 'inactive' );
  41282. }
  41283. }
  41284. /**
  41285. * Ends the active timestamp query for the specified render context.
  41286. *
  41287. * @param {Object} renderContext - The render context to end timing for.
  41288. * @param {string} renderContext.id - Unique identifier for the render context.
  41289. */
  41290. endQuery( renderContext ) {
  41291. if ( ! this.trackTimestamp || this.isDisposed ) {
  41292. return;
  41293. }
  41294. const baseOffset = this.queryOffsets.get( renderContext.id );
  41295. if ( baseOffset == null ) {
  41296. return;
  41297. }
  41298. // Only end if this is the active query
  41299. if ( this.activeQuery !== baseOffset ) {
  41300. return;
  41301. }
  41302. try {
  41303. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  41304. this.queryStates.set( baseOffset, 'ended' );
  41305. this.activeQuery = null;
  41306. } catch ( error ) {
  41307. console.error( 'Error in endQuery:', error );
  41308. // Reset state on error
  41309. this.queryStates.set( baseOffset, 'inactive' );
  41310. this.activeQuery = null;
  41311. }
  41312. }
  41313. /**
  41314. * Asynchronously resolves all completed queries and returns the total duration.
  41315. *
  41316. * @async
  41317. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  41318. */
  41319. async resolveQueriesAsync() {
  41320. if ( ! this.trackTimestamp || this.pendingResolve ) {
  41321. return this.lastValue;
  41322. }
  41323. this.pendingResolve = true;
  41324. try {
  41325. // Wait for all ended queries to complete
  41326. const resolvePromises = [];
  41327. for ( const [ baseOffset, state ] of this.queryStates ) {
  41328. if ( state === 'ended' ) {
  41329. const query = this.queries[ baseOffset ];
  41330. resolvePromises.push( this.resolveQuery( query ) );
  41331. }
  41332. }
  41333. if ( resolvePromises.length === 0 ) {
  41334. return this.lastValue;
  41335. }
  41336. const results = await Promise.all( resolvePromises );
  41337. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  41338. // Store the last valid result
  41339. this.lastValue = totalDuration;
  41340. // Reset states
  41341. this.currentQueryIndex = 0;
  41342. this.queryOffsets.clear();
  41343. this.queryStates.clear();
  41344. this.activeQuery = null;
  41345. return totalDuration;
  41346. } catch ( error ) {
  41347. console.error( 'Error resolving queries:', error );
  41348. return this.lastValue;
  41349. } finally {
  41350. this.pendingResolve = false;
  41351. }
  41352. }
  41353. /**
  41354. * Resolves a single query, checking for completion and disjoint operation.
  41355. *
  41356. * @async
  41357. * @param {WebGLQuery} query - The query object to resolve.
  41358. * @returns {Promise<number>} The elapsed time in milliseconds.
  41359. */
  41360. async resolveQuery( query ) {
  41361. return new Promise( ( resolve ) => {
  41362. if ( this.isDisposed ) {
  41363. resolve( this.lastValue );
  41364. return;
  41365. }
  41366. let timeoutId;
  41367. let isResolved = false;
  41368. const cleanup = () => {
  41369. if ( timeoutId ) {
  41370. clearTimeout( timeoutId );
  41371. timeoutId = null;
  41372. }
  41373. };
  41374. const finalizeResolution = ( value ) => {
  41375. if ( ! isResolved ) {
  41376. isResolved = true;
  41377. cleanup();
  41378. resolve( value );
  41379. }
  41380. };
  41381. const checkQuery = () => {
  41382. if ( this.isDisposed ) {
  41383. finalizeResolution( this.lastValue );
  41384. return;
  41385. }
  41386. try {
  41387. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  41388. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  41389. if ( disjoint ) {
  41390. finalizeResolution( this.lastValue );
  41391. return;
  41392. }
  41393. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  41394. if ( ! available ) {
  41395. timeoutId = setTimeout( checkQuery, 1 );
  41396. return;
  41397. }
  41398. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  41399. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  41400. } catch ( error ) {
  41401. console.error( 'Error checking query:', error );
  41402. resolve( this.lastValue );
  41403. }
  41404. };
  41405. checkQuery();
  41406. } );
  41407. }
  41408. /**
  41409. * Releases all resources held by this query pool.
  41410. * This includes deleting all query objects and clearing internal state.
  41411. */
  41412. dispose() {
  41413. if ( this.isDisposed ) {
  41414. return;
  41415. }
  41416. this.isDisposed = true;
  41417. if ( ! this.trackTimestamp ) return;
  41418. for ( const query of this.queries ) {
  41419. this.gl.deleteQuery( query );
  41420. }
  41421. this.queries = [];
  41422. this.queryStates.clear();
  41423. this.queryOffsets.clear();
  41424. this.lastValue = 0;
  41425. this.activeQuery = null;
  41426. }
  41427. }
  41428. /**
  41429. * A backend implementation targeting WebGL 2.
  41430. *
  41431. * @private
  41432. * @augments Backend
  41433. */
  41434. class WebGLBackend extends Backend {
  41435. /**
  41436. * Constructs a new WebGPU backend.
  41437. *
  41438. * @param {Object} parameters - The configuration parameter.
  41439. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  41440. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  41441. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  41442. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  41443. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  41444. * @param {number} [parameters.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.
  41445. * @param {boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  41446. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  41447. */
  41448. constructor( parameters = {} ) {
  41449. super( parameters );
  41450. /**
  41451. * This flag can be used for type testing.
  41452. *
  41453. * @type {boolean}
  41454. * @readonly
  41455. * @default true
  41456. */
  41457. this.isWebGLBackend = true;
  41458. /**
  41459. * A reference to a backend module holding shader attribute-related
  41460. * utility functions.
  41461. *
  41462. * @type {?WebGLAttributeUtils}
  41463. * @default null
  41464. */
  41465. this.attributeUtils = null;
  41466. /**
  41467. * A reference to a backend module holding extension-related
  41468. * utility functions.
  41469. *
  41470. * @type {?WebGLExtensions}
  41471. * @default null
  41472. */
  41473. this.extensions = null;
  41474. /**
  41475. * A reference to a backend module holding capability-related
  41476. * utility functions.
  41477. *
  41478. * @type {?WebGLCapabilities}
  41479. * @default null
  41480. */
  41481. this.capabilities = null;
  41482. /**
  41483. * A reference to a backend module holding texture-related
  41484. * utility functions.
  41485. *
  41486. * @type {?WebGLTextureUtils}
  41487. * @default null
  41488. */
  41489. this.textureUtils = null;
  41490. /**
  41491. * A reference to a backend module holding renderer-related
  41492. * utility functions.
  41493. *
  41494. * @type {?WebGLBufferRenderer}
  41495. * @default null
  41496. */
  41497. this.bufferRenderer = null;
  41498. /**
  41499. * A reference to the rendering context.
  41500. *
  41501. * @type {?WebGL2RenderingContext}
  41502. * @default null
  41503. */
  41504. this.gl = null;
  41505. /**
  41506. * A reference to a backend module holding state-related
  41507. * utility functions.
  41508. *
  41509. * @type {?WebGLState}
  41510. * @default null
  41511. */
  41512. this.state = null;
  41513. /**
  41514. * A reference to a backend module holding common
  41515. * utility functions.
  41516. *
  41517. * @type {?WebGLUtils}
  41518. * @default null
  41519. */
  41520. this.utils = null;
  41521. /**
  41522. * Dictionary for caching VAOs.
  41523. *
  41524. * @type {Object<string,WebGLVertexArrayObject>}
  41525. */
  41526. this.vaoCache = {};
  41527. /**
  41528. * Dictionary for caching transform feedback objects.
  41529. *
  41530. * @type {Object<string,WebGLTransformFeedback>}
  41531. */
  41532. this.transformFeedbackCache = {};
  41533. /**
  41534. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  41535. * Only relevant when using compute shaders.
  41536. *
  41537. * @type {boolean}
  41538. * @default false
  41539. */
  41540. this.discard = false;
  41541. /**
  41542. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  41543. * device does not support the extension.
  41544. *
  41545. * @type {?EXTDisjointTimerQueryWebGL2}
  41546. * @default null
  41547. */
  41548. this.disjoint = null;
  41549. /**
  41550. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  41551. * device does not support the extension.
  41552. *
  41553. * @type {?KHRParallelShaderCompile}
  41554. * @default null
  41555. */
  41556. this.parallel = null;
  41557. /**
  41558. * Whether to track timestamps with a Timestamp Query API or not.
  41559. *
  41560. * @type {boolean}
  41561. * @default false
  41562. */
  41563. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41564. /**
  41565. * A reference to the current render context.
  41566. *
  41567. * @private
  41568. * @type {RenderContext}
  41569. * @default null
  41570. */
  41571. this._currentContext = null;
  41572. /**
  41573. * A unique collection of bindings.
  41574. *
  41575. * @private
  41576. * @type {WeakSet}
  41577. */
  41578. this._knownBindings = new WeakSet();
  41579. /**
  41580. * The target framebuffer when rendering with
  41581. * the WebXR device API.
  41582. *
  41583. * @private
  41584. * @type {WebGLFramebuffer}
  41585. * @default null
  41586. */
  41587. this._xrFamebuffer = null;
  41588. }
  41589. /**
  41590. * Initializes the backend so it is ready for usage.
  41591. *
  41592. * @param {Renderer} renderer - The renderer.
  41593. */
  41594. init( renderer ) {
  41595. super.init( renderer );
  41596. //
  41597. const parameters = this.parameters;
  41598. const contextAttributes = {
  41599. antialias: false, // MSAA is applied via a custom renderbuffer
  41600. alpha: true, // always true for performance reasons
  41601. depth: false, // depth and stencil are set to false since the engine always renders into a framebuffer target first
  41602. stencil: false
  41603. };
  41604. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  41605. function onContextLost( event ) {
  41606. event.preventDefault();
  41607. const contextLossInfo = {
  41608. api: 'WebGL',
  41609. message: event.statusMessage || 'Unknown reason',
  41610. reason: null,
  41611. originalEvent: event
  41612. };
  41613. renderer.onDeviceLost( contextLossInfo );
  41614. }
  41615. this._onContextLost = onContextLost;
  41616. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  41617. this.gl = glContext;
  41618. this.extensions = new WebGLExtensions( this );
  41619. this.capabilities = new WebGLCapabilities( this );
  41620. this.attributeUtils = new WebGLAttributeUtils( this );
  41621. this.textureUtils = new WebGLTextureUtils( this );
  41622. this.bufferRenderer = new WebGLBufferRenderer( this );
  41623. this.state = new WebGLState( this );
  41624. this.utils = new WebGLUtils( this );
  41625. this.extensions.get( 'EXT_color_buffer_float' );
  41626. this.extensions.get( 'WEBGL_clip_cull_distance' );
  41627. this.extensions.get( 'OES_texture_float_linear' );
  41628. this.extensions.get( 'EXT_color_buffer_half_float' );
  41629. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41630. this.extensions.get( 'WEBGL_render_shared_exponent' );
  41631. this.extensions.get( 'WEBGL_multi_draw' );
  41632. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  41633. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  41634. }
  41635. /**
  41636. * The coordinate system of the backend.
  41637. *
  41638. * @type {number}
  41639. * @readonly
  41640. */
  41641. get coordinateSystem() {
  41642. return WebGLCoordinateSystem;
  41643. }
  41644. /**
  41645. * This method performs a readback operation by moving buffer data from
  41646. * a storage buffer attribute from the GPU to the CPU.
  41647. *
  41648. * @async
  41649. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41650. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41651. */
  41652. async getArrayBufferAsync( attribute ) {
  41653. return await this.attributeUtils.getArrayBufferAsync( attribute );
  41654. }
  41655. /**
  41656. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41657. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41658. *
  41659. * @async
  41660. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41661. */
  41662. async waitForGPU() {
  41663. await this.utils._clientWaitAsync();
  41664. }
  41665. /**
  41666. * Ensures the backend is XR compatible.
  41667. *
  41668. * @async
  41669. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  41670. */
  41671. async makeXRCompatible() {
  41672. const attributes = this.gl.getContextAttributes();
  41673. if ( attributes.xrCompatible !== true ) {
  41674. await this.gl.makeXRCompatible();
  41675. }
  41676. }
  41677. /**
  41678. * Sets the XR rendering destination.
  41679. *
  41680. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  41681. */
  41682. setXRTarget( xrFamebuffer ) {
  41683. this._xrFamebuffer = xrFamebuffer;
  41684. }
  41685. /**
  41686. * Configures the given XR render target with external textures.
  41687. *
  41688. * This method is only relevant when using the WebXR Layers API.
  41689. *
  41690. * @param {XRRenderTarget} renderTarget - The XR render target.
  41691. * @param {WebGLTexture} colorTexture - A native color texture.
  41692. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  41693. */
  41694. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  41695. const gl = this.gl;
  41696. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  41697. if ( depthTexture !== null ) {
  41698. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  41699. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  41700. renderTarget.autoAllocateDepthBuffer = false;
  41701. // The multisample_render_to_texture extension doesn't work properly if there
  41702. // are midframe flushes and an external depth texture.
  41703. if ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  41704. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  41705. }
  41706. }
  41707. }
  41708. /**
  41709. * Inits a time stamp query for the given render context.
  41710. *
  41711. * @param {RenderContext} renderContext - The render context.
  41712. */
  41713. initTimestampQuery( renderContext ) {
  41714. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41715. const type = renderContext.isComputeNode ? 'compute' : 'render';
  41716. if ( ! this.timestampQueryPool[ type ] ) {
  41717. // TODO: Variable maxQueries?
  41718. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  41719. }
  41720. const timestampQueryPool = this.timestampQueryPool[ type ];
  41721. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  41722. if ( baseOffset !== null ) {
  41723. timestampQueryPool.beginQuery( renderContext );
  41724. }
  41725. }
  41726. // timestamp utils
  41727. /**
  41728. * Prepares the timestamp buffer.
  41729. *
  41730. * @param {RenderContext} renderContext - The render context.
  41731. */
  41732. prepareTimestampBuffer( renderContext ) {
  41733. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41734. const type = renderContext.isComputeNode ? 'compute' : 'render';
  41735. const timestampQueryPool = this.timestampQueryPool[ type ];
  41736. timestampQueryPool.endQuery( renderContext );
  41737. }
  41738. /**
  41739. * Returns the backend's rendering context.
  41740. *
  41741. * @return {WebGL2RenderingContext} The rendering context.
  41742. */
  41743. getContext() {
  41744. return this.gl;
  41745. }
  41746. /**
  41747. * This method is executed at the beginning of a render call and prepares
  41748. * the WebGL state for upcoming render calls
  41749. *
  41750. * @param {RenderContext} renderContext - The render context.
  41751. */
  41752. beginRender( renderContext ) {
  41753. const { state, gl } = this;
  41754. const renderContextData = this.get( renderContext );
  41755. //
  41756. if ( renderContext.viewport ) {
  41757. this.updateViewport( renderContext );
  41758. } else {
  41759. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41760. }
  41761. if ( renderContext.scissor ) {
  41762. const { x, y, width, height } = renderContext.scissorValue;
  41763. state.scissor( x, renderContext.height - height - y, width, height );
  41764. }
  41765. //
  41766. this.initTimestampQuery( renderContext );
  41767. renderContextData.previousContext = this._currentContext;
  41768. this._currentContext = renderContext;
  41769. this._setFramebuffer( renderContext );
  41770. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41771. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41772. if ( occlusionQueryCount > 0 ) {
  41773. // Get a reference to the array of objects with queries. The renderContextData property
  41774. // can be changed by another render pass before the async reading of all previous queries complete
  41775. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41776. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41777. renderContextData.lastOcclusionObject = null;
  41778. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41779. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41780. renderContextData.occlusionQueryIndex = 0;
  41781. }
  41782. }
  41783. /**
  41784. * This method is executed at the end of a render call and finalizes work
  41785. * after draw calls.
  41786. *
  41787. * @param {RenderContext} renderContext - The render context.
  41788. */
  41789. finishRender( renderContext ) {
  41790. const { gl, state } = this;
  41791. const renderContextData = this.get( renderContext );
  41792. const previousContext = renderContextData.previousContext;
  41793. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41794. if ( occlusionQueryCount > 0 ) {
  41795. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41796. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41797. }
  41798. this.resolveOccludedAsync( renderContext );
  41799. }
  41800. const textures = renderContext.textures;
  41801. if ( textures !== null ) {
  41802. for ( let i = 0; i < textures.length; i ++ ) {
  41803. const texture = textures[ i ];
  41804. if ( texture.generateMipmaps ) {
  41805. this.generateMipmaps( texture );
  41806. }
  41807. }
  41808. }
  41809. this._currentContext = previousContext;
  41810. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41811. const renderTargetContextData = this.get( renderContext.renderTarget );
  41812. const { samples } = renderContext.renderTarget;
  41813. if ( samples > 0 && this._useMultisampledRTT( renderContext.renderTarget ) === false ) {
  41814. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41815. const mask = gl.COLOR_BUFFER_BIT;
  41816. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41817. const textures = renderContext.textures;
  41818. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41819. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41820. for ( let i = 0; i < textures.length; i ++ ) {
  41821. // TODO Add support for MRT
  41822. if ( renderContext.scissor ) {
  41823. const { x, y, width, height } = renderContext.scissorValue;
  41824. const viewY = renderContext.height - height - y;
  41825. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41826. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41827. } else {
  41828. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41829. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41830. }
  41831. }
  41832. }
  41833. }
  41834. if ( previousContext !== null ) {
  41835. this._setFramebuffer( previousContext );
  41836. if ( previousContext.viewport ) {
  41837. this.updateViewport( previousContext );
  41838. } else {
  41839. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41840. }
  41841. }
  41842. this.prepareTimestampBuffer( renderContext );
  41843. }
  41844. /**
  41845. * This method processes the result of occlusion queries and writes it
  41846. * into render context data.
  41847. *
  41848. * @async
  41849. * @param {RenderContext} renderContext - The render context.
  41850. */
  41851. resolveOccludedAsync( renderContext ) {
  41852. const renderContextData = this.get( renderContext );
  41853. // handle occlusion query results
  41854. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41855. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41856. const occluded = new WeakSet();
  41857. const { gl } = this;
  41858. renderContextData.currentOcclusionQueryObjects = null;
  41859. renderContextData.currentOcclusionQueries = null;
  41860. const check = () => {
  41861. let completed = 0;
  41862. // check all queries and requeue as appropriate
  41863. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41864. const query = currentOcclusionQueries[ i ];
  41865. if ( query === null ) continue;
  41866. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41867. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41868. currentOcclusionQueries[ i ] = null;
  41869. gl.deleteQuery( query );
  41870. completed ++;
  41871. }
  41872. }
  41873. if ( completed < currentOcclusionQueries.length ) {
  41874. requestAnimationFrame( check );
  41875. } else {
  41876. renderContextData.occluded = occluded;
  41877. }
  41878. };
  41879. check();
  41880. }
  41881. }
  41882. /**
  41883. * Returns `true` if the given 3D object is fully occluded by other
  41884. * 3D objects in the scene.
  41885. *
  41886. * @param {RenderContext} renderContext - The render context.
  41887. * @param {Object3D} object - The 3D object to test.
  41888. * @return {boolean} Whether the 3D object is fully occluded or not.
  41889. */
  41890. isOccluded( renderContext, object ) {
  41891. const renderContextData = this.get( renderContext );
  41892. return renderContextData.occluded && renderContextData.occluded.has( object );
  41893. }
  41894. /**
  41895. * Updates the viewport with the values from the given render context.
  41896. *
  41897. * @param {RenderContext} renderContext - The render context.
  41898. */
  41899. updateViewport( renderContext ) {
  41900. const { state } = this;
  41901. const { x, y, width, height } = renderContext.viewportValue;
  41902. state.viewport( x, renderContext.height - height - y, width, height );
  41903. }
  41904. /**
  41905. * Defines the scissor test.
  41906. *
  41907. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41908. */
  41909. setScissorTest( boolean ) {
  41910. const state = this.state;
  41911. state.setScissorTest( boolean );
  41912. }
  41913. /**
  41914. * Returns the clear color and alpha into a single
  41915. * color object.
  41916. *
  41917. * @return {Color4} The clear color.
  41918. */
  41919. getClearColor() {
  41920. const clearColor = super.getClearColor();
  41921. // Since the canvas is always created with alpha: true,
  41922. // WebGL must always premultiply the clear color.
  41923. clearColor.r *= clearColor.a;
  41924. clearColor.g *= clearColor.a;
  41925. clearColor.b *= clearColor.a;
  41926. return clearColor;
  41927. }
  41928. /**
  41929. * Performs a clear operation.
  41930. *
  41931. * @param {boolean} color - Whether the color buffer should be cleared or not.
  41932. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  41933. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  41934. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  41935. * @param {boolean} [setFrameBuffer=true] - TODO.
  41936. */
  41937. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41938. const { gl, renderer } = this;
  41939. if ( descriptor === null ) {
  41940. const clearColor = this.getClearColor();
  41941. descriptor = {
  41942. textures: null,
  41943. clearColorValue: clearColor
  41944. };
  41945. }
  41946. //
  41947. let clear = 0;
  41948. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41949. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41950. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41951. if ( clear !== 0 ) {
  41952. let clearColor;
  41953. if ( descriptor.clearColorValue ) {
  41954. clearColor = descriptor.clearColorValue;
  41955. } else {
  41956. clearColor = this.getClearColor();
  41957. }
  41958. const clearDepth = renderer.getClearDepth();
  41959. const clearStencil = renderer.getClearStencil();
  41960. if ( depth ) this.state.setDepthMask( true );
  41961. if ( descriptor.textures === null ) {
  41962. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41963. gl.clear( clear );
  41964. } else {
  41965. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41966. if ( color ) {
  41967. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41968. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41969. }
  41970. }
  41971. if ( depth && stencil ) {
  41972. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  41973. } else if ( depth ) {
  41974. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  41975. } else if ( stencil ) {
  41976. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  41977. }
  41978. }
  41979. }
  41980. }
  41981. /**
  41982. * This method is executed at the beginning of a compute call and
  41983. * prepares the state for upcoming compute tasks.
  41984. *
  41985. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41986. */
  41987. beginCompute( computeGroup ) {
  41988. const { state, gl } = this;
  41989. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41990. this.initTimestampQuery( computeGroup );
  41991. }
  41992. /**
  41993. * Executes a compute command for the given compute node.
  41994. *
  41995. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  41996. * @param {Node} computeNode - The compute node.
  41997. * @param {Array<BindGroup>} bindings - The bindings.
  41998. * @param {ComputePipeline} pipeline - The compute pipeline.
  41999. */
  42000. compute( computeGroup, computeNode, bindings, pipeline ) {
  42001. const { state, gl } = this;
  42002. if ( this.discard === false ) {
  42003. // required here to handle async behaviour of render.compute()
  42004. gl.enable( gl.RASTERIZER_DISCARD );
  42005. this.discard = true;
  42006. }
  42007. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  42008. const vaoKey = this._getVaoKey( null, attributes );
  42009. const vaoGPU = this.vaoCache[ vaoKey ];
  42010. if ( vaoGPU === undefined ) {
  42011. this._createVao( null, attributes );
  42012. } else {
  42013. gl.bindVertexArray( vaoGPU );
  42014. }
  42015. state.useProgram( programGPU );
  42016. this._bindUniforms( bindings );
  42017. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  42018. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42019. gl.beginTransformFeedback( gl.POINTS );
  42020. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  42021. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  42022. } else {
  42023. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  42024. }
  42025. gl.endTransformFeedback();
  42026. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42027. // switch active buffers
  42028. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42029. const dualAttributeData = transformBuffers[ i ];
  42030. if ( dualAttributeData.pbo ) {
  42031. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  42032. }
  42033. dualAttributeData.switchBuffers();
  42034. }
  42035. }
  42036. /**
  42037. * This method is executed at the end of a compute call and
  42038. * finalizes work after compute tasks.
  42039. *
  42040. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42041. */
  42042. finishCompute( computeGroup ) {
  42043. const gl = this.gl;
  42044. this.discard = false;
  42045. gl.disable( gl.RASTERIZER_DISCARD );
  42046. this.prepareTimestampBuffer( computeGroup );
  42047. if ( this._currentContext ) {
  42048. this._setFramebuffer( this._currentContext );
  42049. }
  42050. }
  42051. /**
  42052. * Executes a draw command for the given render object.
  42053. *
  42054. * @param {RenderObject} renderObject - The render object to draw.
  42055. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42056. */
  42057. draw( renderObject/*, info*/ ) {
  42058. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  42059. const { programGPU } = this.get( pipeline );
  42060. const { gl, state } = this;
  42061. const contextData = this.get( context );
  42062. const drawParams = renderObject.getDrawParameters();
  42063. if ( drawParams === null ) return;
  42064. //
  42065. this._bindUniforms( renderObject.getBindings() );
  42066. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  42067. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  42068. state.useProgram( programGPU );
  42069. //
  42070. const renderObjectData = this.get( renderObject );
  42071. let vaoGPU = renderObjectData.staticVao;
  42072. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  42073. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  42074. vaoGPU = this.vaoCache[ vaoKey ];
  42075. if ( vaoGPU === undefined ) {
  42076. let staticVao;
  42077. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  42078. if ( staticVao ) {
  42079. renderObjectData.staticVao = vaoGPU;
  42080. renderObjectData.geometryId = renderObject.geometry.id;
  42081. }
  42082. }
  42083. }
  42084. gl.bindVertexArray( vaoGPU );
  42085. //
  42086. const index = renderObject.getIndex();
  42087. //
  42088. const lastObject = contextData.lastOcclusionObject;
  42089. if ( lastObject !== object && lastObject !== undefined ) {
  42090. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42091. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42092. contextData.occlusionQueryIndex ++;
  42093. }
  42094. if ( object.occlusionTest === true ) {
  42095. const query = gl.createQuery();
  42096. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  42097. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  42098. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42099. }
  42100. contextData.lastOcclusionObject = object;
  42101. }
  42102. //
  42103. const renderer = this.bufferRenderer;
  42104. if ( object.isPoints ) renderer.mode = gl.POINTS;
  42105. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  42106. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  42107. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  42108. else {
  42109. if ( material.wireframe === true ) {
  42110. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  42111. renderer.mode = gl.LINES;
  42112. } else {
  42113. renderer.mode = gl.TRIANGLES;
  42114. }
  42115. }
  42116. //
  42117. const { vertexCount, instanceCount } = drawParams;
  42118. let { firstVertex } = drawParams;
  42119. renderer.object = object;
  42120. if ( index !== null ) {
  42121. firstVertex *= index.array.BYTES_PER_ELEMENT;
  42122. const indexData = this.get( index );
  42123. renderer.index = index.count;
  42124. renderer.type = indexData.type;
  42125. } else {
  42126. renderer.index = 0;
  42127. }
  42128. const draw = () => {
  42129. if ( object.isBatchedMesh ) {
  42130. if ( object._multiDrawInstances !== null ) {
  42131. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  42132. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  42133. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  42134. } else {
  42135. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  42136. }
  42137. } else if ( instanceCount > 1 ) {
  42138. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  42139. } else {
  42140. renderer.render( firstVertex, vertexCount );
  42141. }
  42142. };
  42143. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  42144. const cameraData = this.get( renderObject.camera );
  42145. const cameras = renderObject.camera.cameras;
  42146. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  42147. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  42148. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  42149. const indexesGPU = [];
  42150. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42151. const bufferGPU = gl.createBuffer();
  42152. data[ 0 ] = i;
  42153. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42154. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  42155. indexesGPU.push( bufferGPU );
  42156. }
  42157. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  42158. }
  42159. const cameraIndexData = this.get( cameraIndex );
  42160. const pixelRatio = this.renderer.getPixelRatio();
  42161. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42162. const subCamera = cameras[ i ];
  42163. if ( object.layers.test( subCamera.layers ) ) {
  42164. const vp = subCamera.viewport;
  42165. const x = vp.x * pixelRatio;
  42166. const y = vp.y * pixelRatio;
  42167. const width = vp.width * pixelRatio;
  42168. const height = vp.height * pixelRatio;
  42169. state.viewport(
  42170. Math.floor( x ),
  42171. Math.floor( renderObject.context.height - height - y ),
  42172. Math.floor( width ),
  42173. Math.floor( height )
  42174. );
  42175. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  42176. draw();
  42177. }
  42178. }
  42179. } else {
  42180. draw();
  42181. }
  42182. //
  42183. gl.bindVertexArray( null );
  42184. }
  42185. /**
  42186. * Explain why always null is returned.
  42187. *
  42188. * @param {RenderObject} renderObject - The render object.
  42189. * @return {boolean} Whether the render pipeline requires an update or not.
  42190. */
  42191. needsRenderUpdate( /*renderObject*/ ) {
  42192. return false;
  42193. }
  42194. /**
  42195. * Explain why no cache key is computed.
  42196. *
  42197. * @param {RenderObject} renderObject - The render object.
  42198. * @return {string} The cache key.
  42199. */
  42200. getRenderCacheKey( /*renderObject*/ ) {
  42201. return '';
  42202. }
  42203. // textures
  42204. /**
  42205. * Creates a default texture for the given texture that can be used
  42206. * as a placeholder until the actual texture is ready for usage.
  42207. *
  42208. * @param {Texture} texture - The texture to create a default texture for.
  42209. */
  42210. createDefaultTexture( texture ) {
  42211. this.textureUtils.createDefaultTexture( texture );
  42212. }
  42213. /**
  42214. * Defines a texture on the GPU for the given texture object.
  42215. *
  42216. * @param {Texture} texture - The texture.
  42217. * @param {Object} [options={}] - Optional configuration parameter.
  42218. */
  42219. createTexture( texture, options ) {
  42220. this.textureUtils.createTexture( texture, options );
  42221. }
  42222. /**
  42223. * Uploads the updated texture data to the GPU.
  42224. *
  42225. * @param {Texture} texture - The texture.
  42226. * @param {Object} [options={}] - Optional configuration parameter.
  42227. */
  42228. updateTexture( texture, options ) {
  42229. this.textureUtils.updateTexture( texture, options );
  42230. }
  42231. /**
  42232. * Generates mipmaps for the given texture.
  42233. *
  42234. * @param {Texture} texture - The texture.
  42235. */
  42236. generateMipmaps( texture ) {
  42237. this.textureUtils.generateMipmaps( texture );
  42238. }
  42239. /**
  42240. * Destroys the GPU data for the given texture object.
  42241. *
  42242. * @param {Texture} texture - The texture.
  42243. */
  42244. destroyTexture( texture ) {
  42245. this.textureUtils.destroyTexture( texture );
  42246. }
  42247. /**
  42248. * Returns texture data as a typed array.
  42249. *
  42250. * @async
  42251. * @param {Texture} texture - The texture to copy.
  42252. * @param {number} x - The x coordinate of the copy origin.
  42253. * @param {number} y - The y coordinate of the copy origin.
  42254. * @param {number} width - The width of the copy.
  42255. * @param {number} height - The height of the copy.
  42256. * @param {number} faceIndex - The face index.
  42257. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42258. */
  42259. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42260. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  42261. }
  42262. /**
  42263. * This method does nothing since WebGL 2 has no concept of samplers.
  42264. *
  42265. * @param {Texture} texture - The texture to create the sampler for.
  42266. */
  42267. createSampler( /*texture*/ ) {
  42268. //console.warn( 'Abstract class.' );
  42269. }
  42270. /**
  42271. * This method does nothing since WebGL 2 has no concept of samplers.
  42272. *
  42273. * @param {Texture} texture - The texture to destroy the sampler for.
  42274. */
  42275. destroySampler( /*texture*/ ) {}
  42276. // node builder
  42277. /**
  42278. * Returns a node builder for the given render object.
  42279. *
  42280. * @param {RenderObject} object - The render object.
  42281. * @param {Renderer} renderer - The renderer.
  42282. * @return {GLSLNodeBuilder} The node builder.
  42283. */
  42284. createNodeBuilder( object, renderer ) {
  42285. return new GLSLNodeBuilder( object, renderer );
  42286. }
  42287. // program
  42288. /**
  42289. * Creates a shader program from the given programmable stage.
  42290. *
  42291. * @param {ProgrammableStage} program - The programmable stage.
  42292. */
  42293. createProgram( program ) {
  42294. const gl = this.gl;
  42295. const { stage, code } = program;
  42296. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  42297. gl.shaderSource( shader, code );
  42298. gl.compileShader( shader );
  42299. this.set( program, {
  42300. shaderGPU: shader
  42301. } );
  42302. }
  42303. /**
  42304. * Destroys the shader program of the given programmable stage.
  42305. *
  42306. * @param {ProgrammableStage} program - The programmable stage.
  42307. */
  42308. destroyProgram( program ) {
  42309. this.delete( program );
  42310. }
  42311. /**
  42312. * Creates a render pipeline for the given render object.
  42313. *
  42314. * @param {RenderObject} renderObject - The render object.
  42315. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42316. */
  42317. createRenderPipeline( renderObject, promises ) {
  42318. const gl = this.gl;
  42319. const pipeline = renderObject.pipeline;
  42320. // Program
  42321. const { fragmentProgram, vertexProgram } = pipeline;
  42322. const programGPU = gl.createProgram();
  42323. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42324. const vertexShader = this.get( vertexProgram ).shaderGPU;
  42325. gl.attachShader( programGPU, fragmentShader );
  42326. gl.attachShader( programGPU, vertexShader );
  42327. gl.linkProgram( programGPU );
  42328. this.set( pipeline, {
  42329. programGPU,
  42330. fragmentShader,
  42331. vertexShader
  42332. } );
  42333. if ( promises !== null && this.parallel ) {
  42334. const p = new Promise( ( resolve /*, reject*/ ) => {
  42335. const parallel = this.parallel;
  42336. const checkStatus = () => {
  42337. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  42338. this._completeCompile( renderObject, pipeline );
  42339. resolve();
  42340. } else {
  42341. requestAnimationFrame( checkStatus );
  42342. }
  42343. };
  42344. checkStatus();
  42345. } );
  42346. promises.push( p );
  42347. return;
  42348. }
  42349. this._completeCompile( renderObject, pipeline );
  42350. }
  42351. /**
  42352. * Formats the source code of error messages.
  42353. *
  42354. * @private
  42355. * @param {string} string - The code.
  42356. * @param {number} errorLine - The error line.
  42357. * @return {string} The formatted code.
  42358. */
  42359. _handleSource( string, errorLine ) {
  42360. const lines = string.split( '\n' );
  42361. const lines2 = [];
  42362. const from = Math.max( errorLine - 6, 0 );
  42363. const to = Math.min( errorLine + 6, lines.length );
  42364. for ( let i = from; i < to; i ++ ) {
  42365. const line = i + 1;
  42366. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  42367. }
  42368. return lines2.join( '\n' );
  42369. }
  42370. /**
  42371. * Gets the shader compilation errors from the info log.
  42372. *
  42373. * @private
  42374. * @param {WebGL2RenderingContext} gl - The rendering context.
  42375. * @param {WebGLShader} shader - The WebGL shader object.
  42376. * @param {string} type - The shader type.
  42377. * @return {string} The shader errors.
  42378. */
  42379. _getShaderErrors( gl, shader, type ) {
  42380. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  42381. const errors = gl.getShaderInfoLog( shader ).trim();
  42382. if ( status && errors === '' ) return '';
  42383. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  42384. if ( errorMatches ) {
  42385. const errorLine = parseInt( errorMatches[ 1 ] );
  42386. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  42387. } else {
  42388. return errors;
  42389. }
  42390. }
  42391. /**
  42392. * Logs shader compilation errors.
  42393. *
  42394. * @private
  42395. * @param {WebGLProgram} programGPU - The WebGL program.
  42396. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  42397. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  42398. */
  42399. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  42400. if ( this.renderer.debug.checkShaderErrors ) {
  42401. const gl = this.gl;
  42402. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  42403. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42404. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  42405. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  42406. } else {
  42407. // default error reporting
  42408. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  42409. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  42410. console.error(
  42411. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  42412. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  42413. 'Program Info Log: ' + programLog + '\n' +
  42414. vertexErrors + '\n' +
  42415. fragmentErrors
  42416. );
  42417. }
  42418. } else if ( programLog !== '' ) {
  42419. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  42420. }
  42421. }
  42422. }
  42423. /**
  42424. * Completes the shader program setup for the given render object.
  42425. *
  42426. * @private
  42427. * @param {RenderObject} renderObject - The render object.
  42428. * @param {RenderPipeline} pipeline - The render pipeline.
  42429. */
  42430. _completeCompile( renderObject, pipeline ) {
  42431. const { state, gl } = this;
  42432. const pipelineData = this.get( pipeline );
  42433. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  42434. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42435. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42436. }
  42437. state.useProgram( programGPU );
  42438. // Bindings
  42439. const bindings = renderObject.getBindings();
  42440. this._setupBindings( bindings, programGPU );
  42441. //
  42442. this.set( pipeline, {
  42443. programGPU
  42444. } );
  42445. }
  42446. /**
  42447. * Creates a compute pipeline for the given compute node.
  42448. *
  42449. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42450. * @param {Array<BindGroup>} bindings - The bindings.
  42451. */
  42452. createComputePipeline( computePipeline, bindings ) {
  42453. const { state, gl } = this;
  42454. // Program
  42455. const fragmentProgram = {
  42456. stage: 'fragment',
  42457. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  42458. };
  42459. this.createProgram( fragmentProgram );
  42460. const { computeProgram } = computePipeline;
  42461. const programGPU = gl.createProgram();
  42462. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42463. const vertexShader = this.get( computeProgram ).shaderGPU;
  42464. const transforms = computeProgram.transforms;
  42465. const transformVaryingNames = [];
  42466. const transformAttributeNodes = [];
  42467. for ( let i = 0; i < transforms.length; i ++ ) {
  42468. const transform = transforms[ i ];
  42469. transformVaryingNames.push( transform.varyingName );
  42470. transformAttributeNodes.push( transform.attributeNode );
  42471. }
  42472. gl.attachShader( programGPU, fragmentShader );
  42473. gl.attachShader( programGPU, vertexShader );
  42474. gl.transformFeedbackVaryings(
  42475. programGPU,
  42476. transformVaryingNames,
  42477. gl.SEPARATE_ATTRIBS
  42478. );
  42479. gl.linkProgram( programGPU );
  42480. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42481. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42482. }
  42483. state.useProgram( programGPU );
  42484. // Bindings
  42485. this._setupBindings( bindings, programGPU );
  42486. const attributeNodes = computeProgram.attributes;
  42487. const attributes = [];
  42488. const transformBuffers = [];
  42489. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  42490. const attribute = attributeNodes[ i ].node.attribute;
  42491. attributes.push( attribute );
  42492. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42493. }
  42494. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  42495. const attribute = transformAttributeNodes[ i ].attribute;
  42496. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42497. const attributeData = this.get( attribute );
  42498. transformBuffers.push( attributeData );
  42499. }
  42500. //
  42501. this.set( computePipeline, {
  42502. programGPU,
  42503. transformBuffers,
  42504. attributes
  42505. } );
  42506. }
  42507. /**
  42508. * Creates bindings from the given bind group definition.
  42509. *
  42510. * @param {BindGroup} bindGroup - The bind group.
  42511. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42512. * @param {number} cacheIndex - The cache index.
  42513. * @param {number} version - The version.
  42514. */
  42515. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  42516. if ( this._knownBindings.has( bindings ) === false ) {
  42517. this._knownBindings.add( bindings );
  42518. let uniformBuffers = 0;
  42519. let textures = 0;
  42520. for ( const bindGroup of bindings ) {
  42521. this.set( bindGroup, {
  42522. textures: textures,
  42523. uniformBuffers: uniformBuffers
  42524. } );
  42525. for ( const binding of bindGroup.bindings ) {
  42526. if ( binding.isUniformBuffer ) uniformBuffers ++;
  42527. if ( binding.isSampledTexture ) textures ++;
  42528. }
  42529. }
  42530. }
  42531. this.updateBindings( bindGroup, bindings );
  42532. }
  42533. /**
  42534. * Updates the given bind group definition.
  42535. *
  42536. * @param {BindGroup} bindGroup - The bind group.
  42537. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42538. * @param {number} cacheIndex - The cache index.
  42539. * @param {number} version - The version.
  42540. */
  42541. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  42542. const { gl } = this;
  42543. const bindGroupData = this.get( bindGroup );
  42544. let i = bindGroupData.uniformBuffers;
  42545. let t = bindGroupData.textures;
  42546. for ( const binding of bindGroup.bindings ) {
  42547. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42548. const data = binding.buffer;
  42549. const bufferGPU = gl.createBuffer();
  42550. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42551. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42552. this.set( binding, {
  42553. index: i ++,
  42554. bufferGPU
  42555. } );
  42556. } else if ( binding.isSampledTexture ) {
  42557. const { textureGPU, glTextureType } = this.get( binding.texture );
  42558. this.set( binding, {
  42559. index: t ++,
  42560. textureGPU,
  42561. glTextureType
  42562. } );
  42563. }
  42564. }
  42565. }
  42566. /**
  42567. * Updates a buffer binding.
  42568. *
  42569. * @param {Buffer} binding - The buffer binding to update.
  42570. */
  42571. updateBinding( binding ) {
  42572. const gl = this.gl;
  42573. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42574. const bindingData = this.get( binding );
  42575. const bufferGPU = bindingData.bufferGPU;
  42576. const data = binding.buffer;
  42577. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42578. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42579. }
  42580. }
  42581. // attributes
  42582. /**
  42583. * Creates the GPU buffer of an indexed shader attribute.
  42584. *
  42585. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  42586. */
  42587. createIndexAttribute( attribute ) {
  42588. const gl = this.gl;
  42589. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  42590. }
  42591. /**
  42592. * Creates the GPU buffer of a shader attribute.
  42593. *
  42594. * @param {BufferAttribute} attribute - The buffer attribute.
  42595. */
  42596. createAttribute( attribute ) {
  42597. if ( this.has( attribute ) ) return;
  42598. const gl = this.gl;
  42599. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42600. }
  42601. /**
  42602. * Creates the GPU buffer of a storage attribute.
  42603. *
  42604. * @param {BufferAttribute} attribute - The buffer attribute.
  42605. */
  42606. createStorageAttribute( attribute ) {
  42607. if ( this.has( attribute ) ) return;
  42608. const gl = this.gl;
  42609. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42610. }
  42611. /**
  42612. * Updates the GPU buffer of a shader attribute.
  42613. *
  42614. * @param {BufferAttribute} attribute - The buffer attribute to update.
  42615. */
  42616. updateAttribute( attribute ) {
  42617. this.attributeUtils.updateAttribute( attribute );
  42618. }
  42619. /**
  42620. * Destroys the GPU buffer of a shader attribute.
  42621. *
  42622. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  42623. */
  42624. destroyAttribute( attribute ) {
  42625. this.attributeUtils.destroyAttribute( attribute );
  42626. }
  42627. /**
  42628. * Checks if the given feature is supported by the backend.
  42629. *
  42630. * @param {string} name - The feature's name.
  42631. * @return {boolean} Whether the feature is supported or not.
  42632. */
  42633. hasFeature( name ) {
  42634. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  42635. const extensions = this.extensions;
  42636. for ( let i = 0; i < keysMatching.length; i ++ ) {
  42637. if ( extensions.has( keysMatching[ i ] ) ) return true;
  42638. }
  42639. return false;
  42640. }
  42641. /**
  42642. * Returns the maximum anisotropy texture filtering value.
  42643. *
  42644. * @return {number} The maximum anisotropy texture filtering value.
  42645. */
  42646. getMaxAnisotropy() {
  42647. return this.capabilities.getMaxAnisotropy();
  42648. }
  42649. /**
  42650. * Copies data of the given source texture to the given destination texture.
  42651. *
  42652. * @param {Texture} srcTexture - The source texture.
  42653. * @param {Texture} dstTexture - The destination texture.
  42654. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  42655. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42656. * @param {number} [level=0] - The mip level to copy.
  42657. */
  42658. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  42659. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  42660. }
  42661. /**
  42662. * Copies the current bound framebuffer to the given texture.
  42663. *
  42664. * @param {Texture} texture - The destination texture.
  42665. * @param {RenderContext} renderContext - The render context.
  42666. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42667. */
  42668. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42669. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  42670. }
  42671. /**
  42672. * Configures the active framebuffer from the given render context.
  42673. *
  42674. * @private
  42675. * @param {RenderContext} descriptor - The render context.
  42676. */
  42677. _setFramebuffer( descriptor ) {
  42678. const { gl, state } = this;
  42679. let currentFrameBuffer = null;
  42680. if ( descriptor.textures !== null ) {
  42681. const renderTarget = descriptor.renderTarget;
  42682. const renderTargetContextData = this.get( renderTarget );
  42683. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  42684. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  42685. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  42686. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  42687. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  42688. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  42689. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  42690. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  42691. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42692. const useMultisampledRTT = this._useMultisampledRTT( renderTarget );
  42693. const cacheKey = getCacheKey( descriptor );
  42694. let fb;
  42695. if ( isCube ) {
  42696. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  42697. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  42698. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  42699. fb = this._xrFamebuffer;
  42700. } else {
  42701. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  42702. fb = renderTargetContextData.framebuffers[ cacheKey ];
  42703. }
  42704. if ( fb === undefined ) {
  42705. fb = gl.createFramebuffer();
  42706. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42707. const textures = descriptor.textures;
  42708. if ( isCube ) {
  42709. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  42710. const { textureGPU } = this.get( textures[ 0 ] );
  42711. const cubeFace = this.renderer._activeCubeFace;
  42712. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  42713. } else {
  42714. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  42715. for ( let i = 0; i < textures.length; i ++ ) {
  42716. const texture = textures[ i ];
  42717. const textureData = this.get( texture );
  42718. textureData.renderTarget = descriptor.renderTarget;
  42719. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  42720. const attachment = gl.COLOR_ATTACHMENT0 + i;
  42721. if ( isRenderTarget3D || isRenderTargetArray ) {
  42722. const layer = this.renderer._activeCubeFace;
  42723. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  42724. } else {
  42725. if ( useMultisampledRTT ) {
  42726. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42727. } else {
  42728. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42729. }
  42730. }
  42731. }
  42732. state.drawBuffers( descriptor, fb );
  42733. }
  42734. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  42735. const renderbuffer = gl.createRenderbuffer();
  42736. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  42737. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  42738. } else {
  42739. if ( descriptor.depthTexture !== null ) {
  42740. const textureData = this.get( descriptor.depthTexture );
  42741. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42742. textureData.renderTarget = descriptor.renderTarget;
  42743. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  42744. if ( useMultisampledRTT ) {
  42745. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42746. } else {
  42747. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42748. }
  42749. }
  42750. }
  42751. } else {
  42752. // rebind external XR textures
  42753. if ( isXRRenderTarget && hasExternalTextures ) {
  42754. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42755. // rebind color
  42756. const textureData = this.get( descriptor.textures[ 0 ] );
  42757. if ( useMultisampledRTT ) {
  42758. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42759. } else {
  42760. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42761. }
  42762. // rebind depth
  42763. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42764. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  42765. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  42766. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42767. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  42768. } else {
  42769. const textureData = this.get( descriptor.depthTexture );
  42770. if ( useMultisampledRTT ) {
  42771. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42772. } else {
  42773. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42774. }
  42775. }
  42776. }
  42777. }
  42778. if ( samples > 0 && useMultisampledRTT === false ) {
  42779. if ( msaaFb === undefined ) {
  42780. const invalidationArray = [];
  42781. msaaFb = gl.createFramebuffer();
  42782. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  42783. const msaaRenderbuffers = [];
  42784. const textures = descriptor.textures;
  42785. for ( let i = 0; i < textures.length; i ++ ) {
  42786. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  42787. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42788. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  42789. if ( depthBuffer ) {
  42790. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42791. invalidationArray.push( depthStyle );
  42792. }
  42793. const texture = descriptor.textures[ i ];
  42794. const textureData = this.get( texture );
  42795. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  42796. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42797. }
  42798. renderTargetContextData.msaaFrameBuffer = msaaFb;
  42799. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  42800. if ( depthRenderbuffer === undefined ) {
  42801. depthRenderbuffer = gl.createRenderbuffer();
  42802. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  42803. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  42804. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42805. invalidationArray.push( depthStyle );
  42806. }
  42807. renderTargetContextData.invalidationArray = invalidationArray;
  42808. }
  42809. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42810. } else {
  42811. currentFrameBuffer = fb;
  42812. }
  42813. }
  42814. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  42815. }
  42816. /**
  42817. * Computes the VAO key for the given index and attributes.
  42818. *
  42819. * @private
  42820. * @param {?BufferAttribute} index - The index. `null` for non-indexed geometries.
  42821. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42822. * @return {string} The VAO key.
  42823. */
  42824. _getVaoKey( index, attributes ) {
  42825. let key = '';
  42826. if ( index !== null ) {
  42827. const indexData = this.get( index );
  42828. key += ':' + indexData.id;
  42829. }
  42830. for ( let i = 0; i < attributes.length; i ++ ) {
  42831. const attributeData = this.get( attributes[ i ] );
  42832. key += ':' + attributeData.id;
  42833. }
  42834. return key;
  42835. }
  42836. /**
  42837. * Creates a VAO from the index and attributes.
  42838. *
  42839. * @private
  42840. * @param {?BufferAttribute} index - The index. `null` for non-indexed geometries.
  42841. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42842. * @return {Object} The VAO data.
  42843. */
  42844. _createVao( index, attributes ) {
  42845. const { gl } = this;
  42846. const vaoGPU = gl.createVertexArray();
  42847. let key = '';
  42848. let staticVao = true;
  42849. gl.bindVertexArray( vaoGPU );
  42850. if ( index !== null ) {
  42851. const indexData = this.get( index );
  42852. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  42853. key += ':' + indexData.id;
  42854. }
  42855. for ( let i = 0; i < attributes.length; i ++ ) {
  42856. const attribute = attributes[ i ];
  42857. const attributeData = this.get( attribute );
  42858. key += ':' + attributeData.id;
  42859. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  42860. gl.enableVertexAttribArray( i );
  42861. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  42862. let stride, offset;
  42863. if ( attribute.isInterleavedBufferAttribute === true ) {
  42864. stride = attribute.data.stride * attributeData.bytesPerElement;
  42865. offset = attribute.offset * attributeData.bytesPerElement;
  42866. } else {
  42867. stride = 0;
  42868. offset = 0;
  42869. }
  42870. if ( attributeData.isInteger ) {
  42871. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  42872. } else {
  42873. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  42874. }
  42875. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  42876. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  42877. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  42878. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  42879. }
  42880. }
  42881. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  42882. this.vaoCache[ key ] = vaoGPU;
  42883. return { vaoGPU, staticVao };
  42884. }
  42885. /**
  42886. * Creates a transform feedback from the given transform buffers.
  42887. *
  42888. * @private
  42889. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  42890. * @return {WebGLTransformFeedback} The transform feedback.
  42891. */
  42892. _getTransformFeedback( transformBuffers ) {
  42893. let key = '';
  42894. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42895. key += ':' + transformBuffers[ i ].id;
  42896. }
  42897. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  42898. if ( transformFeedbackGPU !== undefined ) {
  42899. return transformFeedbackGPU;
  42900. }
  42901. const { gl } = this;
  42902. transformFeedbackGPU = gl.createTransformFeedback();
  42903. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42904. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42905. const attributeData = transformBuffers[ i ];
  42906. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  42907. }
  42908. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42909. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  42910. return transformFeedbackGPU;
  42911. }
  42912. /**
  42913. * Setups the given bindings.
  42914. *
  42915. * @private
  42916. * @param {Array<BindGroup>} bindings - The bindings.
  42917. * @param {WebGLProgram} programGPU - The WebGL program.
  42918. */
  42919. _setupBindings( bindings, programGPU ) {
  42920. const gl = this.gl;
  42921. for ( const bindGroup of bindings ) {
  42922. for ( const binding of bindGroup.bindings ) {
  42923. const bindingData = this.get( binding );
  42924. const index = bindingData.index;
  42925. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42926. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  42927. gl.uniformBlockBinding( programGPU, location, index );
  42928. } else if ( binding.isSampledTexture ) {
  42929. const location = gl.getUniformLocation( programGPU, binding.name );
  42930. gl.uniform1i( location, index );
  42931. }
  42932. }
  42933. }
  42934. }
  42935. /**
  42936. * Binds the given uniforms.
  42937. *
  42938. * @private
  42939. * @param {Array<BindGroup>} bindings - The bindings.
  42940. */
  42941. _bindUniforms( bindings ) {
  42942. const { gl, state } = this;
  42943. for ( const bindGroup of bindings ) {
  42944. for ( const binding of bindGroup.bindings ) {
  42945. const bindingData = this.get( binding );
  42946. const index = bindingData.index;
  42947. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42948. // TODO USE bindBufferRange to group multiple uniform buffers
  42949. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  42950. } else if ( binding.isSampledTexture ) {
  42951. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  42952. }
  42953. }
  42954. }
  42955. }
  42956. /**
  42957. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  42958. * should be used when MSAA is enabled.
  42959. *
  42960. * @private
  42961. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  42962. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  42963. */
  42964. _useMultisampledRTT( renderTarget ) {
  42965. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  42966. }
  42967. /**
  42968. * Frees internal resources.
  42969. */
  42970. dispose() {
  42971. const extension = this.extensions.get( 'WEBGL_lose_context' );
  42972. if ( extension ) extension.loseContext();
  42973. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  42974. }
  42975. }
  42976. const GPUPrimitiveTopology = {
  42977. PointList: 'point-list',
  42978. LineList: 'line-list',
  42979. LineStrip: 'line-strip',
  42980. TriangleList: 'triangle-list',
  42981. TriangleStrip: 'triangle-strip',
  42982. };
  42983. const GPUCompareFunction = {
  42984. Never: 'never',
  42985. Less: 'less',
  42986. Equal: 'equal',
  42987. LessEqual: 'less-equal',
  42988. Greater: 'greater',
  42989. NotEqual: 'not-equal',
  42990. GreaterEqual: 'greater-equal',
  42991. Always: 'always'
  42992. };
  42993. const GPUStoreOp = {
  42994. Store: 'store'};
  42995. const GPULoadOp = {
  42996. Load: 'load',
  42997. Clear: 'clear'
  42998. };
  42999. const GPUFrontFace = {
  43000. CCW: 'ccw'};
  43001. const GPUCullMode = {
  43002. None: 'none',
  43003. Front: 'front',
  43004. Back: 'back'
  43005. };
  43006. const GPUIndexFormat = {
  43007. Uint16: 'uint16',
  43008. Uint32: 'uint32'
  43009. };
  43010. const GPUTextureFormat = {
  43011. // 8-bit formats
  43012. R8Unorm: 'r8unorm',
  43013. R8Snorm: 'r8snorm',
  43014. R8Uint: 'r8uint',
  43015. R8Sint: 'r8sint',
  43016. // 16-bit formats
  43017. R16Uint: 'r16uint',
  43018. R16Sint: 'r16sint',
  43019. R16Float: 'r16float',
  43020. RG8Unorm: 'rg8unorm',
  43021. RG8Snorm: 'rg8snorm',
  43022. RG8Uint: 'rg8uint',
  43023. RG8Sint: 'rg8sint',
  43024. // 32-bit formats
  43025. R32Uint: 'r32uint',
  43026. R32Sint: 'r32sint',
  43027. R32Float: 'r32float',
  43028. RG16Uint: 'rg16uint',
  43029. RG16Sint: 'rg16sint',
  43030. RG16Float: 'rg16float',
  43031. RGBA8Unorm: 'rgba8unorm',
  43032. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  43033. RGBA8Snorm: 'rgba8snorm',
  43034. RGBA8Uint: 'rgba8uint',
  43035. RGBA8Sint: 'rgba8sint',
  43036. BGRA8Unorm: 'bgra8unorm',
  43037. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  43038. // Packed 32-bit formats
  43039. RGB9E5UFloat: 'rgb9e5ufloat',
  43040. RGB10A2Unorm: 'rgb10a2unorm',
  43041. // 64-bit formats
  43042. RG32Uint: 'rg32uint',
  43043. RG32Sint: 'rg32sint',
  43044. RG32Float: 'rg32float',
  43045. RGBA16Uint: 'rgba16uint',
  43046. RGBA16Sint: 'rgba16sint',
  43047. RGBA16Float: 'rgba16float',
  43048. // 128-bit formats
  43049. RGBA32Uint: 'rgba32uint',
  43050. RGBA32Sint: 'rgba32sint',
  43051. RGBA32Float: 'rgba32float',
  43052. Depth16Unorm: 'depth16unorm',
  43053. Depth24Plus: 'depth24plus',
  43054. Depth24PlusStencil8: 'depth24plus-stencil8',
  43055. Depth32Float: 'depth32float',
  43056. // 'depth32float-stencil8' extension
  43057. Depth32FloatStencil8: 'depth32float-stencil8',
  43058. // BC compressed formats usable if 'texture-compression-bc' is both
  43059. // supported by the device/user agent and enabled in requestDevice.
  43060. BC1RGBAUnorm: 'bc1-rgba-unorm',
  43061. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  43062. BC2RGBAUnorm: 'bc2-rgba-unorm',
  43063. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  43064. BC3RGBAUnorm: 'bc3-rgba-unorm',
  43065. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  43066. BC4RUnorm: 'bc4-r-unorm',
  43067. BC5RGUnorm: 'bc5-rg-unorm',
  43068. BC5RGSnorm: 'bc5-rg-snorm',
  43069. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  43070. BC6HRGBFloat: 'bc6h-rgb-float',
  43071. BC7RGBAUnorm: 'bc7-rgba-unorm',
  43072. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  43073. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  43074. // supported by the device/user agent and enabled in requestDevice.
  43075. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  43076. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  43077. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  43078. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  43079. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  43080. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  43081. EACR11Unorm: 'eac-r11unorm',
  43082. EACR11Snorm: 'eac-r11snorm',
  43083. EACRG11Unorm: 'eac-rg11unorm',
  43084. EACRG11Snorm: 'eac-rg11snorm',
  43085. // ASTC compressed formats usable if 'texture-compression-astc' is both
  43086. // supported by the device/user agent and enabled in requestDevice.
  43087. ASTC4x4Unorm: 'astc-4x4-unorm',
  43088. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  43089. ASTC5x4Unorm: 'astc-5x4-unorm',
  43090. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  43091. ASTC5x5Unorm: 'astc-5x5-unorm',
  43092. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  43093. ASTC6x5Unorm: 'astc-6x5-unorm',
  43094. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  43095. ASTC6x6Unorm: 'astc-6x6-unorm',
  43096. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  43097. ASTC8x5Unorm: 'astc-8x5-unorm',
  43098. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  43099. ASTC8x6Unorm: 'astc-8x6-unorm',
  43100. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  43101. ASTC8x8Unorm: 'astc-8x8-unorm',
  43102. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  43103. ASTC10x5Unorm: 'astc-10x5-unorm',
  43104. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  43105. ASTC10x6Unorm: 'astc-10x6-unorm',
  43106. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  43107. ASTC10x8Unorm: 'astc-10x8-unorm',
  43108. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  43109. ASTC10x10Unorm: 'astc-10x10-unorm',
  43110. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  43111. ASTC12x10Unorm: 'astc-12x10-unorm',
  43112. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  43113. ASTC12x12Unorm: 'astc-12x12-unorm',
  43114. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  43115. };
  43116. const GPUAddressMode = {
  43117. ClampToEdge: 'clamp-to-edge',
  43118. Repeat: 'repeat',
  43119. MirrorRepeat: 'mirror-repeat'
  43120. };
  43121. const GPUFilterMode = {
  43122. Linear: 'linear',
  43123. Nearest: 'nearest'
  43124. };
  43125. const GPUBlendFactor = {
  43126. Zero: 'zero',
  43127. One: 'one',
  43128. Src: 'src',
  43129. OneMinusSrc: 'one-minus-src',
  43130. SrcAlpha: 'src-alpha',
  43131. OneMinusSrcAlpha: 'one-minus-src-alpha',
  43132. Dst: 'dst',
  43133. OneMinusDstColor: 'one-minus-dst',
  43134. DstAlpha: 'dst-alpha',
  43135. OneMinusDstAlpha: 'one-minus-dst-alpha',
  43136. SrcAlphaSaturated: 'src-alpha-saturated',
  43137. Constant: 'constant',
  43138. OneMinusConstant: 'one-minus-constant'
  43139. };
  43140. const GPUBlendOperation = {
  43141. Add: 'add',
  43142. Subtract: 'subtract',
  43143. ReverseSubtract: 'reverse-subtract',
  43144. Min: 'min',
  43145. Max: 'max'
  43146. };
  43147. const GPUColorWriteFlags = {
  43148. None: 0,
  43149. All: 0xF
  43150. };
  43151. const GPUStencilOperation = {
  43152. Keep: 'keep',
  43153. Zero: 'zero',
  43154. Replace: 'replace',
  43155. Invert: 'invert',
  43156. IncrementClamp: 'increment-clamp',
  43157. DecrementClamp: 'decrement-clamp',
  43158. IncrementWrap: 'increment-wrap',
  43159. DecrementWrap: 'decrement-wrap'
  43160. };
  43161. const GPUBufferBindingType = {
  43162. Storage: 'storage',
  43163. ReadOnlyStorage: 'read-only-storage'
  43164. };
  43165. const GPUStorageTextureAccess = {
  43166. WriteOnly: 'write-only',
  43167. ReadOnly: 'read-only',
  43168. ReadWrite: 'read-write',
  43169. };
  43170. const GPUTextureSampleType = {
  43171. Float: 'float',
  43172. UnfilterableFloat: 'unfilterable-float',
  43173. Depth: 'depth',
  43174. SInt: 'sint',
  43175. UInt: 'uint'
  43176. };
  43177. const GPUTextureDimension = {
  43178. TwoD: '2d',
  43179. ThreeD: '3d'
  43180. };
  43181. const GPUTextureViewDimension = {
  43182. TwoD: '2d',
  43183. TwoDArray: '2d-array',
  43184. Cube: 'cube',
  43185. ThreeD: '3d'
  43186. };
  43187. const GPUTextureAspect = {
  43188. All: 'all'};
  43189. const GPUInputStepMode = {
  43190. Vertex: 'vertex',
  43191. Instance: 'instance'
  43192. };
  43193. const GPUFeatureName = {
  43194. DepthClipControl: 'depth-clip-control',
  43195. Depth32FloatStencil8: 'depth32float-stencil8',
  43196. TextureCompressionBC: 'texture-compression-bc',
  43197. TextureCompressionETC2: 'texture-compression-etc2',
  43198. TextureCompressionASTC: 'texture-compression-astc',
  43199. TimestampQuery: 'timestamp-query',
  43200. IndirectFirstInstance: 'indirect-first-instance',
  43201. ShaderF16: 'shader-f16',
  43202. RG11B10UFloat: 'rg11b10ufloat-renderable',
  43203. BGRA8UNormStorage: 'bgra8unorm-storage',
  43204. Float32Filterable: 'float32-filterable',
  43205. ClipDistances: 'clip-distances',
  43206. DualSourceBlending: 'dual-source-blending',
  43207. Subgroups: 'subgroups'
  43208. };
  43209. /**
  43210. * Represents a sampler binding type.
  43211. *
  43212. * @private
  43213. * @augments Binding
  43214. */
  43215. class Sampler extends Binding {
  43216. /**
  43217. * Constructs a new sampler.
  43218. *
  43219. * @param {string} name - The samplers's name.
  43220. * @param {?Texture} texture - The texture this binding is referring to.
  43221. */
  43222. constructor( name, texture ) {
  43223. super( name );
  43224. /**
  43225. * The texture the sampler is referring to.
  43226. *
  43227. * @type {?Texture}
  43228. */
  43229. this.texture = texture;
  43230. /**
  43231. * The binding's version.
  43232. *
  43233. * @type {number}
  43234. */
  43235. this.version = texture ? texture.version : 0;
  43236. /**
  43237. * This flag can be used for type testing.
  43238. *
  43239. * @type {boolean}
  43240. * @readonly
  43241. * @default true
  43242. */
  43243. this.isSampler = true;
  43244. }
  43245. }
  43246. /**
  43247. * A special form of sampler binding type.
  43248. * It's texture value is managed by a node object.
  43249. *
  43250. * @private
  43251. * @augments Sampler
  43252. */
  43253. class NodeSampler extends Sampler {
  43254. /**
  43255. * Constructs a new node-based sampler.
  43256. *
  43257. * @param {string} name - The samplers's name.
  43258. * @param {TextureNode} textureNode - The texture node.
  43259. * @param {UniformGroupNode} groupNode - The uniform group node.
  43260. */
  43261. constructor( name, textureNode, groupNode ) {
  43262. super( name, textureNode ? textureNode.value : null );
  43263. /**
  43264. * The texture node.
  43265. *
  43266. * @type {TextureNode}
  43267. */
  43268. this.textureNode = textureNode;
  43269. /**
  43270. * The uniform group node.
  43271. *
  43272. * @type {UniformGroupNode}
  43273. */
  43274. this.groupNode = groupNode;
  43275. }
  43276. /**
  43277. * Updates the texture value of this sampler.
  43278. */
  43279. update() {
  43280. this.texture = this.textureNode.value;
  43281. }
  43282. }
  43283. /**
  43284. * Represents a storage buffer binding type.
  43285. *
  43286. * @private
  43287. * @augments Buffer
  43288. */
  43289. class StorageBuffer extends Buffer {
  43290. /**
  43291. * Constructs a new uniform buffer.
  43292. *
  43293. * @param {string} name - The buffer's name.
  43294. * @param {BufferAttribute} attribute - The buffer attribute.
  43295. */
  43296. constructor( name, attribute ) {
  43297. super( name, attribute ? attribute.array : null );
  43298. /**
  43299. * This flag can be used for type testing.
  43300. *
  43301. * @type {BufferAttribute}
  43302. */
  43303. this.attribute = attribute;
  43304. /**
  43305. * This flag can be used for type testing.
  43306. *
  43307. * @type {boolean}
  43308. * @readonly
  43309. * @default true
  43310. */
  43311. this.isStorageBuffer = true;
  43312. }
  43313. }
  43314. let _id = 0;
  43315. /**
  43316. * A special form of storage buffer binding type.
  43317. * It's buffer value is managed by a node object.
  43318. *
  43319. * @private
  43320. * @augments StorageBuffer
  43321. */
  43322. class NodeStorageBuffer extends StorageBuffer {
  43323. /**
  43324. * Constructs a new node-based storage buffer.
  43325. *
  43326. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  43327. * @param {UniformGroupNode} groupNode - The uniform group node.
  43328. */
  43329. constructor( nodeUniform, groupNode ) {
  43330. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  43331. /**
  43332. * The node uniform.
  43333. *
  43334. * @type {StorageBufferNode}
  43335. */
  43336. this.nodeUniform = nodeUniform;
  43337. /**
  43338. * The access type.
  43339. *
  43340. * @type {string}
  43341. */
  43342. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  43343. /**
  43344. * The uniform group node.
  43345. *
  43346. * @type {UniformGroupNode}
  43347. */
  43348. this.groupNode = groupNode;
  43349. }
  43350. /**
  43351. * The storage buffer.
  43352. *
  43353. * @type {BufferAttribute}
  43354. */
  43355. get buffer() {
  43356. return this.nodeUniform.value;
  43357. }
  43358. }
  43359. /**
  43360. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  43361. *
  43362. * @private
  43363. */
  43364. class WebGPUTexturePassUtils extends DataMap {
  43365. /**
  43366. * Constructs a new utility object.
  43367. *
  43368. * @param {GPUDevice} device - The WebGPU device.
  43369. */
  43370. constructor( device ) {
  43371. super();
  43372. /**
  43373. * The WebGPU device.
  43374. *
  43375. * @type {GPUDevice}
  43376. */
  43377. this.device = device;
  43378. const mipmapVertexSource = `
  43379. struct VarysStruct {
  43380. @builtin( position ) Position: vec4<f32>,
  43381. @location( 0 ) vTex : vec2<f32>
  43382. };
  43383. @vertex
  43384. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  43385. var Varys : VarysStruct;
  43386. var pos = array< vec2<f32>, 4 >(
  43387. vec2<f32>( -1.0, 1.0 ),
  43388. vec2<f32>( 1.0, 1.0 ),
  43389. vec2<f32>( -1.0, -1.0 ),
  43390. vec2<f32>( 1.0, -1.0 )
  43391. );
  43392. var tex = array< vec2<f32>, 4 >(
  43393. vec2<f32>( 0.0, 0.0 ),
  43394. vec2<f32>( 1.0, 0.0 ),
  43395. vec2<f32>( 0.0, 1.0 ),
  43396. vec2<f32>( 1.0, 1.0 )
  43397. );
  43398. Varys.vTex = tex[ vertexIndex ];
  43399. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  43400. return Varys;
  43401. }
  43402. `;
  43403. const mipmapFragmentSource = `
  43404. @group( 0 ) @binding( 0 )
  43405. var imgSampler : sampler;
  43406. @group( 0 ) @binding( 1 )
  43407. var img : texture_2d<f32>;
  43408. @fragment
  43409. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  43410. return textureSample( img, imgSampler, vTex );
  43411. }
  43412. `;
  43413. const flipYFragmentSource = `
  43414. @group( 0 ) @binding( 0 )
  43415. var imgSampler : sampler;
  43416. @group( 0 ) @binding( 1 )
  43417. var img : texture_2d<f32>;
  43418. @fragment
  43419. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  43420. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  43421. }
  43422. `;
  43423. /**
  43424. * The mipmap GPU sampler.
  43425. *
  43426. * @type {GPUSampler}
  43427. */
  43428. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  43429. /**
  43430. * The flipY GPU sampler.
  43431. *
  43432. * @type {GPUSampler}
  43433. */
  43434. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  43435. /**
  43436. * A cache for GPU render pipelines used for copy/transfer passes.
  43437. * Every texture format requires a unique pipeline.
  43438. *
  43439. * @type {Object<string,GPURenderPipeline>}
  43440. */
  43441. this.transferPipelines = {};
  43442. /**
  43443. * A cache for GPU render pipelines used for flipY passes.
  43444. * Every texture format requires a unique pipeline.
  43445. *
  43446. * @type {Object<string,GPURenderPipeline>}
  43447. */
  43448. this.flipYPipelines = {};
  43449. /**
  43450. * The mipmap vertex shader module.
  43451. *
  43452. * @type {GPUShaderModule}
  43453. */
  43454. this.mipmapVertexShaderModule = device.createShaderModule( {
  43455. label: 'mipmapVertex',
  43456. code: mipmapVertexSource
  43457. } );
  43458. /**
  43459. * The mipmap fragment shader module.
  43460. *
  43461. * @type {GPUShaderModule}
  43462. */
  43463. this.mipmapFragmentShaderModule = device.createShaderModule( {
  43464. label: 'mipmapFragment',
  43465. code: mipmapFragmentSource
  43466. } );
  43467. /**
  43468. * The flipY fragment shader module.
  43469. *
  43470. * @type {GPUShaderModule}
  43471. */
  43472. this.flipYFragmentShaderModule = device.createShaderModule( {
  43473. label: 'flipYFragment',
  43474. code: flipYFragmentSource
  43475. } );
  43476. }
  43477. /**
  43478. * Returns a render pipeline for the internal copy render pass. The pass
  43479. * requires a unique render pipeline for each texture format.
  43480. *
  43481. * @param {string} format - The GPU texture format
  43482. * @return {GPURenderPipeline} The GPU render pipeline.
  43483. */
  43484. getTransferPipeline( format ) {
  43485. let pipeline = this.transferPipelines[ format ];
  43486. if ( pipeline === undefined ) {
  43487. pipeline = this.device.createRenderPipeline( {
  43488. label: `mipmap-${ format }`,
  43489. vertex: {
  43490. module: this.mipmapVertexShaderModule,
  43491. entryPoint: 'main'
  43492. },
  43493. fragment: {
  43494. module: this.mipmapFragmentShaderModule,
  43495. entryPoint: 'main',
  43496. targets: [ { format } ]
  43497. },
  43498. primitive: {
  43499. topology: GPUPrimitiveTopology.TriangleStrip,
  43500. stripIndexFormat: GPUIndexFormat.Uint32
  43501. },
  43502. layout: 'auto'
  43503. } );
  43504. this.transferPipelines[ format ] = pipeline;
  43505. }
  43506. return pipeline;
  43507. }
  43508. /**
  43509. * Returns a render pipeline for the flipY render pass. The pass
  43510. * requires a unique render pipeline for each texture format.
  43511. *
  43512. * @param {string} format - The GPU texture format
  43513. * @return {GPURenderPipeline} The GPU render pipeline.
  43514. */
  43515. getFlipYPipeline( format ) {
  43516. let pipeline = this.flipYPipelines[ format ];
  43517. if ( pipeline === undefined ) {
  43518. pipeline = this.device.createRenderPipeline( {
  43519. label: `flipY-${ format }`,
  43520. vertex: {
  43521. module: this.mipmapVertexShaderModule,
  43522. entryPoint: 'main'
  43523. },
  43524. fragment: {
  43525. module: this.flipYFragmentShaderModule,
  43526. entryPoint: 'main',
  43527. targets: [ { format } ]
  43528. },
  43529. primitive: {
  43530. topology: GPUPrimitiveTopology.TriangleStrip,
  43531. stripIndexFormat: GPUIndexFormat.Uint32
  43532. },
  43533. layout: 'auto'
  43534. } );
  43535. this.flipYPipelines[ format ] = pipeline;
  43536. }
  43537. return pipeline;
  43538. }
  43539. /**
  43540. * Flip the contents of the given GPU texture along its vertical axis.
  43541. *
  43542. * @param {GPUTexture} textureGPU - The GPU texture object.
  43543. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43544. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43545. */
  43546. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  43547. const format = textureGPUDescriptor.format;
  43548. const { width, height } = textureGPUDescriptor.size;
  43549. const transferPipeline = this.getTransferPipeline( format );
  43550. const flipYPipeline = this.getFlipYPipeline( format );
  43551. const tempTexture = this.device.createTexture( {
  43552. size: { width, height, depthOrArrayLayers: 1 },
  43553. format,
  43554. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  43555. } );
  43556. const srcView = textureGPU.createView( {
  43557. baseMipLevel: 0,
  43558. mipLevelCount: 1,
  43559. dimension: GPUTextureViewDimension.TwoD,
  43560. baseArrayLayer
  43561. } );
  43562. const dstView = tempTexture.createView( {
  43563. baseMipLevel: 0,
  43564. mipLevelCount: 1,
  43565. dimension: GPUTextureViewDimension.TwoD,
  43566. baseArrayLayer: 0
  43567. } );
  43568. const commandEncoder = this.device.createCommandEncoder( {} );
  43569. const pass = ( pipeline, sourceView, destinationView ) => {
  43570. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  43571. const bindGroup = this.device.createBindGroup( {
  43572. layout: bindGroupLayout,
  43573. entries: [ {
  43574. binding: 0,
  43575. resource: this.flipYSampler
  43576. }, {
  43577. binding: 1,
  43578. resource: sourceView
  43579. } ]
  43580. } );
  43581. const passEncoder = commandEncoder.beginRenderPass( {
  43582. colorAttachments: [ {
  43583. view: destinationView,
  43584. loadOp: GPULoadOp.Clear,
  43585. storeOp: GPUStoreOp.Store,
  43586. clearValue: [ 0, 0, 0, 0 ]
  43587. } ]
  43588. } );
  43589. passEncoder.setPipeline( pipeline );
  43590. passEncoder.setBindGroup( 0, bindGroup );
  43591. passEncoder.draw( 4, 1, 0, 0 );
  43592. passEncoder.end();
  43593. };
  43594. pass( transferPipeline, srcView, dstView );
  43595. pass( flipYPipeline, dstView, srcView );
  43596. this.device.queue.submit( [ commandEncoder.finish() ] );
  43597. tempTexture.destroy();
  43598. }
  43599. /**
  43600. * Generates mipmaps for the given GPU texture.
  43601. *
  43602. * @param {GPUTexture} textureGPU - The GPU texture object.
  43603. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43604. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43605. */
  43606. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  43607. const textureData = this.get( textureGPU );
  43608. if ( textureData.useCount === undefined ) {
  43609. textureData.useCount = 0;
  43610. textureData.layers = [];
  43611. }
  43612. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  43613. const commandEncoder = this.device.createCommandEncoder( {} );
  43614. this._mipmapRunBundles( commandEncoder, passes );
  43615. this.device.queue.submit( [ commandEncoder.finish() ] );
  43616. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  43617. textureData.useCount ++;
  43618. }
  43619. /**
  43620. * Since multiple copy render passes are required to generate mipmaps, the passes
  43621. * are managed as render bundles to improve performance.
  43622. *
  43623. * @param {GPUTexture} textureGPU - The GPU texture object.
  43624. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43625. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  43626. * @return {Array} An array of render bundles.
  43627. */
  43628. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  43629. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  43630. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  43631. let srcView = textureGPU.createView( {
  43632. baseMipLevel: 0,
  43633. mipLevelCount: 1,
  43634. dimension: GPUTextureViewDimension.TwoD,
  43635. baseArrayLayer
  43636. } );
  43637. const passes = [];
  43638. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  43639. const bindGroup = this.device.createBindGroup( {
  43640. layout: bindGroupLayout,
  43641. entries: [ {
  43642. binding: 0,
  43643. resource: this.mipmapSampler
  43644. }, {
  43645. binding: 1,
  43646. resource: srcView
  43647. } ]
  43648. } );
  43649. const dstView = textureGPU.createView( {
  43650. baseMipLevel: i,
  43651. mipLevelCount: 1,
  43652. dimension: GPUTextureViewDimension.TwoD,
  43653. baseArrayLayer
  43654. } );
  43655. const passDescriptor = {
  43656. colorAttachments: [ {
  43657. view: dstView,
  43658. loadOp: GPULoadOp.Clear,
  43659. storeOp: GPUStoreOp.Store,
  43660. clearValue: [ 0, 0, 0, 0 ]
  43661. } ]
  43662. };
  43663. const passEncoder = this.device.createRenderBundleEncoder( {
  43664. colorFormats: [ textureGPUDescriptor.format ]
  43665. } );
  43666. passEncoder.setPipeline( pipeline );
  43667. passEncoder.setBindGroup( 0, bindGroup );
  43668. passEncoder.draw( 4, 1, 0, 0 );
  43669. passes.push( {
  43670. renderBundles: [ passEncoder.finish() ],
  43671. passDescriptor
  43672. } );
  43673. srcView = dstView;
  43674. }
  43675. return passes;
  43676. }
  43677. /**
  43678. * Executes the render bundles.
  43679. *
  43680. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  43681. * @param {Array} passes - An array of render bundles.
  43682. */
  43683. _mipmapRunBundles( commandEncoder, passes ) {
  43684. const levels = passes.length;
  43685. for ( let i = 0; i < levels; i ++ ) {
  43686. const pass = passes[ i ];
  43687. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  43688. passEncoder.executeBundles( pass.renderBundles );
  43689. passEncoder.end();
  43690. }
  43691. }
  43692. }
  43693. const _compareToWebGPU = {
  43694. [ NeverCompare ]: 'never',
  43695. [ LessCompare ]: 'less',
  43696. [ EqualCompare ]: 'equal',
  43697. [ LessEqualCompare ]: 'less-equal',
  43698. [ GreaterCompare ]: 'greater',
  43699. [ GreaterEqualCompare ]: 'greater-equal',
  43700. [ AlwaysCompare ]: 'always',
  43701. [ NotEqualCompare ]: 'not-equal'
  43702. };
  43703. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  43704. /**
  43705. * A WebGPU backend utility module for managing textures.
  43706. *
  43707. * @private
  43708. */
  43709. class WebGPUTextureUtils {
  43710. /**
  43711. * Constructs a new utility object.
  43712. *
  43713. * @param {WebGPUBackend} backend - The WebGPU backend.
  43714. */
  43715. constructor( backend ) {
  43716. /**
  43717. * A reference to the WebGPU backend.
  43718. *
  43719. * @type {WebGPUBackend}
  43720. */
  43721. this.backend = backend;
  43722. /**
  43723. * A reference to the pass utils.
  43724. *
  43725. * @type {?WebGPUTexturePassUtils}
  43726. * @default null
  43727. */
  43728. this._passUtils = null;
  43729. /**
  43730. * A dictionary for managing default textures. The key
  43731. * is the texture format, the value the texture object.
  43732. *
  43733. * @type {Object<string,Texture>}
  43734. */
  43735. this.defaultTexture = {};
  43736. /**
  43737. * A dictionary for managing default cube textures. The key
  43738. * is the texture format, the value the texture object.
  43739. *
  43740. * @type {Object<string,CubeTexture>}
  43741. */
  43742. this.defaultCubeTexture = {};
  43743. /**
  43744. * A default video frame.
  43745. *
  43746. * @type {?VideoFrame}
  43747. * @default null
  43748. */
  43749. this.defaultVideoFrame = null;
  43750. /**
  43751. * Represents the color attachment of the default framebuffer.
  43752. *
  43753. * @type {?GPUTexture}
  43754. * @default null
  43755. */
  43756. this.colorBuffer = null;
  43757. /**
  43758. * Represents the depth attachment of the default framebuffer.
  43759. *
  43760. * @type {DepthTexture}
  43761. */
  43762. this.depthTexture = new DepthTexture();
  43763. this.depthTexture.name = 'depthBuffer';
  43764. }
  43765. /**
  43766. * Creates a GPU sampler for the given texture.
  43767. *
  43768. * @param {Texture} texture - The texture to create the sampler for.
  43769. */
  43770. createSampler( texture ) {
  43771. const backend = this.backend;
  43772. const device = backend.device;
  43773. const textureGPU = backend.get( texture );
  43774. const samplerDescriptorGPU = {
  43775. addressModeU: this._convertAddressMode( texture.wrapS ),
  43776. addressModeV: this._convertAddressMode( texture.wrapT ),
  43777. addressModeW: this._convertAddressMode( texture.wrapR ),
  43778. magFilter: this._convertFilterMode( texture.magFilter ),
  43779. minFilter: this._convertFilterMode( texture.minFilter ),
  43780. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  43781. maxAnisotropy: 1
  43782. };
  43783. // anisotropy can only be used when all filter modes are set to linear.
  43784. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  43785. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  43786. }
  43787. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  43788. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  43789. }
  43790. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  43791. }
  43792. /**
  43793. * Creates a default texture for the given texture that can be used
  43794. * as a placeholder until the actual texture is ready for usage.
  43795. *
  43796. * @param {Texture} texture - The texture to create a default texture for.
  43797. */
  43798. createDefaultTexture( texture ) {
  43799. let textureGPU;
  43800. const format = getFormat( texture );
  43801. if ( texture.isCubeTexture ) {
  43802. textureGPU = this._getDefaultCubeTextureGPU( format );
  43803. } else if ( texture.isVideoTexture ) {
  43804. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  43805. } else {
  43806. textureGPU = this._getDefaultTextureGPU( format );
  43807. }
  43808. this.backend.get( texture ).texture = textureGPU;
  43809. }
  43810. /**
  43811. * Defines a texture on the GPU for the given texture object.
  43812. *
  43813. * @param {Texture} texture - The texture.
  43814. * @param {Object} [options={}] - Optional configuration parameter.
  43815. * @return {undefined}
  43816. */
  43817. createTexture( texture, options = {} ) {
  43818. const backend = this.backend;
  43819. const textureData = backend.get( texture );
  43820. if ( textureData.initialized ) {
  43821. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  43822. }
  43823. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  43824. if ( options.levels === undefined ) options.levels = 1;
  43825. if ( options.depth === undefined ) options.depth = 1;
  43826. const { width, height, depth, levels } = options;
  43827. if ( texture.isFramebufferTexture ) {
  43828. if ( options.renderTarget ) {
  43829. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  43830. } else {
  43831. options.format = this.backend.utils.getPreferredCanvasFormat();
  43832. }
  43833. }
  43834. const dimension = this._getDimension( texture );
  43835. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  43836. textureData.format = format;
  43837. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  43838. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  43839. if ( texture.isStorageTexture === true ) {
  43840. usage |= GPUTextureUsage.STORAGE_BINDING;
  43841. }
  43842. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  43843. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  43844. }
  43845. const textureDescriptorGPU = {
  43846. label: texture.name,
  43847. size: {
  43848. width: width,
  43849. height: height,
  43850. depthOrArrayLayers: depth,
  43851. },
  43852. mipLevelCount: levels,
  43853. sampleCount: primarySamples,
  43854. dimension: dimension,
  43855. format: format,
  43856. usage: usage
  43857. };
  43858. // texture creation
  43859. if ( texture.isVideoTexture ) {
  43860. const video = texture.source.data;
  43861. const videoFrame = new VideoFrame( video );
  43862. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  43863. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  43864. videoFrame.close();
  43865. textureData.externalTexture = video;
  43866. } else {
  43867. if ( format === undefined ) {
  43868. console.warn( 'WebGPURenderer: Texture format not supported.' );
  43869. return this.createDefaultTexture( texture );
  43870. }
  43871. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  43872. }
  43873. if ( isMSAA ) {
  43874. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  43875. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  43876. msaaTextureDescriptorGPU.sampleCount = samples;
  43877. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  43878. }
  43879. textureData.initialized = true;
  43880. textureData.textureDescriptorGPU = textureDescriptorGPU;
  43881. }
  43882. /**
  43883. * Destroys the GPU data for the given texture object.
  43884. *
  43885. * @param {Texture} texture - The texture.
  43886. */
  43887. destroyTexture( texture ) {
  43888. const backend = this.backend;
  43889. const textureData = backend.get( texture );
  43890. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  43891. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  43892. backend.delete( texture );
  43893. }
  43894. /**
  43895. * Destroys the GPU sampler for the given texture.
  43896. *
  43897. * @param {Texture} texture - The texture to destroy the sampler for.
  43898. */
  43899. destroySampler( texture ) {
  43900. const backend = this.backend;
  43901. const textureData = backend.get( texture );
  43902. delete textureData.sampler;
  43903. }
  43904. /**
  43905. * Generates mipmaps for the given texture.
  43906. *
  43907. * @param {Texture} texture - The texture.
  43908. */
  43909. generateMipmaps( texture ) {
  43910. const textureData = this.backend.get( texture );
  43911. if ( texture.isCubeTexture ) {
  43912. for ( let i = 0; i < 6; i ++ ) {
  43913. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43914. }
  43915. } else {
  43916. const depth = texture.image.depth || 1;
  43917. for ( let i = 0; i < depth; i ++ ) {
  43918. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43919. }
  43920. }
  43921. }
  43922. /**
  43923. * Returns the color buffer representing the color
  43924. * attachment of the default framebuffer.
  43925. *
  43926. * @return {GPUTexture} The color buffer.
  43927. */
  43928. getColorBuffer() {
  43929. if ( this.colorBuffer ) this.colorBuffer.destroy();
  43930. const backend = this.backend;
  43931. const { width, height } = backend.getDrawingBufferSize();
  43932. this.colorBuffer = backend.device.createTexture( {
  43933. label: 'colorBuffer',
  43934. size: {
  43935. width: width,
  43936. height: height,
  43937. depthOrArrayLayers: 1
  43938. },
  43939. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  43940. format: backend.utils.getPreferredCanvasFormat(),
  43941. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  43942. } );
  43943. return this.colorBuffer;
  43944. }
  43945. /**
  43946. * Returns the depth buffer representing the depth
  43947. * attachment of the default framebuffer.
  43948. *
  43949. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  43950. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  43951. * @return {GPUTexture} The depth buffer.
  43952. */
  43953. getDepthBuffer( depth = true, stencil = false ) {
  43954. const backend = this.backend;
  43955. const { width, height } = backend.getDrawingBufferSize();
  43956. const depthTexture = this.depthTexture;
  43957. const depthTextureGPU = backend.get( depthTexture ).texture;
  43958. let format, type;
  43959. if ( stencil ) {
  43960. format = DepthStencilFormat;
  43961. type = UnsignedInt248Type;
  43962. } else if ( depth ) {
  43963. format = DepthFormat;
  43964. type = UnsignedIntType;
  43965. }
  43966. if ( depthTextureGPU !== undefined ) {
  43967. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  43968. return depthTextureGPU;
  43969. }
  43970. this.destroyTexture( depthTexture );
  43971. }
  43972. depthTexture.name = 'depthBuffer';
  43973. depthTexture.format = format;
  43974. depthTexture.type = type;
  43975. depthTexture.image.width = width;
  43976. depthTexture.image.height = height;
  43977. this.createTexture( depthTexture, { width, height } );
  43978. return backend.get( depthTexture ).texture;
  43979. }
  43980. /**
  43981. * Uploads the updated texture data to the GPU.
  43982. *
  43983. * @param {Texture} texture - The texture.
  43984. * @param {Object} [options={}] - Optional configuration parameter.
  43985. */
  43986. updateTexture( texture, options ) {
  43987. const textureData = this.backend.get( texture );
  43988. const { textureDescriptorGPU } = textureData;
  43989. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  43990. return;
  43991. // transfer texture data
  43992. if ( texture.isDataTexture ) {
  43993. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43994. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43995. for ( let i = 0; i < options.image.depth; i ++ ) {
  43996. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  43997. }
  43998. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  43999. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  44000. } else if ( texture.isCubeTexture ) {
  44001. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  44002. } else if ( texture.isVideoTexture ) {
  44003. const video = texture.source.data;
  44004. textureData.externalTexture = video;
  44005. } else {
  44006. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  44007. }
  44008. //
  44009. textureData.version = texture.version;
  44010. if ( texture.onUpdate ) texture.onUpdate( texture );
  44011. }
  44012. /**
  44013. * Returns texture data as a typed array.
  44014. *
  44015. * @async
  44016. * @param {Texture} texture - The texture to copy.
  44017. * @param {number} x - The x coordinate of the copy origin.
  44018. * @param {number} y - The y coordinate of the copy origin.
  44019. * @param {number} width - The width of the copy.
  44020. * @param {number} height - The height of the copy.
  44021. * @param {number} faceIndex - The face index.
  44022. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44023. */
  44024. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44025. const device = this.backend.device;
  44026. const textureData = this.backend.get( texture );
  44027. const textureGPU = textureData.texture;
  44028. const format = textureData.textureDescriptorGPU.format;
  44029. const bytesPerTexel = this._getBytesPerTexel( format );
  44030. let bytesPerRow = width * bytesPerTexel;
  44031. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  44032. const readBuffer = device.createBuffer(
  44033. {
  44034. size: width * height * bytesPerTexel,
  44035. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44036. }
  44037. );
  44038. const encoder = device.createCommandEncoder();
  44039. encoder.copyTextureToBuffer(
  44040. {
  44041. texture: textureGPU,
  44042. origin: { x, y, z: faceIndex },
  44043. },
  44044. {
  44045. buffer: readBuffer,
  44046. bytesPerRow: bytesPerRow
  44047. },
  44048. {
  44049. width: width,
  44050. height: height
  44051. }
  44052. );
  44053. const typedArrayType = this._getTypedArrayType( format );
  44054. device.queue.submit( [ encoder.finish() ] );
  44055. await readBuffer.mapAsync( GPUMapMode.READ );
  44056. const buffer = readBuffer.getMappedRange();
  44057. return new typedArrayType( buffer );
  44058. }
  44059. /**
  44060. * Returns `true` if the given texture is an environment map.
  44061. *
  44062. * @private
  44063. * @param {Texture} texture - The texture.
  44064. * @return {boolean} Whether the given texture is an environment map or not.
  44065. */
  44066. _isEnvironmentTexture( texture ) {
  44067. const mapping = texture.mapping;
  44068. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44069. }
  44070. /**
  44071. * Returns the default GPU texture for the given format.
  44072. *
  44073. * @private
  44074. * @param {string} format - The GPU format.
  44075. * @return {GPUTexture} The GPU texture.
  44076. */
  44077. _getDefaultTextureGPU( format ) {
  44078. let defaultTexture = this.defaultTexture[ format ];
  44079. if ( defaultTexture === undefined ) {
  44080. const texture = new Texture();
  44081. texture.minFilter = NearestFilter;
  44082. texture.magFilter = NearestFilter;
  44083. this.createTexture( texture, { width: 1, height: 1, format } );
  44084. this.defaultTexture[ format ] = defaultTexture = texture;
  44085. }
  44086. return this.backend.get( defaultTexture ).texture;
  44087. }
  44088. /**
  44089. * Returns the default GPU cube texture for the given format.
  44090. *
  44091. * @private
  44092. * @param {string} format - The GPU format.
  44093. * @return {GPUTexture} The GPU texture.
  44094. */
  44095. _getDefaultCubeTextureGPU( format ) {
  44096. let defaultCubeTexture = this.defaultTexture[ format ];
  44097. if ( defaultCubeTexture === undefined ) {
  44098. const texture = new CubeTexture();
  44099. texture.minFilter = NearestFilter;
  44100. texture.magFilter = NearestFilter;
  44101. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  44102. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  44103. }
  44104. return this.backend.get( defaultCubeTexture ).texture;
  44105. }
  44106. /**
  44107. * Returns the default video frame used as default data in context of video textures.
  44108. *
  44109. * @private
  44110. * @return {VideoFrame} The video frame.
  44111. */
  44112. _getDefaultVideoFrame() {
  44113. let defaultVideoFrame = this.defaultVideoFrame;
  44114. if ( defaultVideoFrame === null ) {
  44115. const init = {
  44116. timestamp: 0,
  44117. codedWidth: 1,
  44118. codedHeight: 1,
  44119. format: 'RGBA',
  44120. };
  44121. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  44122. }
  44123. return defaultVideoFrame;
  44124. }
  44125. /**
  44126. * Uploads cube texture image data to the GPU memory.
  44127. *
  44128. * @private
  44129. * @param {Array} images - The cube image data.
  44130. * @param {GPUTexture} textureGPU - The GPU texture.
  44131. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44132. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44133. */
  44134. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  44135. for ( let i = 0; i < 6; i ++ ) {
  44136. const image = images[ i ];
  44137. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  44138. if ( image.isDataTexture ) {
  44139. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44140. } else {
  44141. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44142. }
  44143. }
  44144. }
  44145. /**
  44146. * Uploads texture image data to the GPU memory.
  44147. *
  44148. * @private
  44149. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  44150. * @param {GPUTexture} textureGPU - The GPU texture.
  44151. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44152. * @param {number} originDepth - The origin depth.
  44153. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44154. */
  44155. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  44156. const device = this.backend.device;
  44157. device.queue.copyExternalImageToTexture(
  44158. {
  44159. source: image,
  44160. flipY: flipY
  44161. }, {
  44162. texture: textureGPU,
  44163. mipLevel: 0,
  44164. origin: { x: 0, y: 0, z: originDepth }
  44165. }, {
  44166. width: image.width,
  44167. height: image.height,
  44168. depthOrArrayLayers: 1
  44169. }
  44170. );
  44171. }
  44172. /**
  44173. * Returns the pass utils singleton.
  44174. *
  44175. * @private
  44176. * @return {WebGPUTexturePassUtils} The utils instance.
  44177. */
  44178. _getPassUtils() {
  44179. let passUtils = this._passUtils;
  44180. if ( passUtils === null ) {
  44181. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  44182. }
  44183. return passUtils;
  44184. }
  44185. /**
  44186. * Generates mipmaps for the given GPU texture.
  44187. *
  44188. * @private
  44189. * @param {GPUTexture} textureGPU - The GPU texture object.
  44190. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44191. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44192. */
  44193. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  44194. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  44195. }
  44196. /**
  44197. * Flip the contents of the given GPU texture along its vertical axis.
  44198. *
  44199. * @private
  44200. * @param {GPUTexture} textureGPU - The GPU texture object.
  44201. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44202. * @param {number} [originDepth=0] - The origin depth.
  44203. */
  44204. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  44205. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  44206. }
  44207. /**
  44208. * Uploads texture buffer data to the GPU memory.
  44209. *
  44210. * @private
  44211. * @param {Object} image - An object defining the image buffer data.
  44212. * @param {GPUTexture} textureGPU - The GPU texture.
  44213. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44214. * @param {number} originDepth - The origin depth.
  44215. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44216. * @param {number} [depth=0] - TODO.
  44217. */
  44218. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  44219. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44220. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  44221. const device = this.backend.device;
  44222. const data = image.data;
  44223. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  44224. const bytesPerRow = image.width * bytesPerTexel;
  44225. device.queue.writeTexture(
  44226. {
  44227. texture: textureGPU,
  44228. mipLevel: 0,
  44229. origin: { x: 0, y: 0, z: originDepth }
  44230. },
  44231. data,
  44232. {
  44233. offset: image.width * image.height * bytesPerTexel * depth,
  44234. bytesPerRow
  44235. },
  44236. {
  44237. width: image.width,
  44238. height: image.height,
  44239. depthOrArrayLayers: 1
  44240. } );
  44241. if ( flipY === true ) {
  44242. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  44243. }
  44244. }
  44245. /**
  44246. * Uploads compressed texture data to the GPU memory.
  44247. *
  44248. * @private
  44249. * @param {Array<Object>} mipmaps - An array with mipmap data.
  44250. * @param {GPUTexture} textureGPU - The GPU texture.
  44251. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44252. */
  44253. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  44254. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44255. const device = this.backend.device;
  44256. const blockData = this._getBlockData( textureDescriptorGPU.format );
  44257. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  44258. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44259. const mipmap = mipmaps[ i ];
  44260. const width = mipmap.width;
  44261. const height = mipmap.height;
  44262. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  44263. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  44264. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  44265. for ( let j = 0; j < depth; j ++ ) {
  44266. device.queue.writeTexture(
  44267. {
  44268. texture: textureGPU,
  44269. mipLevel: i,
  44270. origin: { x: 0, y: 0, z: j }
  44271. },
  44272. mipmap.data,
  44273. {
  44274. offset: j * bytesPerImage,
  44275. bytesPerRow,
  44276. rowsPerImage: Math.ceil( height / blockData.height )
  44277. },
  44278. {
  44279. width: Math.ceil( width / blockData.width ) * blockData.width,
  44280. height: Math.ceil( height / blockData.height ) * blockData.height,
  44281. depthOrArrayLayers: 1
  44282. }
  44283. );
  44284. }
  44285. }
  44286. }
  44287. /**
  44288. * This method is only relevant for compressed texture formats. It returns a block
  44289. * data descriptor for the given GPU compressed texture format.
  44290. *
  44291. * @private
  44292. * @param {string} format - The GPU compressed texture format.
  44293. * @return {Object} The block data descriptor.
  44294. */
  44295. _getBlockData( format ) {
  44296. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  44297. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  44298. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  44299. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  44300. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  44301. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  44302. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  44303. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44304. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44305. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44306. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  44307. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  44308. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  44309. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  44310. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44311. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  44312. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  44313. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  44314. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  44315. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  44316. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  44317. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  44318. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  44319. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  44320. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  44321. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  44322. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  44323. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  44324. }
  44325. /**
  44326. * Converts the three.js uv wrapping constants to GPU address mode constants.
  44327. *
  44328. * @private
  44329. * @param {number} value - The three.js constant defining a uv wrapping mode.
  44330. * @return {string} The GPU address mode.
  44331. */
  44332. _convertAddressMode( value ) {
  44333. let addressMode = GPUAddressMode.ClampToEdge;
  44334. if ( value === RepeatWrapping ) {
  44335. addressMode = GPUAddressMode.Repeat;
  44336. } else if ( value === MirroredRepeatWrapping ) {
  44337. addressMode = GPUAddressMode.MirrorRepeat;
  44338. }
  44339. return addressMode;
  44340. }
  44341. /**
  44342. * Converts the three.js filter constants to GPU filter constants.
  44343. *
  44344. * @private
  44345. * @param {number} value - The three.js constant defining a filter mode.
  44346. * @return {string} The GPU filter mode.
  44347. */
  44348. _convertFilterMode( value ) {
  44349. let filterMode = GPUFilterMode.Linear;
  44350. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  44351. filterMode = GPUFilterMode.Nearest;
  44352. }
  44353. return filterMode;
  44354. }
  44355. /**
  44356. * Returns the bytes-per-texel value for the given GPU texture format.
  44357. *
  44358. * @private
  44359. * @param {string} format - The GPU texture format.
  44360. * @return {number} The bytes-per-texel.
  44361. */
  44362. _getBytesPerTexel( format ) {
  44363. // 8-bit formats
  44364. if ( format === GPUTextureFormat.R8Unorm ||
  44365. format === GPUTextureFormat.R8Snorm ||
  44366. format === GPUTextureFormat.R8Uint ||
  44367. format === GPUTextureFormat.R8Sint ) return 1;
  44368. // 16-bit formats
  44369. if ( format === GPUTextureFormat.R16Uint ||
  44370. format === GPUTextureFormat.R16Sint ||
  44371. format === GPUTextureFormat.R16Float ||
  44372. format === GPUTextureFormat.RG8Unorm ||
  44373. format === GPUTextureFormat.RG8Snorm ||
  44374. format === GPUTextureFormat.RG8Uint ||
  44375. format === GPUTextureFormat.RG8Sint ) return 2;
  44376. // 32-bit formats
  44377. if ( format === GPUTextureFormat.R32Uint ||
  44378. format === GPUTextureFormat.R32Sint ||
  44379. format === GPUTextureFormat.R32Float ||
  44380. format === GPUTextureFormat.RG16Uint ||
  44381. format === GPUTextureFormat.RG16Sint ||
  44382. format === GPUTextureFormat.RG16Float ||
  44383. format === GPUTextureFormat.RGBA8Unorm ||
  44384. format === GPUTextureFormat.RGBA8UnormSRGB ||
  44385. format === GPUTextureFormat.RGBA8Snorm ||
  44386. format === GPUTextureFormat.RGBA8Uint ||
  44387. format === GPUTextureFormat.RGBA8Sint ||
  44388. format === GPUTextureFormat.BGRA8Unorm ||
  44389. format === GPUTextureFormat.BGRA8UnormSRGB ||
  44390. // Packed 32-bit formats
  44391. format === GPUTextureFormat.RGB9E5UFloat ||
  44392. format === GPUTextureFormat.RGB10A2Unorm ||
  44393. format === GPUTextureFormat.RG11B10UFloat ||
  44394. format === GPUTextureFormat.Depth32Float ||
  44395. format === GPUTextureFormat.Depth24Plus ||
  44396. format === GPUTextureFormat.Depth24PlusStencil8 ||
  44397. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  44398. // 64-bit formats
  44399. if ( format === GPUTextureFormat.RG32Uint ||
  44400. format === GPUTextureFormat.RG32Sint ||
  44401. format === GPUTextureFormat.RG32Float ||
  44402. format === GPUTextureFormat.RGBA16Uint ||
  44403. format === GPUTextureFormat.RGBA16Sint ||
  44404. format === GPUTextureFormat.RGBA16Float ) return 8;
  44405. // 128-bit formats
  44406. if ( format === GPUTextureFormat.RGBA32Uint ||
  44407. format === GPUTextureFormat.RGBA32Sint ||
  44408. format === GPUTextureFormat.RGBA32Float ) return 16;
  44409. }
  44410. /**
  44411. * Returns the corresponding typed array type for the given GPU texture format.
  44412. *
  44413. * @private
  44414. * @param {string} format - The GPU texture format.
  44415. * @return {TypedArray.constructor} The typed array type.
  44416. */
  44417. _getTypedArrayType( format ) {
  44418. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  44419. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  44420. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  44421. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  44422. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  44423. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  44424. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  44425. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  44426. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  44427. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  44428. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  44429. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  44430. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  44431. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  44432. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  44433. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  44434. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  44435. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  44436. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  44437. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  44438. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  44439. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  44440. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  44441. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  44442. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  44443. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  44444. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  44445. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  44446. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  44447. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  44448. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  44449. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  44450. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  44451. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  44452. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  44453. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  44454. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  44455. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  44456. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  44457. }
  44458. /**
  44459. * Returns the GPU dimensions for the given texture.
  44460. *
  44461. * @private
  44462. * @param {Texture} texture - The texture.
  44463. * @return {string} The GPU dimension.
  44464. */
  44465. _getDimension( texture ) {
  44466. let dimension;
  44467. if ( texture.isData3DTexture ) {
  44468. dimension = GPUTextureDimension.ThreeD;
  44469. } else {
  44470. dimension = GPUTextureDimension.TwoD;
  44471. }
  44472. return dimension;
  44473. }
  44474. }
  44475. /**
  44476. * Returns the GPU format for the given texture.
  44477. *
  44478. * @param {Texture} texture - The texture.
  44479. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  44480. * It is not necessary to apply the device for most formats.
  44481. * @return {string} The GPU format.
  44482. */
  44483. function getFormat( texture, device = null ) {
  44484. const format = texture.format;
  44485. const type = texture.type;
  44486. const colorSpace = texture.colorSpace;
  44487. let formatGPU;
  44488. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  44489. switch ( format ) {
  44490. case RGBA_S3TC_DXT1_Format:
  44491. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  44492. break;
  44493. case RGBA_S3TC_DXT3_Format:
  44494. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  44495. break;
  44496. case RGBA_S3TC_DXT5_Format:
  44497. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  44498. break;
  44499. case RGB_ETC2_Format:
  44500. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  44501. break;
  44502. case RGBA_ETC2_EAC_Format:
  44503. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  44504. break;
  44505. case RGBA_ASTC_4x4_Format:
  44506. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  44507. break;
  44508. case RGBA_ASTC_5x4_Format:
  44509. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  44510. break;
  44511. case RGBA_ASTC_5x5_Format:
  44512. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  44513. break;
  44514. case RGBA_ASTC_6x5_Format:
  44515. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  44516. break;
  44517. case RGBA_ASTC_6x6_Format:
  44518. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  44519. break;
  44520. case RGBA_ASTC_8x5_Format:
  44521. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  44522. break;
  44523. case RGBA_ASTC_8x6_Format:
  44524. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  44525. break;
  44526. case RGBA_ASTC_8x8_Format:
  44527. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  44528. break;
  44529. case RGBA_ASTC_10x5_Format:
  44530. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  44531. break;
  44532. case RGBA_ASTC_10x6_Format:
  44533. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  44534. break;
  44535. case RGBA_ASTC_10x8_Format:
  44536. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  44537. break;
  44538. case RGBA_ASTC_10x10_Format:
  44539. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  44540. break;
  44541. case RGBA_ASTC_12x10_Format:
  44542. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  44543. break;
  44544. case RGBA_ASTC_12x12_Format:
  44545. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  44546. break;
  44547. case RGBAFormat:
  44548. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  44549. break;
  44550. default:
  44551. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  44552. }
  44553. } else {
  44554. switch ( format ) {
  44555. case RGBAFormat:
  44556. switch ( type ) {
  44557. case ByteType:
  44558. formatGPU = GPUTextureFormat.RGBA8Snorm;
  44559. break;
  44560. case ShortType:
  44561. formatGPU = GPUTextureFormat.RGBA16Sint;
  44562. break;
  44563. case UnsignedShortType:
  44564. formatGPU = GPUTextureFormat.RGBA16Uint;
  44565. break;
  44566. case UnsignedIntType:
  44567. formatGPU = GPUTextureFormat.RGBA32Uint;
  44568. break;
  44569. case IntType:
  44570. formatGPU = GPUTextureFormat.RGBA32Sint;
  44571. break;
  44572. case UnsignedByteType:
  44573. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  44574. break;
  44575. case HalfFloatType:
  44576. formatGPU = GPUTextureFormat.RGBA16Float;
  44577. break;
  44578. case FloatType:
  44579. formatGPU = GPUTextureFormat.RGBA32Float;
  44580. break;
  44581. default:
  44582. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  44583. }
  44584. break;
  44585. case RGBFormat:
  44586. switch ( type ) {
  44587. case UnsignedInt5999Type:
  44588. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  44589. break;
  44590. default:
  44591. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  44592. }
  44593. break;
  44594. case RedFormat:
  44595. switch ( type ) {
  44596. case ByteType:
  44597. formatGPU = GPUTextureFormat.R8Snorm;
  44598. break;
  44599. case ShortType:
  44600. formatGPU = GPUTextureFormat.R16Sint;
  44601. break;
  44602. case UnsignedShortType:
  44603. formatGPU = GPUTextureFormat.R16Uint;
  44604. break;
  44605. case UnsignedIntType:
  44606. formatGPU = GPUTextureFormat.R32Uint;
  44607. break;
  44608. case IntType:
  44609. formatGPU = GPUTextureFormat.R32Sint;
  44610. break;
  44611. case UnsignedByteType:
  44612. formatGPU = GPUTextureFormat.R8Unorm;
  44613. break;
  44614. case HalfFloatType:
  44615. formatGPU = GPUTextureFormat.R16Float;
  44616. break;
  44617. case FloatType:
  44618. formatGPU = GPUTextureFormat.R32Float;
  44619. break;
  44620. default:
  44621. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  44622. }
  44623. break;
  44624. case RGFormat:
  44625. switch ( type ) {
  44626. case ByteType:
  44627. formatGPU = GPUTextureFormat.RG8Snorm;
  44628. break;
  44629. case ShortType:
  44630. formatGPU = GPUTextureFormat.RG16Sint;
  44631. break;
  44632. case UnsignedShortType:
  44633. formatGPU = GPUTextureFormat.RG16Uint;
  44634. break;
  44635. case UnsignedIntType:
  44636. formatGPU = GPUTextureFormat.RG32Uint;
  44637. break;
  44638. case IntType:
  44639. formatGPU = GPUTextureFormat.RG32Sint;
  44640. break;
  44641. case UnsignedByteType:
  44642. formatGPU = GPUTextureFormat.RG8Unorm;
  44643. break;
  44644. case HalfFloatType:
  44645. formatGPU = GPUTextureFormat.RG16Float;
  44646. break;
  44647. case FloatType:
  44648. formatGPU = GPUTextureFormat.RG32Float;
  44649. break;
  44650. default:
  44651. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  44652. }
  44653. break;
  44654. case DepthFormat:
  44655. switch ( type ) {
  44656. case UnsignedShortType:
  44657. formatGPU = GPUTextureFormat.Depth16Unorm;
  44658. break;
  44659. case UnsignedIntType:
  44660. formatGPU = GPUTextureFormat.Depth24Plus;
  44661. break;
  44662. case FloatType:
  44663. formatGPU = GPUTextureFormat.Depth32Float;
  44664. break;
  44665. default:
  44666. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  44667. }
  44668. break;
  44669. case DepthStencilFormat:
  44670. switch ( type ) {
  44671. case UnsignedInt248Type:
  44672. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  44673. break;
  44674. case FloatType:
  44675. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  44676. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  44677. }
  44678. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  44679. break;
  44680. default:
  44681. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  44682. }
  44683. break;
  44684. case RedIntegerFormat:
  44685. switch ( type ) {
  44686. case IntType:
  44687. formatGPU = GPUTextureFormat.R32Sint;
  44688. break;
  44689. case UnsignedIntType:
  44690. formatGPU = GPUTextureFormat.R32Uint;
  44691. break;
  44692. default:
  44693. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  44694. }
  44695. break;
  44696. case RGIntegerFormat:
  44697. switch ( type ) {
  44698. case IntType:
  44699. formatGPU = GPUTextureFormat.RG32Sint;
  44700. break;
  44701. case UnsignedIntType:
  44702. formatGPU = GPUTextureFormat.RG32Uint;
  44703. break;
  44704. default:
  44705. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  44706. }
  44707. break;
  44708. case RGBAIntegerFormat:
  44709. switch ( type ) {
  44710. case IntType:
  44711. formatGPU = GPUTextureFormat.RGBA32Sint;
  44712. break;
  44713. case UnsignedIntType:
  44714. formatGPU = GPUTextureFormat.RGBA32Uint;
  44715. break;
  44716. default:
  44717. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  44718. }
  44719. break;
  44720. default:
  44721. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  44722. }
  44723. }
  44724. return formatGPU;
  44725. }
  44726. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  44727. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  44728. const wgslTypeLib$1 = {
  44729. 'f32': 'float',
  44730. 'i32': 'int',
  44731. 'u32': 'uint',
  44732. 'bool': 'bool',
  44733. 'vec2<f32>': 'vec2',
  44734. 'vec2<i32>': 'ivec2',
  44735. 'vec2<u32>': 'uvec2',
  44736. 'vec2<bool>': 'bvec2',
  44737. 'vec2f': 'vec2',
  44738. 'vec2i': 'ivec2',
  44739. 'vec2u': 'uvec2',
  44740. 'vec2b': 'bvec2',
  44741. 'vec3<f32>': 'vec3',
  44742. 'vec3<i32>': 'ivec3',
  44743. 'vec3<u32>': 'uvec3',
  44744. 'vec3<bool>': 'bvec3',
  44745. 'vec3f': 'vec3',
  44746. 'vec3i': 'ivec3',
  44747. 'vec3u': 'uvec3',
  44748. 'vec3b': 'bvec3',
  44749. 'vec4<f32>': 'vec4',
  44750. 'vec4<i32>': 'ivec4',
  44751. 'vec4<u32>': 'uvec4',
  44752. 'vec4<bool>': 'bvec4',
  44753. 'vec4f': 'vec4',
  44754. 'vec4i': 'ivec4',
  44755. 'vec4u': 'uvec4',
  44756. 'vec4b': 'bvec4',
  44757. 'mat2x2<f32>': 'mat2',
  44758. 'mat2x2f': 'mat2',
  44759. 'mat3x3<f32>': 'mat3',
  44760. 'mat3x3f': 'mat3',
  44761. 'mat4x4<f32>': 'mat4',
  44762. 'mat4x4f': 'mat4',
  44763. 'sampler': 'sampler',
  44764. 'texture_1d': 'texture',
  44765. 'texture_2d': 'texture',
  44766. 'texture_2d_array': 'texture',
  44767. 'texture_multisampled_2d': 'cubeTexture',
  44768. 'texture_depth_2d': 'depthTexture',
  44769. 'texture_depth_multisampled_2d': 'depthTexture',
  44770. 'texture_3d': 'texture3D',
  44771. 'texture_cube': 'cubeTexture',
  44772. 'texture_cube_array': 'cubeTexture',
  44773. 'texture_storage_1d': 'storageTexture',
  44774. 'texture_storage_2d': 'storageTexture',
  44775. 'texture_storage_2d_array': 'storageTexture',
  44776. 'texture_storage_3d': 'storageTexture'
  44777. };
  44778. const parse = ( source ) => {
  44779. source = source.trim();
  44780. const declaration = source.match( declarationRegexp );
  44781. if ( declaration !== null && declaration.length === 4 ) {
  44782. const inputsCode = declaration[ 2 ];
  44783. const propsMatches = [];
  44784. let match = null;
  44785. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  44786. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  44787. }
  44788. // Process matches to correctly pair names and types
  44789. const inputs = [];
  44790. for ( let i = 0; i < propsMatches.length; i ++ ) {
  44791. const { name, type } = propsMatches[ i ];
  44792. let resolvedType = type;
  44793. if ( resolvedType.startsWith( 'ptr' ) ) {
  44794. resolvedType = 'pointer';
  44795. } else {
  44796. if ( resolvedType.startsWith( 'texture' ) ) {
  44797. resolvedType = type.split( '<' )[ 0 ];
  44798. }
  44799. resolvedType = wgslTypeLib$1[ resolvedType ];
  44800. }
  44801. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  44802. }
  44803. const blockCode = source.substring( declaration[ 0 ].length );
  44804. const outputType = declaration[ 3 ] || 'void';
  44805. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  44806. const type = wgslTypeLib$1[ outputType ] || outputType;
  44807. return {
  44808. type,
  44809. inputs,
  44810. name,
  44811. inputsCode,
  44812. blockCode,
  44813. outputType
  44814. };
  44815. } else {
  44816. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  44817. }
  44818. };
  44819. /**
  44820. * This class represents a WSL node function.
  44821. *
  44822. * @augments NodeFunction
  44823. */
  44824. class WGSLNodeFunction extends NodeFunction {
  44825. /**
  44826. * Constructs a new WGSL node function.
  44827. *
  44828. * @param {string} source - The WGSL source.
  44829. */
  44830. constructor( source ) {
  44831. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  44832. super( type, inputs, name );
  44833. this.inputsCode = inputsCode;
  44834. this.blockCode = blockCode;
  44835. this.outputType = outputType;
  44836. }
  44837. /**
  44838. * This method returns the WGSL code of the node function.
  44839. *
  44840. * @param {string} [name=this.name] - The function's name.
  44841. * @return {string} The shader code.
  44842. */
  44843. getCode( name = this.name ) {
  44844. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  44845. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  44846. }
  44847. }
  44848. /**
  44849. * A WGSL node parser.
  44850. *
  44851. * @augments NodeParser
  44852. */
  44853. class WGSLNodeParser extends NodeParser {
  44854. /**
  44855. * The method parses the given WGSL code an returns a node function.
  44856. *
  44857. * @param {string} source - The WGSL code.
  44858. * @return {WGSLNodeFunction} A node function.
  44859. */
  44860. parseFunction( source ) {
  44861. return new WGSLNodeFunction( source );
  44862. }
  44863. }
  44864. // GPUShaderStage is not defined in browsers not supporting WebGPU
  44865. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  44866. const accessNames = {
  44867. [ NodeAccess.READ_ONLY ]: 'read',
  44868. [ NodeAccess.WRITE_ONLY ]: 'write',
  44869. [ NodeAccess.READ_WRITE ]: 'read_write'
  44870. };
  44871. const wrapNames = {
  44872. [ RepeatWrapping ]: 'repeat',
  44873. [ ClampToEdgeWrapping ]: 'clamp',
  44874. [ MirroredRepeatWrapping ]: 'mirror'
  44875. };
  44876. const gpuShaderStageLib = {
  44877. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  44878. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  44879. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  44880. };
  44881. const supports = {
  44882. instance: true,
  44883. swizzleAssign: false,
  44884. storageBuffer: true
  44885. };
  44886. const wgslFnOpLib = {
  44887. '^^': 'tsl_xor'
  44888. };
  44889. const wgslTypeLib = {
  44890. float: 'f32',
  44891. int: 'i32',
  44892. uint: 'u32',
  44893. bool: 'bool',
  44894. color: 'vec3<f32>',
  44895. vec2: 'vec2<f32>',
  44896. ivec2: 'vec2<i32>',
  44897. uvec2: 'vec2<u32>',
  44898. bvec2: 'vec2<bool>',
  44899. vec3: 'vec3<f32>',
  44900. ivec3: 'vec3<i32>',
  44901. uvec3: 'vec3<u32>',
  44902. bvec3: 'vec3<bool>',
  44903. vec4: 'vec4<f32>',
  44904. ivec4: 'vec4<i32>',
  44905. uvec4: 'vec4<u32>',
  44906. bvec4: 'vec4<bool>',
  44907. mat2: 'mat2x2<f32>',
  44908. mat3: 'mat3x3<f32>',
  44909. mat4: 'mat4x4<f32>'
  44910. };
  44911. const wgslCodeCache = {};
  44912. const wgslPolyfill = {
  44913. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  44914. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  44915. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  44916. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  44917. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  44918. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  44919. 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 ); }' ),
  44920. 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 ); }' ),
  44921. 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 ); }' ),
  44922. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  44923. 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 ); }' ),
  44924. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  44925. biquadraticTexture: new CodeNode( /* wgsl */`
  44926. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  44927. let res = vec2f( iRes );
  44928. let uvScaled = coord * res;
  44929. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  44930. // https://www.shadertoy.com/view/WtyXRy
  44931. let uv = uvWrapping - 0.5;
  44932. let iuv = floor( uv );
  44933. let f = fract( uv );
  44934. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  44935. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  44936. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  44937. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  44938. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  44939. }
  44940. ` )
  44941. };
  44942. const wgslMethods = {
  44943. dFdx: 'dpdx',
  44944. dFdy: '- dpdy',
  44945. mod_float: 'tsl_mod_float',
  44946. mod_vec2: 'tsl_mod_vec2',
  44947. mod_vec3: 'tsl_mod_vec3',
  44948. mod_vec4: 'tsl_mod_vec4',
  44949. equals_bool: 'tsl_equals_bool',
  44950. equals_bvec2: 'tsl_equals_bvec2',
  44951. equals_bvec3: 'tsl_equals_bvec3',
  44952. equals_bvec4: 'tsl_equals_bvec4',
  44953. inversesqrt: 'inverseSqrt',
  44954. bitcast: 'bitcast<f32>'
  44955. };
  44956. // WebGPU issue: does not support pow() with negative base on Windows
  44957. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  44958. 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 ); }' );
  44959. 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 ] );
  44960. 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 ] );
  44961. 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 ] );
  44962. wgslMethods.pow_float = 'tsl_pow_float';
  44963. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  44964. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  44965. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  44966. }
  44967. //
  44968. let diagnostics = '';
  44969. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  44970. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  44971. }
  44972. /**
  44973. * A node builder targeting WGSL.
  44974. *
  44975. * This module generates WGSL shader code from node materials and also
  44976. * generates the respective bindings and vertex buffer definitions. These
  44977. * data are later used by the renderer to create render and compute pipelines
  44978. * for render objects.
  44979. *
  44980. * @augments NodeBuilder
  44981. */
  44982. class WGSLNodeBuilder extends NodeBuilder {
  44983. /**
  44984. * Constructs a new WGSL node builder renderer.
  44985. *
  44986. * @param {Object3D} object - The 3D object.
  44987. * @param {Renderer} renderer - The renderer.
  44988. */
  44989. constructor( object, renderer ) {
  44990. super( object, renderer, new WGSLNodeParser() );
  44991. /**
  44992. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  44993. * another dictionary which manages UBOs per group ('render','frame','object').
  44994. *
  44995. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44996. */
  44997. this.uniformGroups = {};
  44998. /**
  44999. * A dictionary that holds for each shader stage a Map of builtins.
  45000. *
  45001. * @type {Object<string,Map<string,Object>>}
  45002. */
  45003. this.builtins = {};
  45004. /**
  45005. * A dictionary that holds for each shader stage a Set of directives.
  45006. *
  45007. * @type {Object<string,Set<string>>}
  45008. */
  45009. this.directives = {};
  45010. /**
  45011. * A map for managing scope arrays. Only relevant for when using
  45012. * {@link WorkgroupInfoNode} in context of compute shaders.
  45013. *
  45014. * @type {Map<string,Object>}
  45015. */
  45016. this.scopedArrays = new Map();
  45017. }
  45018. /**
  45019. * Checks if the given texture requires a manual conversion to the working color space.
  45020. *
  45021. * @param {Texture} texture - The texture to check.
  45022. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  45023. */
  45024. needsToWorkingColorSpace( texture ) {
  45025. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  45026. }
  45027. /**
  45028. * Generates the WGSL snippet for sampled textures.
  45029. *
  45030. * @private
  45031. * @param {Texture} texture - The texture.
  45032. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45033. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45034. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45035. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45036. * @return {string} The WGSL snippet.
  45037. */
  45038. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45039. if ( shaderStage === 'fragment' ) {
  45040. if ( depthSnippet ) {
  45041. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  45042. } else {
  45043. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  45044. }
  45045. } else if ( this.isFilteredTexture( texture ) ) {
  45046. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  45047. } else {
  45048. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  45049. }
  45050. }
  45051. /**
  45052. * Generates the WGSL snippet when sampling video textures.
  45053. *
  45054. * @private
  45055. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45056. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45057. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45058. * @return {string} The WGSL snippet.
  45059. */
  45060. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  45061. if ( shaderStage === 'fragment' ) {
  45062. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  45063. } else {
  45064. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  45065. }
  45066. }
  45067. /**
  45068. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45069. *
  45070. * @private
  45071. * @param {Texture} texture - The texture.
  45072. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45073. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45074. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45075. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45076. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45077. * @return {string} The WGSL snippet.
  45078. */
  45079. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45080. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  45081. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  45082. } else if ( this.isFilteredTexture( texture ) ) {
  45083. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  45084. } else {
  45085. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  45086. }
  45087. }
  45088. /**
  45089. * Generates a wrap function used in context of textures.
  45090. *
  45091. * @param {Texture} texture - The texture to generate the function for.
  45092. * @return {string} The name of the generated function.
  45093. */
  45094. generateWrapFunction( texture ) {
  45095. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  45096. let nodeCode = wgslCodeCache[ functionName ];
  45097. if ( nodeCode === undefined ) {
  45098. const includes = [];
  45099. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  45100. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  45101. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  45102. const addWrapSnippet = ( wrap, axis ) => {
  45103. if ( wrap === RepeatWrapping ) {
  45104. includes.push( wgslPolyfill.repeatWrapping_float );
  45105. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  45106. } else if ( wrap === ClampToEdgeWrapping ) {
  45107. includes.push( wgslPolyfill.clampWrapping_float );
  45108. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  45109. } else if ( wrap === MirroredRepeatWrapping ) {
  45110. includes.push( wgslPolyfill.mirrorWrapping_float );
  45111. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  45112. } else {
  45113. code += `\t\tcoord.${ axis }`;
  45114. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  45115. }
  45116. };
  45117. addWrapSnippet( texture.wrapS, 'x' );
  45118. code += ',\n';
  45119. addWrapSnippet( texture.wrapT, 'y' );
  45120. if ( texture.isData3DTexture ) {
  45121. code += ',\n';
  45122. addWrapSnippet( texture.wrapR, 'z' );
  45123. }
  45124. code += '\n\t);\n\n}\n';
  45125. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  45126. }
  45127. nodeCode.build( this );
  45128. return functionName;
  45129. }
  45130. /**
  45131. * Generates the array declaration string.
  45132. *
  45133. * @param {string} type - The type.
  45134. * @param {?number} [count] - The count.
  45135. * @return {string} The generated value as a shader string.
  45136. */
  45137. generateArrayDeclaration( type, count ) {
  45138. return `array< ${ this.getType( type ) }, ${ count } >`;
  45139. }
  45140. /**
  45141. * Generates a WGSL variable that holds the texture dimension of the given texture.
  45142. * It also returns information about the the number of layers (elements) of an arrayed
  45143. * texture as well as the cube face count of cube textures.
  45144. *
  45145. * @param {Texture} texture - The texture to generate the function for.
  45146. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45147. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45148. * @return {string} The name of the dimension variable.
  45149. */
  45150. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  45151. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  45152. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  45153. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  45154. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  45155. let textureDimensionsParams;
  45156. let dimensionType;
  45157. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45158. const isMultisampled = primarySamples > 1;
  45159. if ( texture.isData3DTexture ) {
  45160. dimensionType = 'vec3<u32>';
  45161. } else {
  45162. // Regular 2D textures, depth textures, etc.
  45163. dimensionType = 'vec2<u32>';
  45164. }
  45165. // Build parameters string based on texture type and multisampling
  45166. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  45167. textureDimensionsParams = textureProperty;
  45168. } else {
  45169. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  45170. }
  45171. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  45172. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  45173. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  45174. textureData.arrayLayerCount = new VarNode(
  45175. new ExpressionNode(
  45176. `textureNumLayers(${textureProperty})`,
  45177. 'u32'
  45178. )
  45179. );
  45180. }
  45181. // For cube textures, we know it's always 6 faces
  45182. if ( texture.isTextureCube ) {
  45183. textureData.cubeFaceCount = new VarNode(
  45184. new ExpressionNode( '6u', 'u32' )
  45185. );
  45186. }
  45187. }
  45188. return textureDimensionNode.build( this );
  45189. }
  45190. /**
  45191. * Generates the WGSL snippet for a manual filtered texture.
  45192. *
  45193. * @param {Texture} texture - The texture.
  45194. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45195. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45196. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45197. * @return {string} The WGSL snippet.
  45198. */
  45199. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  45200. this._include( 'biquadraticTexture' );
  45201. const wrapFunction = this.generateWrapFunction( texture );
  45202. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45203. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  45204. }
  45205. /**
  45206. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  45207. * Since it's a lookup, no sampling or filtering is applied.
  45208. *
  45209. * @param {Texture} texture - The texture.
  45210. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45211. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45212. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45213. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45214. * @return {string} The WGSL snippet.
  45215. */
  45216. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  45217. const wrapFunction = this.generateWrapFunction( texture );
  45218. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45219. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  45220. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  45221. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  45222. }
  45223. /**
  45224. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  45225. *
  45226. * @param {Texture} texture - The texture.
  45227. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45228. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45229. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45230. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45231. * @return {string} The WGSL snippet.
  45232. */
  45233. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  45234. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  45235. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  45236. } else if ( depthSnippet ) {
  45237. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  45238. } else {
  45239. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  45240. }
  45241. }
  45242. /**
  45243. * Generates the WGSL snippet that writes a single texel to a texture.
  45244. *
  45245. * @param {Texture} texture - The texture.
  45246. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45247. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45248. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  45249. * @return {string} The WGSL snippet.
  45250. */
  45251. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  45252. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  45253. }
  45254. /**
  45255. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  45256. *
  45257. * @param {Texture} texture - The texture.
  45258. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  45259. */
  45260. isSampleCompare( texture ) {
  45261. return texture.isDepthTexture === true && texture.compareFunction !== null;
  45262. }
  45263. /**
  45264. * Returns `true` if the given texture is unfilterable.
  45265. *
  45266. * @param {Texture} texture - The texture.
  45267. * @return {boolean} Whether the given texture is unfilterable or not.
  45268. */
  45269. isUnfilterable( texture ) {
  45270. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  45271. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  45272. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  45273. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  45274. }
  45275. /**
  45276. * Generates the WGSL snippet for sampling/loading the given texture.
  45277. *
  45278. * @param {Texture} texture - The texture.
  45279. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45280. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45281. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45282. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45283. * @return {string} The WGSL snippet.
  45284. */
  45285. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45286. let snippet = null;
  45287. if ( texture.isVideoTexture === true ) {
  45288. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45289. } else if ( this.isUnfilterable( texture ) ) {
  45290. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  45291. } else {
  45292. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  45293. }
  45294. return snippet;
  45295. }
  45296. /**
  45297. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  45298. *
  45299. * @param {Texture} texture - The texture.
  45300. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45301. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45302. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  45303. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45304. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45305. * @return {string} The WGSL snippet.
  45306. */
  45307. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45308. if ( shaderStage === 'fragment' ) {
  45309. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  45310. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  45311. } else {
  45312. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  45313. }
  45314. }
  45315. /**
  45316. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  45317. * against a reference value.
  45318. *
  45319. * @param {Texture} texture - The texture.
  45320. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45321. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45322. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  45323. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45324. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45325. * @return {string} The WGSL snippet.
  45326. */
  45327. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45328. if ( shaderStage === 'fragment' ) {
  45329. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  45330. } else {
  45331. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  45332. }
  45333. }
  45334. /**
  45335. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45336. *
  45337. * @param {Texture} texture - The texture.
  45338. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45339. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45340. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45341. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45342. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45343. * @return {string} The WGSL snippet.
  45344. */
  45345. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45346. let snippet = null;
  45347. if ( texture.isVideoTexture === true ) {
  45348. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45349. } else {
  45350. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  45351. }
  45352. return snippet;
  45353. }
  45354. /**
  45355. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  45356. *
  45357. * @param {Texture} texture - The texture.
  45358. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45359. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45360. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  45361. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45362. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45363. * @return {string} The WGSL snippet.
  45364. */
  45365. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45366. if ( shaderStage === 'fragment' ) {
  45367. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  45368. } else {
  45369. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  45370. }
  45371. }
  45372. /**
  45373. * Returns a WGSL snippet that represents the property name of the given node.
  45374. *
  45375. * @param {Node} node - The node.
  45376. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45377. * @return {string} The property name.
  45378. */
  45379. getPropertyName( node, shaderStage = this.shaderStage ) {
  45380. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  45381. if ( shaderStage === 'vertex' ) {
  45382. return `varyings.${ node.name }`;
  45383. }
  45384. } else if ( node.isNodeUniform === true ) {
  45385. const name = node.name;
  45386. const type = node.type;
  45387. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  45388. return name;
  45389. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  45390. if ( this.isCustomStruct( node ) ) {
  45391. return name;
  45392. }
  45393. return name + '.value';
  45394. } else {
  45395. return node.groupNode.name + '.' + name;
  45396. }
  45397. }
  45398. return super.getPropertyName( node );
  45399. }
  45400. /**
  45401. * Returns the output struct name.
  45402. *
  45403. * @return {string} The name of the output struct.
  45404. */
  45405. getOutputStructName() {
  45406. return 'output';
  45407. }
  45408. /**
  45409. * Returns uniforms group count for the given shader stage.
  45410. *
  45411. * @private
  45412. * @param {string} shaderStage - The shader stage.
  45413. * @return {number} The uniforms group count for the given shader stage.
  45414. */
  45415. _getUniformGroupCount( shaderStage ) {
  45416. return Object.keys( this.uniforms[ shaderStage ] ).length;
  45417. }
  45418. /**
  45419. * Returns the native shader operator name for a given generic name.
  45420. *
  45421. * @param {string} op - The operator name to resolve.
  45422. * @return {string} The resolved operator name.
  45423. */
  45424. getFunctionOperator( op ) {
  45425. const fnOp = wgslFnOpLib[ op ];
  45426. if ( fnOp !== undefined ) {
  45427. this._include( fnOp );
  45428. return fnOp;
  45429. }
  45430. return null;
  45431. }
  45432. /**
  45433. * Returns the node access for the given node and shader stage.
  45434. *
  45435. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  45436. * @param {string} shaderStage - The shader stage.
  45437. * @return {string} The node access.
  45438. */
  45439. getNodeAccess( node, shaderStage ) {
  45440. if ( shaderStage !== 'compute' )
  45441. return NodeAccess.READ_ONLY;
  45442. return node.access;
  45443. }
  45444. /**
  45445. * Returns A WGSL snippet representing the storage access.
  45446. *
  45447. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  45448. * @param {string} shaderStage - The shader stage.
  45449. * @return {string} The WGSL snippet representing the storage access.
  45450. */
  45451. getStorageAccess( node, shaderStage ) {
  45452. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  45453. }
  45454. /**
  45455. * This method is one of the more important ones since it's responsible
  45456. * for generating a matching binding instance for the given uniform node.
  45457. *
  45458. * These bindings are later used in the renderer to create bind groups
  45459. * and layouts.
  45460. *
  45461. * @param {UniformNode} node - The uniform node.
  45462. * @param {string} type - The node data type.
  45463. * @param {string} shaderStage - The shader stage.
  45464. * @param {?string} [name=null] - An optional uniform name.
  45465. * @return {NodeUniform} The node uniform object.
  45466. */
  45467. getUniformFromNode( node, type, shaderStage, name = null ) {
  45468. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45469. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45470. if ( nodeData.uniformGPU === undefined ) {
  45471. let uniformGPU;
  45472. const group = node.groupNode;
  45473. const groupName = group.name;
  45474. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45475. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  45476. let texture = null;
  45477. const access = this.getNodeAccess( node, shaderStage );
  45478. if ( type === 'texture' || type === 'storageTexture' ) {
  45479. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  45480. } else if ( type === 'cubeTexture' ) {
  45481. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  45482. } else if ( type === 'texture3D' ) {
  45483. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  45484. }
  45485. texture.store = node.isStorageTextureNode === true;
  45486. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45487. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  45488. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  45489. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45490. bindings.push( sampler, texture );
  45491. uniformGPU = [ sampler, texture ];
  45492. } else {
  45493. bindings.push( texture );
  45494. uniformGPU = [ texture ];
  45495. }
  45496. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  45497. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  45498. const buffer = new bufferClass( node, group );
  45499. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45500. bindings.push( buffer );
  45501. uniformGPU = buffer;
  45502. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  45503. } else {
  45504. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  45505. let uniformsGroup = uniformsStage[ groupName ];
  45506. if ( uniformsGroup === undefined ) {
  45507. uniformsGroup = new NodeUniformsGroup( groupName, group );
  45508. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45509. uniformsStage[ groupName ] = uniformsGroup;
  45510. bindings.push( uniformsGroup );
  45511. }
  45512. uniformGPU = this.getNodeUniform( uniformNode, type );
  45513. uniformsGroup.addUniform( uniformGPU );
  45514. }
  45515. nodeData.uniformGPU = uniformGPU;
  45516. }
  45517. return uniformNode;
  45518. }
  45519. /**
  45520. * This method should be used whenever builtins are required in nodes.
  45521. * The internal builtins data structure will make sure builtins are
  45522. * defined in the WGSL source.
  45523. *
  45524. * @param {string} name - The builtin name.
  45525. * @param {string} property - The property name.
  45526. * @param {string} type - The node data type.
  45527. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45528. * @return {string} The property name.
  45529. */
  45530. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  45531. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  45532. if ( map.has( name ) === false ) {
  45533. map.set( name, {
  45534. name,
  45535. property,
  45536. type
  45537. } );
  45538. }
  45539. return property;
  45540. }
  45541. /**
  45542. * Returns `true` if the given builtin is defined in the given shader stage.
  45543. *
  45544. * @param {string} name - The builtin name.
  45545. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45546. * @return {string} Whether the given builtin is defined in the given shader stage or not.
  45547. */
  45548. hasBuiltin( name, shaderStage = this.shaderStage ) {
  45549. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  45550. }
  45551. /**
  45552. * Returns the vertex index builtin.
  45553. *
  45554. * @return {string} The vertex index.
  45555. */
  45556. getVertexIndex() {
  45557. if ( this.shaderStage === 'vertex' ) {
  45558. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  45559. }
  45560. return 'vertexIndex';
  45561. }
  45562. /**
  45563. * Builds the given shader node.
  45564. *
  45565. * @param {ShaderNodeInternal} shaderNode - The shader node.
  45566. * @return {string} The WGSL function code.
  45567. */
  45568. buildFunctionCode( shaderNode ) {
  45569. const layout = shaderNode.layout;
  45570. const flowData = this.flowShaderNode( shaderNode );
  45571. const parameters = [];
  45572. for ( const input of layout.inputs ) {
  45573. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  45574. }
  45575. //
  45576. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  45577. ${ flowData.vars }
  45578. ${ flowData.code }
  45579. `;
  45580. if ( flowData.result ) {
  45581. code += `\treturn ${ flowData.result };\n`;
  45582. }
  45583. code += '\n}\n';
  45584. //
  45585. return code;
  45586. }
  45587. /**
  45588. * Returns the instance index builtin.
  45589. *
  45590. * @return {string} The instance index.
  45591. */
  45592. getInstanceIndex() {
  45593. if ( this.shaderStage === 'vertex' ) {
  45594. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  45595. }
  45596. return 'instanceIndex';
  45597. }
  45598. /**
  45599. * Returns the invocation local index builtin.
  45600. *
  45601. * @return {string} The invocation local index.
  45602. */
  45603. getInvocationLocalIndex() {
  45604. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  45605. }
  45606. /**
  45607. * Returns the subgroup size builtin.
  45608. *
  45609. * @return {string} The subgroup size.
  45610. */
  45611. getSubgroupSize() {
  45612. this.enableSubGroups();
  45613. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45614. }
  45615. /**
  45616. * Returns the invocation subgroup index builtin.
  45617. *
  45618. * @return {string} The invocation subgroup index.
  45619. */
  45620. getInvocationSubgroupIndex() {
  45621. this.enableSubGroups();
  45622. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  45623. }
  45624. /**
  45625. * Returns the subgroup index builtin.
  45626. *
  45627. * @return {string} The subgroup index.
  45628. */
  45629. getSubgroupIndex() {
  45630. this.enableSubGroups();
  45631. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  45632. }
  45633. /**
  45634. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  45635. *
  45636. * @return {null} Null.
  45637. */
  45638. getDrawIndex() {
  45639. return null;
  45640. }
  45641. /**
  45642. * Returns the front facing builtin.
  45643. *
  45644. * @return {string} The front facing builtin.
  45645. */
  45646. getFrontFacing() {
  45647. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  45648. }
  45649. /**
  45650. * Returns the frag coord builtin.
  45651. *
  45652. * @return {string} The frag coord builtin.
  45653. */
  45654. getFragCoord() {
  45655. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  45656. }
  45657. /**
  45658. * Returns the frag depth builtin.
  45659. *
  45660. * @return {string} The frag depth builtin.
  45661. */
  45662. getFragDepth() {
  45663. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  45664. }
  45665. /**
  45666. * Returns the clip distances builtin.
  45667. *
  45668. * @return {string} The clip distances builtin.
  45669. */
  45670. getClipDistance() {
  45671. return 'varyings.hw_clip_distances';
  45672. }
  45673. /**
  45674. * Whether to flip texture data along its vertical axis or not.
  45675. *
  45676. * @return {boolean} Returns always `false` in context of WGSL.
  45677. */
  45678. isFlipY() {
  45679. return false;
  45680. }
  45681. /**
  45682. * Enables the given directive for the given shader stage.
  45683. *
  45684. * @param {string} name - The directive name.
  45685. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  45686. */
  45687. enableDirective( name, shaderStage = this.shaderStage ) {
  45688. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  45689. stage.add( name );
  45690. }
  45691. /**
  45692. * Returns the directives of the given shader stage as a WGSL string.
  45693. *
  45694. * @param {string} shaderStage - The shader stage.
  45695. * @return {string} A WGSL snippet that enables the directives of the given stage.
  45696. */
  45697. getDirectives( shaderStage ) {
  45698. const snippets = [];
  45699. const directives = this.directives[ shaderStage ];
  45700. if ( directives !== undefined ) {
  45701. for ( const directive of directives ) {
  45702. snippets.push( `enable ${directive};` );
  45703. }
  45704. }
  45705. return snippets.join( '\n' );
  45706. }
  45707. /**
  45708. * Enables the 'subgroups' directive.
  45709. */
  45710. enableSubGroups() {
  45711. this.enableDirective( 'subgroups' );
  45712. }
  45713. /**
  45714. * Enables the 'subgroups-f16' directive.
  45715. */
  45716. enableSubgroupsF16() {
  45717. this.enableDirective( 'subgroups-f16' );
  45718. }
  45719. /**
  45720. * Enables the 'clip_distances' directive.
  45721. */
  45722. enableClipDistances() {
  45723. this.enableDirective( 'clip_distances' );
  45724. }
  45725. /**
  45726. * Enables the 'f16' directive.
  45727. */
  45728. enableShaderF16() {
  45729. this.enableDirective( 'f16' );
  45730. }
  45731. /**
  45732. * Enables the 'dual_source_blending' directive.
  45733. */
  45734. enableDualSourceBlending() {
  45735. this.enableDirective( 'dual_source_blending' );
  45736. }
  45737. /**
  45738. * Enables hardware clipping.
  45739. *
  45740. * @param {string} planeCount - The clipping plane count.
  45741. */
  45742. enableHardwareClipping( planeCount ) {
  45743. this.enableClipDistances();
  45744. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  45745. }
  45746. /**
  45747. * Returns the builtins of the given shader stage as a WGSL string.
  45748. *
  45749. * @param {string} shaderStage - The shader stage.
  45750. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  45751. */
  45752. getBuiltins( shaderStage ) {
  45753. const snippets = [];
  45754. const builtins = this.builtins[ shaderStage ];
  45755. if ( builtins !== undefined ) {
  45756. for ( const { name, property, type } of builtins.values() ) {
  45757. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  45758. }
  45759. }
  45760. return snippets.join( ',\n\t' );
  45761. }
  45762. /**
  45763. * This method should be used when a new scoped buffer is used in context of
  45764. * compute shaders. It adds the array to the internal data structure which is
  45765. * later used to generate the respective WGSL.
  45766. *
  45767. * @param {string} name - The array name.
  45768. * @param {string} scope - The scope.
  45769. * @param {string} bufferType - The buffer type.
  45770. * @param {string} bufferCount - The buffer count.
  45771. * @return {string} The array name.
  45772. */
  45773. getScopedArray( name, scope, bufferType, bufferCount ) {
  45774. if ( this.scopedArrays.has( name ) === false ) {
  45775. this.scopedArrays.set( name, {
  45776. name,
  45777. scope,
  45778. bufferType,
  45779. bufferCount
  45780. } );
  45781. }
  45782. return name;
  45783. }
  45784. /**
  45785. * Returns the scoped arrays of the given shader stage as a WGSL string.
  45786. *
  45787. * @param {string} shaderStage - The shader stage.
  45788. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  45789. * Returns `undefined` when used in the vertex or fragment stage.
  45790. */
  45791. getScopedArrays( shaderStage ) {
  45792. if ( shaderStage !== 'compute' ) {
  45793. return;
  45794. }
  45795. const snippets = [];
  45796. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  45797. const type = this.getType( bufferType );
  45798. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  45799. }
  45800. return snippets.join( '\n' );
  45801. }
  45802. /**
  45803. * Returns the shader attributes of the given shader stage as a WGSL string.
  45804. *
  45805. * @param {string} shaderStage - The shader stage.
  45806. * @return {string} The WGSL snippet that defines the shader attributes.
  45807. */
  45808. getAttributes( shaderStage ) {
  45809. const snippets = [];
  45810. if ( shaderStage === 'compute' ) {
  45811. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  45812. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  45813. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  45814. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  45815. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  45816. this.enableDirective( 'subgroups', shaderStage );
  45817. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45818. }
  45819. }
  45820. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45821. const builtins = this.getBuiltins( 'attribute' );
  45822. if ( builtins ) snippets.push( builtins );
  45823. const attributes = this.getAttributesArray();
  45824. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  45825. const attribute = attributes[ index ];
  45826. const name = attribute.name;
  45827. const type = this.getType( attribute.type );
  45828. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  45829. }
  45830. }
  45831. return snippets.join( ',\n\t' );
  45832. }
  45833. /**
  45834. * Returns the members of the given struct type node as a WGSL string.
  45835. *
  45836. * @param {StructTypeNode} struct - The struct type node.
  45837. * @return {string} The WGSL snippet that defines the struct members.
  45838. */
  45839. getStructMembers( struct ) {
  45840. const snippets = [];
  45841. for ( const member of struct.members ) {
  45842. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  45843. let type = this.getType( member.type );
  45844. if ( member.atomic ) {
  45845. type = 'atomic< ' + type + ' >';
  45846. }
  45847. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  45848. }
  45849. return snippets.join( ',\n' );
  45850. }
  45851. /**
  45852. * Returns the structs of the given shader stage as a WGSL string.
  45853. *
  45854. * @param {string} shaderStage - The shader stage.
  45855. * @return {string} The WGSL snippet that defines the structs.
  45856. */
  45857. getStructs( shaderStage ) {
  45858. let result = '';
  45859. const structs = this.structs[ shaderStage ];
  45860. if ( structs.length > 0 ) {
  45861. const snippets = [];
  45862. for ( const struct of structs ) {
  45863. let snippet = `struct ${ struct.name } {\n`;
  45864. snippet += this.getStructMembers( struct );
  45865. snippet += '\n};';
  45866. snippets.push( snippet );
  45867. }
  45868. result = '\n' + snippets.join( '\n\n' ) + '\n';
  45869. }
  45870. return result;
  45871. }
  45872. /**
  45873. * Returns a WGSL string representing a variable.
  45874. *
  45875. * @param {string} type - The variable's type.
  45876. * @param {string} name - The variable's name.
  45877. * @param {?number} [count=null] - The array length.
  45878. * @return {string} The WGSL snippet that defines a variable.
  45879. */
  45880. getVar( type, name, count = null ) {
  45881. let snippet = `var ${ name } : `;
  45882. if ( count !== null ) {
  45883. snippet += this.generateArrayDeclaration( type, count );
  45884. } else {
  45885. snippet += this.getType( type );
  45886. }
  45887. return snippet;
  45888. }
  45889. /**
  45890. * Returns the variables of the given shader stage as a WGSL string.
  45891. *
  45892. * @param {string} shaderStage - The shader stage.
  45893. * @return {string} The WGSL snippet that defines the variables.
  45894. */
  45895. getVars( shaderStage ) {
  45896. const snippets = [];
  45897. const vars = this.vars[ shaderStage ];
  45898. if ( vars !== undefined ) {
  45899. for ( const variable of vars ) {
  45900. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  45901. }
  45902. }
  45903. return `\n${ snippets.join( '\n' ) }\n`;
  45904. }
  45905. /**
  45906. * Returns the varyings of the given shader stage as a WGSL string.
  45907. *
  45908. * @param {string} shaderStage - The shader stage.
  45909. * @return {string} The WGSL snippet that defines the varyings.
  45910. */
  45911. getVaryings( shaderStage ) {
  45912. const snippets = [];
  45913. if ( shaderStage === 'vertex' ) {
  45914. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  45915. }
  45916. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  45917. const varyings = this.varyings;
  45918. const vars = this.vars[ shaderStage ];
  45919. for ( let index = 0; index < varyings.length; index ++ ) {
  45920. const varying = varyings[ index ];
  45921. if ( varying.needsInterpolation ) {
  45922. let attributesSnippet = `@location( ${index} )`;
  45923. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  45924. attributesSnippet += ' @interpolate( flat )';
  45925. }
  45926. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  45927. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  45928. vars.push( varying );
  45929. }
  45930. }
  45931. }
  45932. const builtins = this.getBuiltins( shaderStage );
  45933. if ( builtins ) snippets.push( builtins );
  45934. const code = snippets.join( ',\n\t' );
  45935. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  45936. }
  45937. isCustomStruct( nodeUniform ) {
  45938. return nodeUniform.value.isStorageBufferAttribute && nodeUniform.node.structTypeNode !== null;
  45939. }
  45940. /**
  45941. * Returns the uniforms of the given shader stage as a WGSL string.
  45942. *
  45943. * @param {string} shaderStage - The shader stage.
  45944. * @return {string} The WGSL snippet that defines the uniforms.
  45945. */
  45946. getUniforms( shaderStage ) {
  45947. const uniforms = this.uniforms[ shaderStage ];
  45948. const bindingSnippets = [];
  45949. const bufferSnippets = [];
  45950. const structSnippets = [];
  45951. const uniformGroups = {};
  45952. for ( const uniform of uniforms ) {
  45953. const groupName = uniform.groupNode.name;
  45954. const uniformIndexes = this.bindingsIndexes[ groupName ];
  45955. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  45956. const texture = uniform.node.value;
  45957. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  45958. if ( this.isSampleCompare( texture ) ) {
  45959. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  45960. } else {
  45961. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  45962. }
  45963. }
  45964. let textureType;
  45965. let multisampled = '';
  45966. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45967. if ( primarySamples > 1 ) {
  45968. multisampled = '_multisampled';
  45969. }
  45970. if ( texture.isCubeTexture === true ) {
  45971. textureType = 'texture_cube<f32>';
  45972. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45973. textureType = 'texture_2d_array<f32>';
  45974. } else if ( texture.isDepthTexture === true ) {
  45975. textureType = `texture_depth${multisampled}_2d`;
  45976. } else if ( texture.isVideoTexture === true ) {
  45977. textureType = 'texture_external';
  45978. } else if ( texture.isData3DTexture === true ) {
  45979. textureType = 'texture_3d<f32>';
  45980. } else if ( uniform.node.isStorageTextureNode === true ) {
  45981. const format = getFormat( texture );
  45982. const access = this.getStorageAccess( uniform.node, shaderStage );
  45983. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  45984. } else {
  45985. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  45986. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  45987. }
  45988. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  45989. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  45990. const bufferNode = uniform.node;
  45991. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  45992. const bufferCount = bufferNode.bufferCount;
  45993. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  45994. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  45995. if ( this.isCustomStruct( uniform ) ) {
  45996. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  45997. } else {
  45998. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  45999. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  46000. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  46001. }
  46002. } else {
  46003. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  46004. const groupName = uniform.groupNode.name;
  46005. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  46006. index: uniformIndexes.binding ++,
  46007. id: uniformIndexes.group,
  46008. snippets: []
  46009. } );
  46010. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  46011. }
  46012. }
  46013. for ( const name in uniformGroups ) {
  46014. const group = uniformGroups[ name ];
  46015. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  46016. }
  46017. let code = bindingSnippets.join( '\n' );
  46018. code += bufferSnippets.join( '\n' );
  46019. code += structSnippets.join( '\n' );
  46020. return code;
  46021. }
  46022. /**
  46023. * Controls the code build of the shader stages.
  46024. */
  46025. buildCode() {
  46026. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  46027. this.sortBindingGroups();
  46028. for ( const shaderStage in shadersData ) {
  46029. this.shaderStage = shaderStage;
  46030. const stageData = shadersData[ shaderStage ];
  46031. stageData.uniforms = this.getUniforms( shaderStage );
  46032. stageData.attributes = this.getAttributes( shaderStage );
  46033. stageData.varyings = this.getVaryings( shaderStage );
  46034. stageData.structs = this.getStructs( shaderStage );
  46035. stageData.vars = this.getVars( shaderStage );
  46036. stageData.codes = this.getCodes( shaderStage );
  46037. stageData.directives = this.getDirectives( shaderStage );
  46038. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  46039. //
  46040. let flow = '// code\n\n';
  46041. flow += this.flowCode[ shaderStage ];
  46042. const flowNodes = this.flowNodes[ shaderStage ];
  46043. const mainNode = flowNodes[ flowNodes.length - 1 ];
  46044. const outputNode = mainNode.outputNode;
  46045. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  46046. for ( const node of flowNodes ) {
  46047. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  46048. const slotName = node.name;
  46049. if ( slotName ) {
  46050. if ( flow.length > 0 ) flow += '\n';
  46051. flow += `\t// flow -> ${ slotName }\n`;
  46052. }
  46053. flow += `${ flowSlotData.code }\n\t`;
  46054. if ( node === mainNode && shaderStage !== 'compute' ) {
  46055. flow += '// result\n\n\t';
  46056. if ( shaderStage === 'vertex' ) {
  46057. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  46058. } else if ( shaderStage === 'fragment' ) {
  46059. if ( isOutputStruct ) {
  46060. stageData.returnType = outputNode.getNodeType( this );
  46061. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  46062. flow += `return ${ flowSlotData.result };`;
  46063. } else {
  46064. let structSnippet = '\t@location(0) color: vec4<f32>';
  46065. const builtins = this.getBuiltins( 'output' );
  46066. if ( builtins ) structSnippet += ',\n\t' + builtins;
  46067. stageData.returnType = 'OutputStruct';
  46068. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  46069. stageData.structs += '\nvar<private> output : OutputStruct;';
  46070. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  46071. }
  46072. }
  46073. }
  46074. }
  46075. stageData.flow = flow;
  46076. }
  46077. this.shaderStage = null;
  46078. if ( this.material !== null ) {
  46079. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  46080. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  46081. } else {
  46082. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  46083. }
  46084. }
  46085. /**
  46086. * Returns the native shader method name for a given generic name.
  46087. *
  46088. * @param {string} method - The method name to resolve.
  46089. * @param {string} [output=null] - An optional output.
  46090. * @return {string} The resolved WGSL method name.
  46091. */
  46092. getMethod( method, output = null ) {
  46093. let wgslMethod;
  46094. if ( output !== null ) {
  46095. wgslMethod = this._getWGSLMethod( method + '_' + output );
  46096. }
  46097. if ( wgslMethod === undefined ) {
  46098. wgslMethod = this._getWGSLMethod( method );
  46099. }
  46100. return wgslMethod || method;
  46101. }
  46102. /**
  46103. * Returns the WGSL type of the given node data type.
  46104. *
  46105. * @param {string} type - The node data type.
  46106. * @return {string} The WGSL type.
  46107. */
  46108. getType( type ) {
  46109. return wgslTypeLib[ type ] || type;
  46110. }
  46111. /**
  46112. * Whether the requested feature is available or not.
  46113. *
  46114. * @param {string} name - The requested feature.
  46115. * @return {boolean} Whether the requested feature is supported or not.
  46116. */
  46117. isAvailable( name ) {
  46118. let result = supports[ name ];
  46119. if ( result === undefined ) {
  46120. if ( name === 'float32Filterable' ) {
  46121. result = this.renderer.hasFeature( 'float32-filterable' );
  46122. } else if ( name === 'clipDistance' ) {
  46123. result = this.renderer.hasFeature( 'clip-distances' );
  46124. }
  46125. supports[ name ] = result;
  46126. }
  46127. return result;
  46128. }
  46129. /**
  46130. * Returns the native shader method name for a given generic name.
  46131. *
  46132. * @private
  46133. * @param {string} method - The method name to resolve.
  46134. * @return {string} The resolved WGSL method name.
  46135. */
  46136. _getWGSLMethod( method ) {
  46137. if ( wgslPolyfill[ method ] !== undefined ) {
  46138. this._include( method );
  46139. }
  46140. return wgslMethods[ method ];
  46141. }
  46142. /**
  46143. * Includes the given method name into the current
  46144. * function node.
  46145. *
  46146. * @private
  46147. * @param {string} name - The method name to include.
  46148. * @return {CodeNode} The respective code node.
  46149. */
  46150. _include( name ) {
  46151. const codeNode = wgslPolyfill[ name ];
  46152. codeNode.build( this );
  46153. if ( this.currentFunctionNode !== null ) {
  46154. this.currentFunctionNode.includes.push( codeNode );
  46155. }
  46156. return codeNode;
  46157. }
  46158. /**
  46159. * Returns a WGSL vertex shader based on the given shader data.
  46160. *
  46161. * @private
  46162. * @param {Object} shaderData - The shader data.
  46163. * @return {string} The vertex shader.
  46164. */
  46165. _getWGSLVertexCode( shaderData ) {
  46166. return `${ this.getSignature() }
  46167. // directives
  46168. ${shaderData.directives}
  46169. // structs
  46170. ${shaderData.structs}
  46171. // uniforms
  46172. ${shaderData.uniforms}
  46173. // varyings
  46174. ${shaderData.varyings}
  46175. var<private> varyings : VaryingsStruct;
  46176. // codes
  46177. ${shaderData.codes}
  46178. @vertex
  46179. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  46180. // vars
  46181. ${shaderData.vars}
  46182. // flow
  46183. ${shaderData.flow}
  46184. return varyings;
  46185. }
  46186. `;
  46187. }
  46188. /**
  46189. * Returns a WGSL fragment shader based on the given shader data.
  46190. *
  46191. * @private
  46192. * @param {Object} shaderData - The shader data.
  46193. * @return {string} The vertex shader.
  46194. */
  46195. _getWGSLFragmentCode( shaderData ) {
  46196. return `${ this.getSignature() }
  46197. // global
  46198. ${ diagnostics }
  46199. // structs
  46200. ${shaderData.structs}
  46201. // uniforms
  46202. ${shaderData.uniforms}
  46203. // codes
  46204. ${shaderData.codes}
  46205. @fragment
  46206. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  46207. // vars
  46208. ${shaderData.vars}
  46209. // flow
  46210. ${shaderData.flow}
  46211. }
  46212. `;
  46213. }
  46214. /**
  46215. * Returns a WGSL compute shader based on the given shader data.
  46216. *
  46217. * @private
  46218. * @param {Object} shaderData - The shader data.
  46219. * @param {string} workgroupSize - The workgroup size.
  46220. * @return {string} The vertex shader.
  46221. */
  46222. _getWGSLComputeCode( shaderData, workgroupSize ) {
  46223. return `${ this.getSignature() }
  46224. // directives
  46225. ${shaderData.directives}
  46226. // system
  46227. var<private> instanceIndex : u32;
  46228. // locals
  46229. ${shaderData.scopedArrays}
  46230. // structs
  46231. ${shaderData.structs}
  46232. // uniforms
  46233. ${shaderData.uniforms}
  46234. // codes
  46235. ${shaderData.codes}
  46236. @compute @workgroup_size( ${workgroupSize} )
  46237. fn main( ${shaderData.attributes} ) {
  46238. // system
  46239. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  46240. // vars
  46241. ${shaderData.vars}
  46242. // flow
  46243. ${shaderData.flow}
  46244. }
  46245. `;
  46246. }
  46247. /**
  46248. * Returns a WGSL struct based on the given name and variables.
  46249. *
  46250. * @private
  46251. * @param {string} name - The struct name.
  46252. * @param {string} vars - The struct variables.
  46253. * @return {string} The WGSL snippet representing a struct.
  46254. */
  46255. _getWGSLStruct( name, vars ) {
  46256. return `
  46257. struct ${name} {
  46258. ${vars}
  46259. };`;
  46260. }
  46261. /**
  46262. * Returns a WGSL struct binding.
  46263. *
  46264. * @private
  46265. * @param {string} name - The struct name.
  46266. * @param {string} vars - The struct variables.
  46267. * @param {string} access - The access.
  46268. * @param {number} [binding=0] - The binding index.
  46269. * @param {number} [group=0] - The group index.
  46270. * @return {string} The WGSL snippet representing a struct binding.
  46271. */
  46272. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  46273. const structName = name + 'Struct';
  46274. const structSnippet = this._getWGSLStruct( structName, vars );
  46275. return `${structSnippet}
  46276. @binding( ${ binding } ) @group( ${ group } )
  46277. var<${access}> ${ name } : ${ structName };`;
  46278. }
  46279. }
  46280. /**
  46281. * A WebGPU backend utility module with common helpers.
  46282. *
  46283. * @private
  46284. */
  46285. class WebGPUUtils {
  46286. /**
  46287. * Constructs a new utility object.
  46288. *
  46289. * @param {WebGPUBackend} backend - The WebGPU backend.
  46290. */
  46291. constructor( backend ) {
  46292. /**
  46293. * A reference to the WebGPU backend.
  46294. *
  46295. * @type {WebGPUBackend}
  46296. */
  46297. this.backend = backend;
  46298. }
  46299. /**
  46300. * Returns the depth/stencil GPU format for the given render context.
  46301. *
  46302. * @param {RenderContext} renderContext - The render context.
  46303. * @return {string} The depth/stencil GPU texture format.
  46304. */
  46305. getCurrentDepthStencilFormat( renderContext ) {
  46306. let format;
  46307. if ( renderContext.depthTexture !== null ) {
  46308. format = this.getTextureFormatGPU( renderContext.depthTexture );
  46309. } else if ( renderContext.depth && renderContext.stencil ) {
  46310. format = GPUTextureFormat.Depth24PlusStencil8;
  46311. } else if ( renderContext.depth ) {
  46312. format = GPUTextureFormat.Depth24Plus;
  46313. }
  46314. return format;
  46315. }
  46316. /**
  46317. * Returns the GPU format for the given texture.
  46318. *
  46319. * @param {Texture} texture - The texture.
  46320. * @return {string} The GPU texture format.
  46321. */
  46322. getTextureFormatGPU( texture ) {
  46323. return this.backend.get( texture ).format;
  46324. }
  46325. /**
  46326. * Returns an object that defines the multi-sampling state of the given texture.
  46327. *
  46328. * @param {Texture} texture - The texture.
  46329. * @return {Object} The multi-sampling state.
  46330. */
  46331. getTextureSampleData( texture ) {
  46332. let samples;
  46333. if ( texture.isFramebufferTexture ) {
  46334. samples = 1;
  46335. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  46336. const renderer = this.backend.renderer;
  46337. const renderTarget = renderer.getRenderTarget();
  46338. samples = renderTarget ? renderTarget.samples : renderer.samples;
  46339. } else if ( texture.renderTarget ) {
  46340. samples = texture.renderTarget.samples;
  46341. }
  46342. samples = samples || 1;
  46343. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  46344. const primarySamples = isMSAA ? 1 : samples;
  46345. return { samples, primarySamples, isMSAA };
  46346. }
  46347. /**
  46348. * Returns the default color attachment's GPU format of the current render context.
  46349. *
  46350. * @param {RenderContext} renderContext - The render context.
  46351. * @return {string} The GPU texture format of the default color attachment.
  46352. */
  46353. getCurrentColorFormat( renderContext ) {
  46354. let format;
  46355. if ( renderContext.textures !== null ) {
  46356. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  46357. } else {
  46358. format = this.getPreferredCanvasFormat(); // default context format
  46359. }
  46360. return format;
  46361. }
  46362. /**
  46363. * Returns the output color space of the current render context.
  46364. *
  46365. * @param {RenderContext} renderContext - The render context.
  46366. * @return {string} The output color space.
  46367. */
  46368. getCurrentColorSpace( renderContext ) {
  46369. if ( renderContext.textures !== null ) {
  46370. return renderContext.textures[ 0 ].colorSpace;
  46371. }
  46372. return this.backend.renderer.outputColorSpace;
  46373. }
  46374. /**
  46375. * Returns GPU primitive topology for the given object and material.
  46376. *
  46377. * @param {Object3D} object - The 3D object.
  46378. * @param {Material} material - The material.
  46379. * @return {string} The GPU primitive topology.
  46380. */
  46381. getPrimitiveTopology( object, material ) {
  46382. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  46383. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  46384. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  46385. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  46386. }
  46387. /**
  46388. * Returns a modified sample count from the given sample count value.
  46389. *
  46390. * That is required since WebGPU does not support arbitrary sample counts.
  46391. *
  46392. * @param {number} sampleCount - The input sample count.
  46393. * @return {number} The (potentially updated) output sample count.
  46394. */
  46395. getSampleCount( sampleCount ) {
  46396. let count = 1;
  46397. if ( sampleCount > 1 ) {
  46398. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  46399. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  46400. if ( count === 2 ) {
  46401. count = 4;
  46402. }
  46403. }
  46404. return count;
  46405. }
  46406. /**
  46407. * Returns the sample count of the given render context.
  46408. *
  46409. * @param {RenderContext} renderContext - The render context.
  46410. * @return {number} The sample count.
  46411. */
  46412. getSampleCountRenderContext( renderContext ) {
  46413. if ( renderContext.textures !== null ) {
  46414. return this.getSampleCount( renderContext.sampleCount );
  46415. }
  46416. return this.getSampleCount( this.backend.renderer.samples );
  46417. }
  46418. /**
  46419. * Returns the preferred canvas format.
  46420. *
  46421. * There is a separate method for this so it's possible to
  46422. * honor edge cases for specific devices.
  46423. *
  46424. * @return {string} The GPU texture format of the canvas.
  46425. */
  46426. getPreferredCanvasFormat() {
  46427. const outputType = this.backend.parameters.outputType;
  46428. if ( outputType === undefined ) {
  46429. return navigator.gpu.getPreferredCanvasFormat();
  46430. } else if ( outputType === UnsignedByteType ) {
  46431. return GPUTextureFormat.BGRA8Unorm;
  46432. } else if ( outputType === HalfFloatType ) {
  46433. return GPUTextureFormat.RGBA16Float;
  46434. } else {
  46435. throw new Error( 'Unsupported outputType' );
  46436. }
  46437. }
  46438. }
  46439. const typedArraysToVertexFormatPrefix = new Map( [
  46440. [ Int8Array, [ 'sint8', 'snorm8' ]],
  46441. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  46442. [ Int16Array, [ 'sint16', 'snorm16' ]],
  46443. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  46444. [ Int32Array, [ 'sint32', 'snorm32' ]],
  46445. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  46446. [ Float32Array, [ 'float32', ]],
  46447. ] );
  46448. const typedAttributeToVertexFormatPrefix = new Map( [
  46449. [ Float16BufferAttribute, [ 'float16', ]],
  46450. ] );
  46451. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  46452. [ Int32Array, 'sint32' ],
  46453. [ Int16Array, 'sint32' ], // patch for INT16
  46454. [ Uint32Array, 'uint32' ],
  46455. [ Uint16Array, 'uint32' ], // patch for UINT16
  46456. [ Float32Array, 'float32' ]
  46457. ] );
  46458. /**
  46459. * A WebGPU backend utility module for managing shader attributes.
  46460. *
  46461. * @private
  46462. */
  46463. class WebGPUAttributeUtils {
  46464. /**
  46465. * Constructs a new utility object.
  46466. *
  46467. * @param {WebGPUBackend} backend - The WebGPU backend.
  46468. */
  46469. constructor( backend ) {
  46470. /**
  46471. * A reference to the WebGPU backend.
  46472. *
  46473. * @type {WebGPUBackend}
  46474. */
  46475. this.backend = backend;
  46476. }
  46477. /**
  46478. * Creates the GPU buffer for the given buffer attribute.
  46479. *
  46480. * @param {BufferAttribute} attribute - The buffer attribute.
  46481. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  46482. */
  46483. createAttribute( attribute, usage ) {
  46484. const bufferAttribute = this._getBufferAttribute( attribute );
  46485. const backend = this.backend;
  46486. const bufferData = backend.get( bufferAttribute );
  46487. let buffer = bufferData.buffer;
  46488. if ( buffer === undefined ) {
  46489. const device = backend.device;
  46490. let array = bufferAttribute.array;
  46491. // patch for INT16 and UINT16
  46492. if ( attribute.normalized === false ) {
  46493. if ( array.constructor === Int16Array ) {
  46494. array = new Int32Array( array );
  46495. } else if ( array.constructor === Uint16Array ) {
  46496. array = new Uint32Array( array );
  46497. if ( usage & GPUBufferUsage.INDEX ) {
  46498. for ( let i = 0; i < array.length; i ++ ) {
  46499. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  46500. }
  46501. }
  46502. }
  46503. }
  46504. bufferAttribute.array = array;
  46505. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  46506. array = new array.constructor( bufferAttribute.count * 4 );
  46507. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  46508. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  46509. }
  46510. // Update BufferAttribute
  46511. bufferAttribute.itemSize = 4;
  46512. bufferAttribute.array = array;
  46513. }
  46514. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  46515. buffer = device.createBuffer( {
  46516. label: bufferAttribute.name,
  46517. size: size,
  46518. usage: usage,
  46519. mappedAtCreation: true
  46520. } );
  46521. new array.constructor( buffer.getMappedRange() ).set( array );
  46522. buffer.unmap();
  46523. bufferData.buffer = buffer;
  46524. }
  46525. }
  46526. /**
  46527. * Updates the GPU buffer of the given buffer attribute.
  46528. *
  46529. * @param {BufferAttribute} attribute - The buffer attribute.
  46530. */
  46531. updateAttribute( attribute ) {
  46532. const bufferAttribute = this._getBufferAttribute( attribute );
  46533. const backend = this.backend;
  46534. const device = backend.device;
  46535. const buffer = backend.get( bufferAttribute ).buffer;
  46536. const array = bufferAttribute.array;
  46537. const isTypedArray = this._isTypedArray( array );
  46538. const updateRanges = bufferAttribute.updateRanges;
  46539. if ( updateRanges.length === 0 ) {
  46540. // Not using update ranges
  46541. device.queue.writeBuffer(
  46542. buffer,
  46543. 0,
  46544. array,
  46545. 0
  46546. );
  46547. } else {
  46548. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  46549. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  46550. const range = updateRanges[ i ];
  46551. const dataOffset = range.start * byteOffsetFactor;
  46552. const size = range.count * byteOffsetFactor;
  46553. device.queue.writeBuffer(
  46554. buffer,
  46555. 0,
  46556. array,
  46557. dataOffset,
  46558. size
  46559. );
  46560. }
  46561. bufferAttribute.clearUpdateRanges();
  46562. }
  46563. }
  46564. /**
  46565. * This method creates the vertex buffer layout data which are
  46566. * require when creating a render pipeline for the given render object.
  46567. *
  46568. * @param {RenderObject} renderObject - The render object.
  46569. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  46570. */
  46571. createShaderVertexBuffers( renderObject ) {
  46572. const attributes = renderObject.getAttributes();
  46573. const vertexBuffers = new Map();
  46574. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  46575. const geometryAttribute = attributes[ slot ];
  46576. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  46577. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  46578. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  46579. if ( vertexBufferLayout === undefined ) {
  46580. let arrayStride, stepMode;
  46581. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  46582. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  46583. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  46584. } else {
  46585. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  46586. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  46587. }
  46588. // patch for INT16 and UINT16
  46589. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  46590. arrayStride = 4;
  46591. }
  46592. vertexBufferLayout = {
  46593. arrayStride,
  46594. attributes: [],
  46595. stepMode
  46596. };
  46597. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  46598. }
  46599. const format = this._getVertexFormat( geometryAttribute );
  46600. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  46601. vertexBufferLayout.attributes.push( {
  46602. shaderLocation: slot,
  46603. offset,
  46604. format
  46605. } );
  46606. }
  46607. return Array.from( vertexBuffers.values() );
  46608. }
  46609. /**
  46610. * Destroys the GPU buffer of the given buffer attribute.
  46611. *
  46612. * @param {BufferAttribute} attribute - The buffer attribute.
  46613. */
  46614. destroyAttribute( attribute ) {
  46615. const backend = this.backend;
  46616. const data = backend.get( this._getBufferAttribute( attribute ) );
  46617. data.buffer.destroy();
  46618. backend.delete( attribute );
  46619. }
  46620. /**
  46621. * This method performs a readback operation by moving buffer data from
  46622. * a storage buffer attribute from the GPU to the CPU.
  46623. *
  46624. * @async
  46625. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46626. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46627. */
  46628. async getArrayBufferAsync( attribute ) {
  46629. const backend = this.backend;
  46630. const device = backend.device;
  46631. const data = backend.get( this._getBufferAttribute( attribute ) );
  46632. const bufferGPU = data.buffer;
  46633. const size = bufferGPU.size;
  46634. const readBufferGPU = device.createBuffer( {
  46635. label: `${ attribute.name }_readback`,
  46636. size,
  46637. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46638. } );
  46639. const cmdEncoder = device.createCommandEncoder( {
  46640. label: `readback_encoder_${ attribute.name }`
  46641. } );
  46642. cmdEncoder.copyBufferToBuffer(
  46643. bufferGPU,
  46644. 0,
  46645. readBufferGPU,
  46646. 0,
  46647. size
  46648. );
  46649. const gpuCommands = cmdEncoder.finish();
  46650. device.queue.submit( [ gpuCommands ] );
  46651. await readBufferGPU.mapAsync( GPUMapMode.READ );
  46652. const arrayBuffer = readBufferGPU.getMappedRange();
  46653. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  46654. readBufferGPU.unmap();
  46655. return dstBuffer.buffer;
  46656. }
  46657. /**
  46658. * Returns the vertex format of the given buffer attribute.
  46659. *
  46660. * @private
  46661. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  46662. * @return {string} The vertex format (e.g. 'float32x3').
  46663. */
  46664. _getVertexFormat( geometryAttribute ) {
  46665. const { itemSize, normalized } = geometryAttribute;
  46666. const ArrayType = geometryAttribute.array.constructor;
  46667. const AttributeType = geometryAttribute.constructor;
  46668. let format;
  46669. if ( itemSize === 1 ) {
  46670. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  46671. } else {
  46672. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  46673. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  46674. if ( prefix ) {
  46675. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  46676. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  46677. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  46678. if ( paddedItemSize % 1 ) {
  46679. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  46680. }
  46681. format = `${prefix}x${paddedItemSize}`;
  46682. }
  46683. }
  46684. if ( ! format ) {
  46685. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  46686. }
  46687. return format;
  46688. }
  46689. /**
  46690. * Returns `true` if the given array is a typed array.
  46691. *
  46692. * @private
  46693. * @param {any} array - The array.
  46694. * @return {boolean} Whether the given array is a typed array or not.
  46695. */
  46696. _isTypedArray( array ) {
  46697. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  46698. }
  46699. /**
  46700. * Utility method for handling interleaved buffer attributes correctly.
  46701. * To process them, their `InterleavedBuffer` is returned.
  46702. *
  46703. * @private
  46704. * @param {BufferAttribute} attribute - The attribute.
  46705. * @return {BufferAttribute|InterleavedBuffer}
  46706. */
  46707. _getBufferAttribute( attribute ) {
  46708. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  46709. return attribute;
  46710. }
  46711. }
  46712. /**
  46713. * A WebGPU backend utility module for managing bindings.
  46714. *
  46715. * When reading the documentation it's helpful to keep in mind that
  46716. * all class definitions starting with 'GPU*' are modules from the
  46717. * WebGPU API. So for example `BindGroup` is a class from the engine
  46718. * whereas `GPUBindGroup` is a class from WebGPU.
  46719. *
  46720. * @private
  46721. */
  46722. class WebGPUBindingUtils {
  46723. /**
  46724. * Constructs a new utility object.
  46725. *
  46726. * @param {WebGPUBackend} backend - The WebGPU backend.
  46727. */
  46728. constructor( backend ) {
  46729. /**
  46730. * A reference to the WebGPU backend.
  46731. *
  46732. * @type {WebGPUBackend}
  46733. */
  46734. this.backend = backend;
  46735. /**
  46736. * A cache for managing bind group layouts.
  46737. *
  46738. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  46739. */
  46740. this.bindGroupLayoutCache = new WeakMap();
  46741. }
  46742. /**
  46743. * Creates a GPU bind group layout for the given bind group.
  46744. *
  46745. * @param {BindGroup} bindGroup - The bind group.
  46746. * @return {GPUBindGroupLayout} The GPU bind group layout.
  46747. */
  46748. createBindingsLayout( bindGroup ) {
  46749. const backend = this.backend;
  46750. const device = backend.device;
  46751. const entries = [];
  46752. let index = 0;
  46753. for ( const binding of bindGroup.bindings ) {
  46754. const bindingGPU = {
  46755. binding: index ++,
  46756. visibility: binding.visibility
  46757. };
  46758. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  46759. const buffer = {}; // GPUBufferBindingLayout
  46760. if ( binding.isStorageBuffer ) {
  46761. if ( binding.visibility & 4 ) {
  46762. // compute
  46763. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  46764. buffer.type = GPUBufferBindingType.Storage;
  46765. } else {
  46766. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  46767. }
  46768. } else {
  46769. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  46770. }
  46771. }
  46772. bindingGPU.buffer = buffer;
  46773. } else if ( binding.isSampler ) {
  46774. const sampler = {}; // GPUSamplerBindingLayout
  46775. if ( binding.texture.isDepthTexture ) {
  46776. if ( binding.texture.compareFunction !== null ) {
  46777. sampler.type = 'comparison';
  46778. }
  46779. }
  46780. bindingGPU.sampler = sampler;
  46781. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  46782. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  46783. } else if ( binding.isSampledTexture && binding.store ) {
  46784. const storageTexture = {}; // GPUStorageTextureBindingLayout
  46785. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  46786. const access = binding.access;
  46787. if ( access === NodeAccess.READ_WRITE ) {
  46788. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  46789. } else if ( access === NodeAccess.WRITE_ONLY ) {
  46790. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  46791. } else {
  46792. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  46793. }
  46794. bindingGPU.storageTexture = storageTexture;
  46795. } else if ( binding.isSampledTexture ) {
  46796. const texture = {}; // GPUTextureBindingLayout
  46797. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  46798. if ( primarySamples > 1 ) {
  46799. texture.multisampled = true;
  46800. if ( ! binding.texture.isDepthTexture ) {
  46801. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46802. }
  46803. }
  46804. if ( binding.texture.isDepthTexture ) {
  46805. texture.sampleType = GPUTextureSampleType.Depth;
  46806. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  46807. const type = binding.texture.type;
  46808. if ( type === IntType ) {
  46809. texture.sampleType = GPUTextureSampleType.SInt;
  46810. } else if ( type === UnsignedIntType ) {
  46811. texture.sampleType = GPUTextureSampleType.UInt;
  46812. } else if ( type === FloatType ) {
  46813. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  46814. texture.sampleType = GPUTextureSampleType.Float;
  46815. } else {
  46816. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46817. }
  46818. }
  46819. }
  46820. if ( binding.isSampledCubeTexture ) {
  46821. texture.viewDimension = GPUTextureViewDimension.Cube;
  46822. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46823. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  46824. } else if ( binding.isSampledTexture3D ) {
  46825. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  46826. }
  46827. bindingGPU.texture = texture;
  46828. } else {
  46829. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  46830. }
  46831. entries.push( bindingGPU );
  46832. }
  46833. return device.createBindGroupLayout( { entries } );
  46834. }
  46835. /**
  46836. * Creates bindings from the given bind group definition.
  46837. *
  46838. * @param {BindGroup} bindGroup - The bind group.
  46839. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46840. * @param {number} cacheIndex - The cache index.
  46841. * @param {number} version - The version.
  46842. */
  46843. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  46844. const { backend, bindGroupLayoutCache } = this;
  46845. const bindingsData = backend.get( bindGroup );
  46846. // setup (static) binding layout and (dynamic) binding group
  46847. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  46848. if ( bindLayoutGPU === undefined ) {
  46849. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  46850. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  46851. }
  46852. let bindGroupGPU;
  46853. if ( cacheIndex > 0 ) {
  46854. if ( bindingsData.groups === undefined ) {
  46855. bindingsData.groups = [];
  46856. bindingsData.versions = [];
  46857. }
  46858. if ( bindingsData.versions[ cacheIndex ] === version ) {
  46859. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  46860. }
  46861. }
  46862. if ( bindGroupGPU === undefined ) {
  46863. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  46864. if ( cacheIndex > 0 ) {
  46865. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  46866. bindingsData.versions[ cacheIndex ] = version;
  46867. }
  46868. }
  46869. bindingsData.group = bindGroupGPU;
  46870. bindingsData.layout = bindLayoutGPU;
  46871. }
  46872. /**
  46873. * Updates a buffer binding.
  46874. *
  46875. * @param {Buffer} binding - The buffer binding to update.
  46876. */
  46877. updateBinding( binding ) {
  46878. const backend = this.backend;
  46879. const device = backend.device;
  46880. const buffer = binding.buffer;
  46881. const bufferGPU = backend.get( binding ).buffer;
  46882. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  46883. }
  46884. /**
  46885. * Creates a GPU bind group for the camera index.
  46886. *
  46887. * @param {Uint32Array} data - The index data.
  46888. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  46889. * @return {GPUBindGroup} The GPU bind group.
  46890. */
  46891. createBindGroupIndex( data, layout ) {
  46892. const backend = this.backend;
  46893. const device = backend.device;
  46894. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46895. const index = data[ 0 ];
  46896. const buffer = device.createBuffer( {
  46897. label: 'bindingCameraIndex_' + index,
  46898. size: 16, // uint(4) * 4
  46899. usage: usage
  46900. } );
  46901. device.queue.writeBuffer( buffer, 0, data, 0 );
  46902. const entries = [ { binding: 0, resource: { buffer } } ];
  46903. return device.createBindGroup( {
  46904. label: 'bindGroupCameraIndex_' + index,
  46905. layout,
  46906. entries
  46907. } );
  46908. }
  46909. /**
  46910. * Creates a GPU bind group for the given bind group and GPU layout.
  46911. *
  46912. * @param {BindGroup} bindGroup - The bind group.
  46913. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  46914. * @return {GPUBindGroup} The GPU bind group.
  46915. */
  46916. createBindGroup( bindGroup, layoutGPU ) {
  46917. const backend = this.backend;
  46918. const device = backend.device;
  46919. let bindingPoint = 0;
  46920. const entriesGPU = [];
  46921. for ( const binding of bindGroup.bindings ) {
  46922. if ( binding.isUniformBuffer ) {
  46923. const bindingData = backend.get( binding );
  46924. if ( bindingData.buffer === undefined ) {
  46925. const byteLength = binding.byteLength;
  46926. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46927. const bufferGPU = device.createBuffer( {
  46928. label: 'bindingBuffer_' + binding.name,
  46929. size: byteLength,
  46930. usage: usage
  46931. } );
  46932. bindingData.buffer = bufferGPU;
  46933. }
  46934. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46935. } else if ( binding.isStorageBuffer ) {
  46936. const bindingData = backend.get( binding );
  46937. if ( bindingData.buffer === undefined ) {
  46938. const attribute = binding.attribute;
  46939. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  46940. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  46941. bindingData.buffer = backend.get( attribute ).buffer;
  46942. }
  46943. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46944. } else if ( binding.isSampler ) {
  46945. const textureGPU = backend.get( binding.texture );
  46946. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  46947. } else if ( binding.isSampledTexture ) {
  46948. const textureData = backend.get( binding.texture );
  46949. let resourceGPU;
  46950. if ( textureData.externalTexture !== undefined ) {
  46951. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  46952. } else {
  46953. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  46954. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  46955. resourceGPU = textureData[ propertyName ];
  46956. if ( resourceGPU === undefined ) {
  46957. const aspectGPU = GPUTextureAspect.All;
  46958. let dimensionViewGPU;
  46959. if ( binding.isSampledCubeTexture ) {
  46960. dimensionViewGPU = GPUTextureViewDimension.Cube;
  46961. } else if ( binding.isSampledTexture3D ) {
  46962. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  46963. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46964. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  46965. } else {
  46966. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  46967. }
  46968. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  46969. }
  46970. }
  46971. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  46972. }
  46973. bindingPoint ++;
  46974. }
  46975. return device.createBindGroup( {
  46976. label: 'bindGroup_' + bindGroup.name,
  46977. layout: layoutGPU,
  46978. entries: entriesGPU
  46979. } );
  46980. }
  46981. }
  46982. /**
  46983. * A WebGPU backend utility module for managing pipelines.
  46984. *
  46985. * @private
  46986. */
  46987. class WebGPUPipelineUtils {
  46988. /**
  46989. * Constructs a new utility object.
  46990. *
  46991. * @param {WebGPUBackend} backend - The WebGPU backend.
  46992. */
  46993. constructor( backend ) {
  46994. /**
  46995. * A reference to the WebGPU backend.
  46996. *
  46997. * @type {WebGPUBackend}
  46998. */
  46999. this.backend = backend;
  47000. }
  47001. /**
  47002. * Returns the sample count derived from the given render context.
  47003. *
  47004. * @private
  47005. * @param {RenderContext} renderContext - The render context.
  47006. * @return {number} The sample count.
  47007. */
  47008. _getSampleCount( renderContext ) {
  47009. return this.backend.utils.getSampleCountRenderContext( renderContext );
  47010. }
  47011. /**
  47012. * Creates a render pipeline for the given render object.
  47013. *
  47014. * @param {RenderObject} renderObject - The render object.
  47015. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47016. */
  47017. createRenderPipeline( renderObject, promises ) {
  47018. const { object, material, geometry, pipeline } = renderObject;
  47019. const { vertexProgram, fragmentProgram } = pipeline;
  47020. const backend = this.backend;
  47021. const device = backend.device;
  47022. const utils = backend.utils;
  47023. const pipelineData = backend.get( pipeline );
  47024. // bind group layouts
  47025. const bindGroupLayouts = [];
  47026. for ( const bindGroup of renderObject.getBindings() ) {
  47027. const bindingsData = backend.get( bindGroup );
  47028. bindGroupLayouts.push( bindingsData.layout );
  47029. }
  47030. // vertex buffers
  47031. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  47032. // blending
  47033. let blending;
  47034. if ( material.transparent === true && material.blending !== NoBlending ) {
  47035. blending = this._getBlending( material );
  47036. }
  47037. // stencil
  47038. let stencilFront = {};
  47039. if ( material.stencilWrite === true ) {
  47040. stencilFront = {
  47041. compare: this._getStencilCompare( material ),
  47042. failOp: this._getStencilOperation( material.stencilFail ),
  47043. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  47044. passOp: this._getStencilOperation( material.stencilZPass )
  47045. };
  47046. }
  47047. const colorWriteMask = this._getColorWriteMask( material );
  47048. const targets = [];
  47049. if ( renderObject.context.textures !== null ) {
  47050. const textures = renderObject.context.textures;
  47051. for ( let i = 0; i < textures.length; i ++ ) {
  47052. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  47053. targets.push( {
  47054. format: colorFormat,
  47055. blend: blending,
  47056. writeMask: colorWriteMask
  47057. } );
  47058. }
  47059. } else {
  47060. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  47061. targets.push( {
  47062. format: colorFormat,
  47063. blend: blending,
  47064. writeMask: colorWriteMask
  47065. } );
  47066. }
  47067. const vertexModule = backend.get( vertexProgram ).module;
  47068. const fragmentModule = backend.get( fragmentProgram ).module;
  47069. const primitiveState = this._getPrimitiveState( object, geometry, material );
  47070. const depthCompare = this._getDepthCompare( material );
  47071. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  47072. const sampleCount = this._getSampleCount( renderObject.context );
  47073. const pipelineDescriptor = {
  47074. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  47075. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  47076. fragment: Object.assign( {}, fragmentModule, { targets } ),
  47077. primitive: primitiveState,
  47078. multisample: {
  47079. count: sampleCount,
  47080. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  47081. },
  47082. layout: device.createPipelineLayout( {
  47083. bindGroupLayouts
  47084. } )
  47085. };
  47086. const depthStencil = {};
  47087. const renderDepth = renderObject.context.depth;
  47088. const renderStencil = renderObject.context.stencil;
  47089. if ( renderDepth === true || renderStencil === true ) {
  47090. if ( renderDepth === true ) {
  47091. depthStencil.format = depthStencilFormat;
  47092. depthStencil.depthWriteEnabled = material.depthWrite;
  47093. depthStencil.depthCompare = depthCompare;
  47094. }
  47095. if ( renderStencil === true ) {
  47096. depthStencil.stencilFront = stencilFront;
  47097. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  47098. depthStencil.stencilReadMask = material.stencilFuncMask;
  47099. depthStencil.stencilWriteMask = material.stencilWriteMask;
  47100. }
  47101. pipelineDescriptor.depthStencil = depthStencil;
  47102. }
  47103. if ( promises === null ) {
  47104. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  47105. } else {
  47106. const p = new Promise( ( resolve /*, reject*/ ) => {
  47107. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  47108. pipelineData.pipeline = pipeline;
  47109. resolve();
  47110. } );
  47111. } );
  47112. promises.push( p );
  47113. }
  47114. }
  47115. /**
  47116. * Creates GPU render bundle encoder for the given render context.
  47117. *
  47118. * @param {RenderContext} renderContext - The render context.
  47119. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  47120. */
  47121. createBundleEncoder( renderContext ) {
  47122. const backend = this.backend;
  47123. const { utils, device } = backend;
  47124. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  47125. const colorFormat = utils.getCurrentColorFormat( renderContext );
  47126. const sampleCount = this._getSampleCount( renderContext );
  47127. const descriptor = {
  47128. label: 'renderBundleEncoder',
  47129. colorFormats: [ colorFormat ],
  47130. depthStencilFormat,
  47131. sampleCount
  47132. };
  47133. return device.createRenderBundleEncoder( descriptor );
  47134. }
  47135. /**
  47136. * Creates a compute pipeline for the given compute node.
  47137. *
  47138. * @param {ComputePipeline} pipeline - The compute pipeline.
  47139. * @param {Array<BindGroup>} bindings - The bindings.
  47140. */
  47141. createComputePipeline( pipeline, bindings ) {
  47142. const backend = this.backend;
  47143. const device = backend.device;
  47144. const computeProgram = backend.get( pipeline.computeProgram ).module;
  47145. const pipelineGPU = backend.get( pipeline );
  47146. // bind group layouts
  47147. const bindGroupLayouts = [];
  47148. for ( const bindingsGroup of bindings ) {
  47149. const bindingsData = backend.get( bindingsGroup );
  47150. bindGroupLayouts.push( bindingsData.layout );
  47151. }
  47152. pipelineGPU.pipeline = device.createComputePipeline( {
  47153. compute: computeProgram,
  47154. layout: device.createPipelineLayout( {
  47155. bindGroupLayouts
  47156. } )
  47157. } );
  47158. }
  47159. /**
  47160. * Returns the blending state as a descriptor object required
  47161. * for the pipeline creation.
  47162. *
  47163. * @private
  47164. * @param {Material} material - The material.
  47165. * @return {Object} The blending state.
  47166. */
  47167. _getBlending( material ) {
  47168. let color, alpha;
  47169. const blending = material.blending;
  47170. const blendSrc = material.blendSrc;
  47171. const blendDst = material.blendDst;
  47172. const blendEquation = material.blendEquation;
  47173. if ( blending === CustomBlending ) {
  47174. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  47175. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  47176. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  47177. color = {
  47178. srcFactor: this._getBlendFactor( blendSrc ),
  47179. dstFactor: this._getBlendFactor( blendDst ),
  47180. operation: this._getBlendOperation( blendEquation )
  47181. };
  47182. alpha = {
  47183. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  47184. dstFactor: this._getBlendFactor( blendDstAlpha ),
  47185. operation: this._getBlendOperation( blendEquationAlpha )
  47186. };
  47187. } else {
  47188. const premultipliedAlpha = material.premultipliedAlpha;
  47189. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  47190. color = {
  47191. srcFactor: srcRGB,
  47192. dstFactor: dstRGB,
  47193. operation: GPUBlendOperation.Add
  47194. };
  47195. alpha = {
  47196. srcFactor: srcAlpha,
  47197. dstFactor: dstAlpha,
  47198. operation: GPUBlendOperation.Add
  47199. };
  47200. };
  47201. if ( premultipliedAlpha ) {
  47202. switch ( blending ) {
  47203. case NormalBlending:
  47204. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47205. break;
  47206. case AdditiveBlending:
  47207. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  47208. break;
  47209. case SubtractiveBlending:
  47210. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47211. break;
  47212. case MultiplyBlending:
  47213. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  47214. break;
  47215. }
  47216. } else {
  47217. switch ( blending ) {
  47218. case NormalBlending:
  47219. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47220. break;
  47221. case AdditiveBlending:
  47222. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  47223. break;
  47224. case SubtractiveBlending:
  47225. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47226. break;
  47227. case MultiplyBlending:
  47228. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  47229. break;
  47230. }
  47231. }
  47232. }
  47233. if ( color !== undefined && alpha !== undefined ) {
  47234. return { color, alpha };
  47235. } else {
  47236. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  47237. }
  47238. }
  47239. /**
  47240. * Returns the GPU blend factor which is required for the pipeline creation.
  47241. *
  47242. * @private
  47243. * @param {number} blend - The blend factor as a three.js constant.
  47244. * @return {string} The GPU blend factor.
  47245. */
  47246. _getBlendFactor( blend ) {
  47247. let blendFactor;
  47248. switch ( blend ) {
  47249. case ZeroFactor:
  47250. blendFactor = GPUBlendFactor.Zero;
  47251. break;
  47252. case OneFactor:
  47253. blendFactor = GPUBlendFactor.One;
  47254. break;
  47255. case SrcColorFactor:
  47256. blendFactor = GPUBlendFactor.Src;
  47257. break;
  47258. case OneMinusSrcColorFactor:
  47259. blendFactor = GPUBlendFactor.OneMinusSrc;
  47260. break;
  47261. case SrcAlphaFactor:
  47262. blendFactor = GPUBlendFactor.SrcAlpha;
  47263. break;
  47264. case OneMinusSrcAlphaFactor:
  47265. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  47266. break;
  47267. case DstColorFactor:
  47268. blendFactor = GPUBlendFactor.Dst;
  47269. break;
  47270. case OneMinusDstColorFactor:
  47271. blendFactor = GPUBlendFactor.OneMinusDstColor;
  47272. break;
  47273. case DstAlphaFactor:
  47274. blendFactor = GPUBlendFactor.DstAlpha;
  47275. break;
  47276. case OneMinusDstAlphaFactor:
  47277. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  47278. break;
  47279. case SrcAlphaSaturateFactor:
  47280. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  47281. break;
  47282. case BlendColorFactor:
  47283. blendFactor = GPUBlendFactor.Constant;
  47284. break;
  47285. case OneMinusBlendColorFactor:
  47286. blendFactor = GPUBlendFactor.OneMinusConstant;
  47287. break;
  47288. default:
  47289. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  47290. }
  47291. return blendFactor;
  47292. }
  47293. /**
  47294. * Returns the GPU stencil compare function which is required for the pipeline creation.
  47295. *
  47296. * @private
  47297. * @param {Material} material - The material.
  47298. * @return {string} The GPU stencil compare function.
  47299. */
  47300. _getStencilCompare( material ) {
  47301. let stencilCompare;
  47302. const stencilFunc = material.stencilFunc;
  47303. switch ( stencilFunc ) {
  47304. case NeverStencilFunc:
  47305. stencilCompare = GPUCompareFunction.Never;
  47306. break;
  47307. case AlwaysStencilFunc:
  47308. stencilCompare = GPUCompareFunction.Always;
  47309. break;
  47310. case LessStencilFunc:
  47311. stencilCompare = GPUCompareFunction.Less;
  47312. break;
  47313. case LessEqualStencilFunc:
  47314. stencilCompare = GPUCompareFunction.LessEqual;
  47315. break;
  47316. case EqualStencilFunc:
  47317. stencilCompare = GPUCompareFunction.Equal;
  47318. break;
  47319. case GreaterEqualStencilFunc:
  47320. stencilCompare = GPUCompareFunction.GreaterEqual;
  47321. break;
  47322. case GreaterStencilFunc:
  47323. stencilCompare = GPUCompareFunction.Greater;
  47324. break;
  47325. case NotEqualStencilFunc:
  47326. stencilCompare = GPUCompareFunction.NotEqual;
  47327. break;
  47328. default:
  47329. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  47330. }
  47331. return stencilCompare;
  47332. }
  47333. /**
  47334. * Returns the GPU stencil operation which is required for the pipeline creation.
  47335. *
  47336. * @private
  47337. * @param {number} op - A three.js constant defining the stencil operation.
  47338. * @return {string} The GPU stencil operation.
  47339. */
  47340. _getStencilOperation( op ) {
  47341. let stencilOperation;
  47342. switch ( op ) {
  47343. case KeepStencilOp:
  47344. stencilOperation = GPUStencilOperation.Keep;
  47345. break;
  47346. case ZeroStencilOp:
  47347. stencilOperation = GPUStencilOperation.Zero;
  47348. break;
  47349. case ReplaceStencilOp:
  47350. stencilOperation = GPUStencilOperation.Replace;
  47351. break;
  47352. case InvertStencilOp:
  47353. stencilOperation = GPUStencilOperation.Invert;
  47354. break;
  47355. case IncrementStencilOp:
  47356. stencilOperation = GPUStencilOperation.IncrementClamp;
  47357. break;
  47358. case DecrementStencilOp:
  47359. stencilOperation = GPUStencilOperation.DecrementClamp;
  47360. break;
  47361. case IncrementWrapStencilOp:
  47362. stencilOperation = GPUStencilOperation.IncrementWrap;
  47363. break;
  47364. case DecrementWrapStencilOp:
  47365. stencilOperation = GPUStencilOperation.DecrementWrap;
  47366. break;
  47367. default:
  47368. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  47369. }
  47370. return stencilOperation;
  47371. }
  47372. /**
  47373. * Returns the GPU blend operation which is required for the pipeline creation.
  47374. *
  47375. * @private
  47376. * @param {number} blendEquation - A three.js constant defining the blend equation.
  47377. * @return {string} The GPU blend operation.
  47378. */
  47379. _getBlendOperation( blendEquation ) {
  47380. let blendOperation;
  47381. switch ( blendEquation ) {
  47382. case AddEquation:
  47383. blendOperation = GPUBlendOperation.Add;
  47384. break;
  47385. case SubtractEquation:
  47386. blendOperation = GPUBlendOperation.Subtract;
  47387. break;
  47388. case ReverseSubtractEquation:
  47389. blendOperation = GPUBlendOperation.ReverseSubtract;
  47390. break;
  47391. case MinEquation:
  47392. blendOperation = GPUBlendOperation.Min;
  47393. break;
  47394. case MaxEquation:
  47395. blendOperation = GPUBlendOperation.Max;
  47396. break;
  47397. default:
  47398. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  47399. }
  47400. return blendOperation;
  47401. }
  47402. /**
  47403. * Returns the primitive state as a descriptor object required
  47404. * for the pipeline creation.
  47405. *
  47406. * @private
  47407. * @param {Object3D} object - The 3D object.
  47408. * @param {BufferGeometry} geometry - The geometry.
  47409. * @param {Material} material - The material.
  47410. * @return {Object} The primitive state.
  47411. */
  47412. _getPrimitiveState( object, geometry, material ) {
  47413. const descriptor = {};
  47414. const utils = this.backend.utils;
  47415. descriptor.topology = utils.getPrimitiveTopology( object, material );
  47416. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  47417. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  47418. }
  47419. switch ( material.side ) {
  47420. case FrontSide:
  47421. descriptor.frontFace = GPUFrontFace.CCW;
  47422. descriptor.cullMode = GPUCullMode.Back;
  47423. break;
  47424. case BackSide:
  47425. descriptor.frontFace = GPUFrontFace.CCW;
  47426. descriptor.cullMode = GPUCullMode.Front;
  47427. break;
  47428. case DoubleSide:
  47429. descriptor.frontFace = GPUFrontFace.CCW;
  47430. descriptor.cullMode = GPUCullMode.None;
  47431. break;
  47432. default:
  47433. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  47434. break;
  47435. }
  47436. return descriptor;
  47437. }
  47438. /**
  47439. * Returns the GPU color write mask which is required for the pipeline creation.
  47440. *
  47441. * @private
  47442. * @param {Material} material - The material.
  47443. * @return {string} The GPU color write mask.
  47444. */
  47445. _getColorWriteMask( material ) {
  47446. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  47447. }
  47448. /**
  47449. * Returns the GPU depth compare function which is required for the pipeline creation.
  47450. *
  47451. * @private
  47452. * @param {Material} material - The material.
  47453. * @return {string} The GPU depth compare function.
  47454. */
  47455. _getDepthCompare( material ) {
  47456. let depthCompare;
  47457. if ( material.depthTest === false ) {
  47458. depthCompare = GPUCompareFunction.Always;
  47459. } else {
  47460. const depthFunc = material.depthFunc;
  47461. switch ( depthFunc ) {
  47462. case NeverDepth:
  47463. depthCompare = GPUCompareFunction.Never;
  47464. break;
  47465. case AlwaysDepth:
  47466. depthCompare = GPUCompareFunction.Always;
  47467. break;
  47468. case LessDepth:
  47469. depthCompare = GPUCompareFunction.Less;
  47470. break;
  47471. case LessEqualDepth:
  47472. depthCompare = GPUCompareFunction.LessEqual;
  47473. break;
  47474. case EqualDepth:
  47475. depthCompare = GPUCompareFunction.Equal;
  47476. break;
  47477. case GreaterEqualDepth:
  47478. depthCompare = GPUCompareFunction.GreaterEqual;
  47479. break;
  47480. case GreaterDepth:
  47481. depthCompare = GPUCompareFunction.Greater;
  47482. break;
  47483. case NotEqualDepth:
  47484. depthCompare = GPUCompareFunction.NotEqual;
  47485. break;
  47486. default:
  47487. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  47488. }
  47489. }
  47490. return depthCompare;
  47491. }
  47492. }
  47493. /**
  47494. * Manages a pool of WebGPU timestamp queries for performance measurement.
  47495. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  47496. *
  47497. * @augments TimestampQueryPool
  47498. */
  47499. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  47500. /**
  47501. * Creates a new WebGPU timestamp query pool.
  47502. *
  47503. * @param {GPUDevice} device - The WebGPU device to create queries on.
  47504. * @param {string} type - The type identifier for this query pool.
  47505. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  47506. */
  47507. constructor( device, type, maxQueries = 2048 ) {
  47508. super( maxQueries );
  47509. this.device = device;
  47510. this.type = type;
  47511. this.querySet = this.device.createQuerySet( {
  47512. type: 'timestamp',
  47513. count: this.maxQueries,
  47514. label: `queryset_global_timestamp_${type}`
  47515. } );
  47516. const bufferSize = this.maxQueries * 8;
  47517. this.resolveBuffer = this.device.createBuffer( {
  47518. label: `buffer_timestamp_resolve_${type}`,
  47519. size: bufferSize,
  47520. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  47521. } );
  47522. this.resultBuffer = this.device.createBuffer( {
  47523. label: `buffer_timestamp_result_${type}`,
  47524. size: bufferSize,
  47525. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47526. } );
  47527. }
  47528. /**
  47529. * Allocates a pair of queries for a given render context.
  47530. *
  47531. * @param {Object} renderContext - The render context to allocate queries for.
  47532. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  47533. */
  47534. allocateQueriesForContext( renderContext ) {
  47535. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  47536. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  47537. 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() } ).` );
  47538. return null;
  47539. }
  47540. const baseOffset = this.currentQueryIndex;
  47541. this.currentQueryIndex += 2;
  47542. this.queryOffsets.set( renderContext.id, baseOffset );
  47543. return baseOffset;
  47544. }
  47545. /**
  47546. * Asynchronously resolves all pending queries and returns the total duration.
  47547. * If there's already a pending resolve operation, returns that promise instead.
  47548. *
  47549. * @async
  47550. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  47551. */
  47552. async resolveQueriesAsync() {
  47553. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  47554. return this.lastValue;
  47555. }
  47556. if ( this.pendingResolve ) {
  47557. return this.pendingResolve;
  47558. }
  47559. this.pendingResolve = this._resolveQueries();
  47560. try {
  47561. const result = await this.pendingResolve;
  47562. return result;
  47563. } finally {
  47564. this.pendingResolve = null;
  47565. }
  47566. }
  47567. /**
  47568. * Internal method to resolve queries and calculate total duration.
  47569. *
  47570. * @async
  47571. * @private
  47572. * @returns {Promise<number>} The total duration in milliseconds.
  47573. */
  47574. async _resolveQueries() {
  47575. if ( this.isDisposed ) {
  47576. return this.lastValue;
  47577. }
  47578. try {
  47579. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  47580. return this.lastValue;
  47581. }
  47582. const currentOffsets = new Map( this.queryOffsets );
  47583. const queryCount = this.currentQueryIndex;
  47584. const bytesUsed = queryCount * 8;
  47585. // Reset state before GPU work
  47586. this.currentQueryIndex = 0;
  47587. this.queryOffsets.clear();
  47588. const commandEncoder = this.device.createCommandEncoder();
  47589. commandEncoder.resolveQuerySet(
  47590. this.querySet,
  47591. 0,
  47592. queryCount,
  47593. this.resolveBuffer,
  47594. 0
  47595. );
  47596. commandEncoder.copyBufferToBuffer(
  47597. this.resolveBuffer,
  47598. 0,
  47599. this.resultBuffer,
  47600. 0,
  47601. bytesUsed
  47602. );
  47603. const commandBuffer = commandEncoder.finish();
  47604. this.device.queue.submit( [ commandBuffer ] );
  47605. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  47606. return this.lastValue;
  47607. }
  47608. // Create and track the mapping operation
  47609. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  47610. if ( this.isDisposed ) {
  47611. if ( this.resultBuffer.mapState === 'mapped' ) {
  47612. this.resultBuffer.unmap();
  47613. }
  47614. return this.lastValue;
  47615. }
  47616. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  47617. let totalDuration = 0;
  47618. for ( const [ , baseOffset ] of currentOffsets ) {
  47619. const startTime = times[ baseOffset ];
  47620. const endTime = times[ baseOffset + 1 ];
  47621. const duration = Number( endTime - startTime ) / 1e6;
  47622. totalDuration += duration;
  47623. }
  47624. this.resultBuffer.unmap();
  47625. this.lastValue = totalDuration;
  47626. return totalDuration;
  47627. } catch ( error ) {
  47628. console.error( 'Error resolving queries:', error );
  47629. if ( this.resultBuffer.mapState === 'mapped' ) {
  47630. this.resultBuffer.unmap();
  47631. }
  47632. return this.lastValue;
  47633. }
  47634. }
  47635. /**
  47636. * Dispose of the query pool.
  47637. *
  47638. * @async
  47639. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  47640. */
  47641. async dispose() {
  47642. if ( this.isDisposed ) {
  47643. return;
  47644. }
  47645. this.isDisposed = true;
  47646. // Wait for pending resolve operation
  47647. if ( this.pendingResolve ) {
  47648. try {
  47649. await this.pendingResolve;
  47650. } catch ( error ) {
  47651. console.error( 'Error waiting for pending resolve:', error );
  47652. }
  47653. }
  47654. // Ensure buffer is unmapped before destroying
  47655. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  47656. try {
  47657. this.resultBuffer.unmap();
  47658. } catch ( error ) {
  47659. console.error( 'Error unmapping buffer:', error );
  47660. }
  47661. }
  47662. // Destroy resources
  47663. if ( this.querySet ) {
  47664. this.querySet.destroy();
  47665. this.querySet = null;
  47666. }
  47667. if ( this.resolveBuffer ) {
  47668. this.resolveBuffer.destroy();
  47669. this.resolveBuffer = null;
  47670. }
  47671. if ( this.resultBuffer ) {
  47672. this.resultBuffer.destroy();
  47673. this.resultBuffer = null;
  47674. }
  47675. this.queryOffsets.clear();
  47676. this.pendingResolve = null;
  47677. }
  47678. }
  47679. /*// debugger tools
  47680. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  47681. //*/
  47682. /**
  47683. * A backend implementation targeting WebGPU.
  47684. *
  47685. * @private
  47686. * @augments Backend
  47687. */
  47688. class WebGPUBackend extends Backend {
  47689. /**
  47690. * Constructs a new WebGPU backend.
  47691. *
  47692. * @param {Object} parameters - The configuration parameter.
  47693. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47694. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47695. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47696. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47697. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47698. * @param {number} [parameters.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.
  47699. * @param {boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  47700. * @param {boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  47701. * @param {string} [parameters.powerPreference=undefined] - The power preference.
  47702. * @param {Object} [parameters.requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  47703. * @param {GPUDevice} [parameters.device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  47704. * @param {number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  47705. */
  47706. constructor( parameters = {} ) {
  47707. super( parameters );
  47708. /**
  47709. * This flag can be used for type testing.
  47710. *
  47711. * @type {boolean}
  47712. * @readonly
  47713. * @default true
  47714. */
  47715. this.isWebGPUBackend = true;
  47716. // some parameters require default values other than "undefined"
  47717. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  47718. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  47719. /**
  47720. * Whether to track timestamps with a Timestamp Query API or not.
  47721. *
  47722. * @type {boolean}
  47723. * @default false
  47724. */
  47725. this.trackTimestamp = ( parameters.trackTimestamp === true );
  47726. /**
  47727. * A reference to the device.
  47728. *
  47729. * @type {?GPUDevice}
  47730. * @default null
  47731. */
  47732. this.device = null;
  47733. /**
  47734. * A reference to the context.
  47735. *
  47736. * @type {?GPUCanvasContext}
  47737. * @default null
  47738. */
  47739. this.context = null;
  47740. /**
  47741. * A reference to the color attachment of the default framebuffer.
  47742. *
  47743. * @type {?GPUTexture}
  47744. * @default null
  47745. */
  47746. this.colorBuffer = null;
  47747. /**
  47748. * A reference to the default render pass descriptor.
  47749. *
  47750. * @type {?Object}
  47751. * @default null
  47752. */
  47753. this.defaultRenderPassdescriptor = null;
  47754. /**
  47755. * A reference to a backend module holding common utility functions.
  47756. *
  47757. * @type {WebGPUUtils}
  47758. */
  47759. this.utils = new WebGPUUtils( this );
  47760. /**
  47761. * A reference to a backend module holding shader attribute-related
  47762. * utility functions.
  47763. *
  47764. * @type {WebGPUAttributeUtils}
  47765. */
  47766. this.attributeUtils = new WebGPUAttributeUtils( this );
  47767. /**
  47768. * A reference to a backend module holding shader binding-related
  47769. * utility functions.
  47770. *
  47771. * @type {WebGPUBindingUtils}
  47772. */
  47773. this.bindingUtils = new WebGPUBindingUtils( this );
  47774. /**
  47775. * A reference to a backend module holding shader pipeline-related
  47776. * utility functions.
  47777. *
  47778. * @type {WebGPUPipelineUtils}
  47779. */
  47780. this.pipelineUtils = new WebGPUPipelineUtils( this );
  47781. /**
  47782. * A reference to a backend module holding shader texture-related
  47783. * utility functions.
  47784. *
  47785. * @type {WebGPUTextureUtils}
  47786. */
  47787. this.textureUtils = new WebGPUTextureUtils( this );
  47788. /**
  47789. * A map that manages the resolve buffers for occlusion queries.
  47790. *
  47791. * @type {Map<number,GPUBuffer>}
  47792. */
  47793. this.occludedResolveCache = new Map();
  47794. }
  47795. /**
  47796. * Initializes the backend so it is ready for usage.
  47797. *
  47798. * @async
  47799. * @param {Renderer} renderer - The renderer.
  47800. * @return {Promise} A Promise that resolves when the backend has been initialized.
  47801. */
  47802. async init( renderer ) {
  47803. await super.init( renderer );
  47804. //
  47805. const parameters = this.parameters;
  47806. // create the device if it is not passed with parameters
  47807. let device;
  47808. if ( parameters.device === undefined ) {
  47809. const adapterOptions = {
  47810. powerPreference: parameters.powerPreference
  47811. };
  47812. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  47813. if ( adapter === null ) {
  47814. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  47815. }
  47816. // feature support
  47817. const features = Object.values( GPUFeatureName );
  47818. const supportedFeatures = [];
  47819. for ( const name of features ) {
  47820. if ( adapter.features.has( name ) ) {
  47821. supportedFeatures.push( name );
  47822. }
  47823. }
  47824. const deviceDescriptor = {
  47825. requiredFeatures: supportedFeatures,
  47826. requiredLimits: parameters.requiredLimits
  47827. };
  47828. device = await adapter.requestDevice( deviceDescriptor );
  47829. } else {
  47830. device = parameters.device;
  47831. }
  47832. device.lost.then( ( info ) => {
  47833. const deviceLossInfo = {
  47834. api: 'WebGPU',
  47835. message: info.message || 'Unknown reason',
  47836. reason: info.reason || null,
  47837. originalEvent: info
  47838. };
  47839. renderer.onDeviceLost( deviceLossInfo );
  47840. } );
  47841. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  47842. this.device = device;
  47843. this.context = context;
  47844. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  47845. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  47846. this.context.configure( {
  47847. device: this.device,
  47848. format: this.utils.getPreferredCanvasFormat(),
  47849. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  47850. alphaMode: alphaMode
  47851. } );
  47852. this.updateSize();
  47853. }
  47854. /**
  47855. * The coordinate system of the backend.
  47856. *
  47857. * @type {number}
  47858. * @readonly
  47859. */
  47860. get coordinateSystem() {
  47861. return WebGPUCoordinateSystem;
  47862. }
  47863. /**
  47864. * This method performs a readback operation by moving buffer data from
  47865. * a storage buffer attribute from the GPU to the CPU.
  47866. *
  47867. * @async
  47868. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47869. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47870. */
  47871. async getArrayBufferAsync( attribute ) {
  47872. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47873. }
  47874. /**
  47875. * Returns the backend's rendering context.
  47876. *
  47877. * @return {GPUCanvasContext} The rendering context.
  47878. */
  47879. getContext() {
  47880. return this.context;
  47881. }
  47882. /**
  47883. * Returns the default render pass descriptor.
  47884. *
  47885. * In WebGPU, the default framebuffer must be configured
  47886. * like custom framebuffers so the backend needs a render
  47887. * pass descriptor even when rendering directly to screen.
  47888. *
  47889. * @private
  47890. * @return {Object} The render pass descriptor.
  47891. */
  47892. _getDefaultRenderPassDescriptor() {
  47893. let descriptor = this.defaultRenderPassdescriptor;
  47894. if ( descriptor === null ) {
  47895. const renderer = this.renderer;
  47896. descriptor = {
  47897. colorAttachments: [ {
  47898. view: null
  47899. } ],
  47900. };
  47901. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  47902. descriptor.depthStencilAttachment = {
  47903. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  47904. };
  47905. }
  47906. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47907. if ( this.renderer.samples > 0 ) {
  47908. colorAttachment.view = this.colorBuffer.createView();
  47909. } else {
  47910. colorAttachment.resolveTarget = undefined;
  47911. }
  47912. this.defaultRenderPassdescriptor = descriptor;
  47913. }
  47914. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47915. if ( this.renderer.samples > 0 ) {
  47916. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  47917. } else {
  47918. colorAttachment.view = this.context.getCurrentTexture().createView();
  47919. }
  47920. return descriptor;
  47921. }
  47922. /**
  47923. * Returns the render pass descriptor for the given render context.
  47924. *
  47925. * @private
  47926. * @param {RenderContext} renderContext - The render context.
  47927. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  47928. * @return {Object} The render pass descriptor.
  47929. */
  47930. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  47931. const renderTarget = renderContext.renderTarget;
  47932. const renderTargetData = this.get( renderTarget );
  47933. let descriptors = renderTargetData.descriptors;
  47934. if ( descriptors === undefined ||
  47935. renderTargetData.width !== renderTarget.width ||
  47936. renderTargetData.height !== renderTarget.height ||
  47937. renderTargetData.dimensions !== renderTarget.dimensions ||
  47938. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  47939. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  47940. renderTargetData.samples !== renderTarget.samples ||
  47941. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  47942. ) {
  47943. descriptors = {};
  47944. renderTargetData.descriptors = descriptors;
  47945. // dispose
  47946. const onDispose = () => {
  47947. renderTarget.removeEventListener( 'dispose', onDispose );
  47948. this.delete( renderTarget );
  47949. };
  47950. renderTarget.addEventListener( 'dispose', onDispose );
  47951. }
  47952. const cacheKey = renderContext.getCacheKey();
  47953. let descriptor = descriptors[ cacheKey ];
  47954. if ( descriptor === undefined ) {
  47955. const textures = renderContext.textures;
  47956. const colorAttachments = [];
  47957. let sliceIndex;
  47958. for ( let i = 0; i < textures.length; i ++ ) {
  47959. const textureData = this.get( textures[ i ] );
  47960. const viewDescriptor = {
  47961. label: `colorAttachment_${ i }`,
  47962. baseMipLevel: renderContext.activeMipmapLevel,
  47963. mipLevelCount: 1,
  47964. baseArrayLayer: renderContext.activeCubeFace,
  47965. arrayLayerCount: 1,
  47966. dimension: GPUTextureViewDimension.TwoD
  47967. };
  47968. if ( renderTarget.isRenderTarget3D ) {
  47969. sliceIndex = renderContext.activeCubeFace;
  47970. viewDescriptor.baseArrayLayer = 0;
  47971. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  47972. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47973. } else if ( renderTarget.isRenderTargetArray ) {
  47974. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  47975. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47976. }
  47977. const textureView = textureData.texture.createView( viewDescriptor );
  47978. let view, resolveTarget;
  47979. if ( textureData.msaaTexture !== undefined ) {
  47980. view = textureData.msaaTexture.createView();
  47981. resolveTarget = textureView;
  47982. } else {
  47983. view = textureView;
  47984. resolveTarget = undefined;
  47985. }
  47986. colorAttachments.push( {
  47987. view,
  47988. depthSlice: sliceIndex,
  47989. resolveTarget,
  47990. loadOp: GPULoadOp.Load,
  47991. storeOp: GPUStoreOp.Store,
  47992. ...colorAttachmentsConfig
  47993. } );
  47994. }
  47995. descriptor = {
  47996. colorAttachments,
  47997. };
  47998. if ( renderContext.depth ) {
  47999. const depthTextureData = this.get( renderContext.depthTexture );
  48000. const depthStencilAttachment = {
  48001. view: depthTextureData.texture.createView()
  48002. };
  48003. descriptor.depthStencilAttachment = depthStencilAttachment;
  48004. }
  48005. descriptors[ cacheKey ] = descriptor;
  48006. renderTargetData.width = renderTarget.width;
  48007. renderTargetData.height = renderTarget.height;
  48008. renderTargetData.samples = renderTarget.samples;
  48009. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  48010. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  48011. renderTargetData.dimensions = renderTarget.dimensions;
  48012. renderTargetData.depthSlice = sliceIndex;
  48013. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  48014. }
  48015. return descriptor;
  48016. }
  48017. /**
  48018. * This method is executed at the beginning of a render call and prepares
  48019. * the WebGPU state for upcoming render calls
  48020. *
  48021. * @param {RenderContext} renderContext - The render context.
  48022. */
  48023. beginRender( renderContext ) {
  48024. const renderContextData = this.get( renderContext );
  48025. const device = this.device;
  48026. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48027. let occlusionQuerySet;
  48028. if ( occlusionQueryCount > 0 ) {
  48029. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  48030. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  48031. // Get a reference to the array of objects with queries. The renderContextData property
  48032. // can be changed by another render pass before the buffer.mapAsyc() completes.
  48033. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  48034. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  48035. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48036. //
  48037. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  48038. renderContextData.occlusionQuerySet = occlusionQuerySet;
  48039. renderContextData.occlusionQueryIndex = 0;
  48040. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48041. renderContextData.lastOcclusionObject = null;
  48042. }
  48043. let descriptor;
  48044. if ( renderContext.textures === null ) {
  48045. descriptor = this._getDefaultRenderPassDescriptor();
  48046. } else {
  48047. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  48048. }
  48049. this.initTimestampQuery( renderContext, descriptor );
  48050. descriptor.occlusionQuerySet = occlusionQuerySet;
  48051. const depthStencilAttachment = descriptor.depthStencilAttachment;
  48052. if ( renderContext.textures !== null ) {
  48053. const colorAttachments = descriptor.colorAttachments;
  48054. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  48055. const colorAttachment = colorAttachments[ i ];
  48056. if ( renderContext.clearColor ) {
  48057. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  48058. colorAttachment.loadOp = GPULoadOp.Clear;
  48059. colorAttachment.storeOp = GPUStoreOp.Store;
  48060. } else {
  48061. colorAttachment.loadOp = GPULoadOp.Load;
  48062. colorAttachment.storeOp = GPUStoreOp.Store;
  48063. }
  48064. }
  48065. } else {
  48066. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48067. if ( renderContext.clearColor ) {
  48068. colorAttachment.clearValue = renderContext.clearColorValue;
  48069. colorAttachment.loadOp = GPULoadOp.Clear;
  48070. colorAttachment.storeOp = GPUStoreOp.Store;
  48071. } else {
  48072. colorAttachment.loadOp = GPULoadOp.Load;
  48073. colorAttachment.storeOp = GPUStoreOp.Store;
  48074. }
  48075. }
  48076. //
  48077. if ( renderContext.depth ) {
  48078. if ( renderContext.clearDepth ) {
  48079. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  48080. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48081. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48082. } else {
  48083. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48084. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48085. }
  48086. }
  48087. if ( renderContext.stencil ) {
  48088. if ( renderContext.clearStencil ) {
  48089. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  48090. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48091. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48092. } else {
  48093. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48094. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48095. }
  48096. }
  48097. //
  48098. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  48099. const currentPass = encoder.beginRenderPass( descriptor );
  48100. //
  48101. renderContextData.descriptor = descriptor;
  48102. renderContextData.encoder = encoder;
  48103. renderContextData.currentPass = currentPass;
  48104. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48105. renderContextData.renderBundles = [];
  48106. //
  48107. if ( renderContext.viewport ) {
  48108. this.updateViewport( renderContext );
  48109. }
  48110. if ( renderContext.scissor ) {
  48111. const { x, y, width, height } = renderContext.scissorValue;
  48112. currentPass.setScissorRect( x, y, width, height );
  48113. }
  48114. }
  48115. /**
  48116. * This method is executed at the end of a render call and finalizes work
  48117. * after draw calls.
  48118. *
  48119. * @param {RenderContext} renderContext - The render context.
  48120. */
  48121. finishRender( renderContext ) {
  48122. const renderContextData = this.get( renderContext );
  48123. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48124. if ( renderContextData.renderBundles.length > 0 ) {
  48125. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  48126. }
  48127. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48128. renderContextData.currentPass.endOcclusionQuery();
  48129. }
  48130. renderContextData.currentPass.end();
  48131. if ( occlusionQueryCount > 0 ) {
  48132. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  48133. //
  48134. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  48135. if ( queryResolveBuffer === undefined ) {
  48136. queryResolveBuffer = this.device.createBuffer(
  48137. {
  48138. size: bufferSize,
  48139. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  48140. }
  48141. );
  48142. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  48143. }
  48144. //
  48145. const readBuffer = this.device.createBuffer(
  48146. {
  48147. size: bufferSize,
  48148. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48149. }
  48150. );
  48151. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  48152. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  48153. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  48154. renderContextData.occlusionQueryBuffer = readBuffer;
  48155. //
  48156. this.resolveOccludedAsync( renderContext );
  48157. }
  48158. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  48159. //
  48160. if ( renderContext.textures !== null ) {
  48161. const textures = renderContext.textures;
  48162. for ( let i = 0; i < textures.length; i ++ ) {
  48163. const texture = textures[ i ];
  48164. if ( texture.generateMipmaps === true ) {
  48165. this.textureUtils.generateMipmaps( texture );
  48166. }
  48167. }
  48168. }
  48169. }
  48170. /**
  48171. * Returns `true` if the given 3D object is fully occluded by other
  48172. * 3D objects in the scene.
  48173. *
  48174. * @param {RenderContext} renderContext - The render context.
  48175. * @param {Object3D} object - The 3D object to test.
  48176. * @return {boolean} Whether the 3D object is fully occluded or not.
  48177. */
  48178. isOccluded( renderContext, object ) {
  48179. const renderContextData = this.get( renderContext );
  48180. return renderContextData.occluded && renderContextData.occluded.has( object );
  48181. }
  48182. /**
  48183. * This method processes the result of occlusion queries and writes it
  48184. * into render context data.
  48185. *
  48186. * @async
  48187. * @param {RenderContext} renderContext - The render context.
  48188. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  48189. */
  48190. async resolveOccludedAsync( renderContext ) {
  48191. const renderContextData = this.get( renderContext );
  48192. // handle occlusion query results
  48193. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  48194. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  48195. const occluded = new WeakSet();
  48196. renderContextData.currentOcclusionQueryObjects = null;
  48197. renderContextData.currentOcclusionQueryBuffer = null;
  48198. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  48199. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  48200. const results = new BigUint64Array( buffer );
  48201. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  48202. if ( results[ i ] === BigInt( 0 ) ) {
  48203. occluded.add( currentOcclusionQueryObjects[ i ] );
  48204. }
  48205. }
  48206. currentOcclusionQueryBuffer.destroy();
  48207. renderContextData.occluded = occluded;
  48208. }
  48209. }
  48210. /**
  48211. * Updates the viewport with the values from the given render context.
  48212. *
  48213. * @param {RenderContext} renderContext - The render context.
  48214. */
  48215. updateViewport( renderContext ) {
  48216. const { currentPass } = this.get( renderContext );
  48217. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  48218. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  48219. }
  48220. /**
  48221. * Returns the clear color and alpha into a single
  48222. * color object.
  48223. *
  48224. * @return {Color4} The clear color.
  48225. */
  48226. getClearColor() {
  48227. const clearColor = super.getClearColor();
  48228. // only premultiply alpha when alphaMode is "premultiplied"
  48229. if ( this.renderer.alpha === true ) {
  48230. clearColor.r *= clearColor.a;
  48231. clearColor.g *= clearColor.a;
  48232. clearColor.b *= clearColor.a;
  48233. }
  48234. return clearColor;
  48235. }
  48236. /**
  48237. * Performs a clear operation.
  48238. *
  48239. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48240. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48241. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48242. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  48243. */
  48244. clear( color, depth, stencil, renderTargetContext = null ) {
  48245. const device = this.device;
  48246. const renderer = this.renderer;
  48247. let colorAttachments = [];
  48248. let depthStencilAttachment;
  48249. let clearValue;
  48250. let supportsDepth;
  48251. let supportsStencil;
  48252. if ( color ) {
  48253. const clearColor = this.getClearColor();
  48254. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  48255. }
  48256. if ( renderTargetContext === null ) {
  48257. supportsDepth = renderer.depth;
  48258. supportsStencil = renderer.stencil;
  48259. const descriptor = this._getDefaultRenderPassDescriptor();
  48260. if ( color ) {
  48261. colorAttachments = descriptor.colorAttachments;
  48262. const colorAttachment = colorAttachments[ 0 ];
  48263. colorAttachment.clearValue = clearValue;
  48264. colorAttachment.loadOp = GPULoadOp.Clear;
  48265. colorAttachment.storeOp = GPUStoreOp.Store;
  48266. }
  48267. if ( supportsDepth || supportsStencil ) {
  48268. depthStencilAttachment = descriptor.depthStencilAttachment;
  48269. }
  48270. } else {
  48271. supportsDepth = renderTargetContext.depth;
  48272. supportsStencil = renderTargetContext.stencil;
  48273. if ( color ) {
  48274. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  48275. colorAttachments = descriptor.colorAttachments;
  48276. }
  48277. if ( supportsDepth || supportsStencil ) {
  48278. const depthTextureData = this.get( renderTargetContext.depthTexture );
  48279. depthStencilAttachment = {
  48280. view: depthTextureData.texture.createView()
  48281. };
  48282. }
  48283. }
  48284. //
  48285. if ( supportsDepth ) {
  48286. if ( depth ) {
  48287. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48288. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  48289. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48290. } else {
  48291. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48292. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48293. }
  48294. }
  48295. //
  48296. if ( supportsStencil ) {
  48297. if ( stencil ) {
  48298. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48299. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  48300. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48301. } else {
  48302. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48303. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48304. }
  48305. }
  48306. //
  48307. const encoder = device.createCommandEncoder( { label: 'clear' } );
  48308. const currentPass = encoder.beginRenderPass( {
  48309. colorAttachments,
  48310. depthStencilAttachment
  48311. } );
  48312. currentPass.end();
  48313. device.queue.submit( [ encoder.finish() ] );
  48314. }
  48315. // compute
  48316. /**
  48317. * This method is executed at the beginning of a compute call and
  48318. * prepares the state for upcoming compute tasks.
  48319. *
  48320. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48321. */
  48322. beginCompute( computeGroup ) {
  48323. const groupGPU = this.get( computeGroup );
  48324. const descriptor = {
  48325. label: 'computeGroup_' + computeGroup.id
  48326. };
  48327. this.initTimestampQuery( computeGroup, descriptor );
  48328. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  48329. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  48330. }
  48331. /**
  48332. * Executes a compute command for the given compute node.
  48333. *
  48334. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  48335. * @param {Node} computeNode - The compute node.
  48336. * @param {Array<BindGroup>} bindings - The bindings.
  48337. * @param {ComputePipeline} pipeline - The compute pipeline.
  48338. */
  48339. compute( computeGroup, computeNode, bindings, pipeline ) {
  48340. const { passEncoderGPU } = this.get( computeGroup );
  48341. // pipeline
  48342. const pipelineGPU = this.get( pipeline ).pipeline;
  48343. passEncoderGPU.setPipeline( pipelineGPU );
  48344. // bind groups
  48345. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  48346. const bindGroup = bindings[ i ];
  48347. const bindingsData = this.get( bindGroup );
  48348. passEncoderGPU.setBindGroup( i, bindingsData.group );
  48349. }
  48350. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  48351. const computeNodeData = this.get( computeNode );
  48352. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  48353. const { dispatchSize } = computeNodeData;
  48354. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  48355. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  48356. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  48357. } else {
  48358. dispatchSize.x = computeNode.dispatchCount;
  48359. }
  48360. passEncoderGPU.dispatchWorkgroups(
  48361. dispatchSize.x,
  48362. dispatchSize.y,
  48363. dispatchSize.z
  48364. );
  48365. }
  48366. /**
  48367. * This method is executed at the end of a compute call and
  48368. * finalizes work after compute tasks.
  48369. *
  48370. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48371. */
  48372. finishCompute( computeGroup ) {
  48373. const groupData = this.get( computeGroup );
  48374. groupData.passEncoderGPU.end();
  48375. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  48376. }
  48377. /**
  48378. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  48379. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  48380. *
  48381. * @async
  48382. * @return {Promise} A Promise that resolves when synchronization has been finished.
  48383. */
  48384. async waitForGPU() {
  48385. await this.device.queue.onSubmittedWorkDone();
  48386. }
  48387. // render object
  48388. /**
  48389. * Executes a draw command for the given render object.
  48390. *
  48391. * @param {RenderObject} renderObject - The render object to draw.
  48392. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  48393. */
  48394. draw( renderObject, info ) {
  48395. const { object, material, context, pipeline } = renderObject;
  48396. const bindings = renderObject.getBindings();
  48397. const renderContextData = this.get( context );
  48398. const pipelineGPU = this.get( pipeline ).pipeline;
  48399. const currentSets = renderContextData.currentSets;
  48400. const passEncoderGPU = renderContextData.currentPass;
  48401. const drawParams = renderObject.getDrawParameters();
  48402. if ( drawParams === null ) return;
  48403. // pipeline
  48404. if ( currentSets.pipeline !== pipelineGPU ) {
  48405. passEncoderGPU.setPipeline( pipelineGPU );
  48406. currentSets.pipeline = pipelineGPU;
  48407. }
  48408. // bind groups
  48409. const currentBindingGroups = currentSets.bindingGroups;
  48410. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  48411. const bindGroup = bindings[ i ];
  48412. const bindingsData = this.get( bindGroup );
  48413. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  48414. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  48415. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  48416. }
  48417. }
  48418. // attributes
  48419. const index = renderObject.getIndex();
  48420. const hasIndex = ( index !== null );
  48421. // index
  48422. if ( hasIndex === true ) {
  48423. if ( currentSets.index !== index ) {
  48424. const buffer = this.get( index ).buffer;
  48425. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  48426. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  48427. currentSets.index = index;
  48428. }
  48429. }
  48430. // vertex buffers
  48431. const vertexBuffers = renderObject.getVertexBuffers();
  48432. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  48433. const vertexBuffer = vertexBuffers[ i ];
  48434. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  48435. const buffer = this.get( vertexBuffer ).buffer;
  48436. passEncoderGPU.setVertexBuffer( i, buffer );
  48437. currentSets.attributes[ i ] = vertexBuffer;
  48438. }
  48439. }
  48440. // occlusion queries - handle multiple consecutive draw calls for an object
  48441. if ( renderContextData.occlusionQuerySet !== undefined ) {
  48442. const lastObject = renderContextData.lastOcclusionObject;
  48443. if ( lastObject !== object ) {
  48444. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  48445. passEncoderGPU.endOcclusionQuery();
  48446. renderContextData.occlusionQueryIndex ++;
  48447. }
  48448. if ( object.occlusionTest === true ) {
  48449. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  48450. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  48451. }
  48452. renderContextData.lastOcclusionObject = object;
  48453. }
  48454. }
  48455. // stencil
  48456. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  48457. passEncoderGPU.setStencilReference( material.stencilRef );
  48458. renderContextData.currentStencilRef = material.stencilRef;
  48459. }
  48460. // draw
  48461. const draw = () => {
  48462. if ( object.isBatchedMesh === true ) {
  48463. const starts = object._multiDrawStarts;
  48464. const counts = object._multiDrawCounts;
  48465. const drawCount = object._multiDrawCount;
  48466. const drawInstances = object._multiDrawInstances;
  48467. for ( let i = 0; i < drawCount; i ++ ) {
  48468. const count = drawInstances ? drawInstances[ i ] : 1;
  48469. const firstInstance = count > 1 ? 0 : i;
  48470. if ( hasIndex === true ) {
  48471. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  48472. } else {
  48473. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  48474. }
  48475. info.update( object, counts[ i ], count );
  48476. }
  48477. } else if ( hasIndex === true ) {
  48478. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  48479. const indirect = renderObject.getIndirect();
  48480. if ( indirect !== null ) {
  48481. const buffer = this.get( indirect ).buffer;
  48482. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  48483. } else {
  48484. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  48485. }
  48486. info.update( object, indexCount, instanceCount );
  48487. } else {
  48488. const { vertexCount, instanceCount, firstVertex } = drawParams;
  48489. const indirect = renderObject.getIndirect();
  48490. if ( indirect !== null ) {
  48491. const buffer = this.get( indirect ).buffer;
  48492. passEncoderGPU.drawIndirect( buffer, 0 );
  48493. } else {
  48494. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  48495. }
  48496. info.update( object, vertexCount, instanceCount );
  48497. }
  48498. };
  48499. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  48500. const cameraData = this.get( renderObject.camera );
  48501. const cameras = renderObject.camera.cameras;
  48502. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  48503. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  48504. const bindingsData = this.get( cameraIndex );
  48505. const indexesGPU = [];
  48506. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  48507. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48508. data[ 0 ] = i;
  48509. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  48510. indexesGPU.push( bindGroupIndex );
  48511. }
  48512. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  48513. }
  48514. const pixelRatio = this.renderer.getPixelRatio();
  48515. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48516. const subCamera = cameras[ i ];
  48517. if ( object.layers.test( subCamera.layers ) ) {
  48518. const vp = subCamera.viewport;
  48519. passEncoderGPU.setViewport(
  48520. Math.floor( vp.x * pixelRatio ),
  48521. Math.floor( vp.y * pixelRatio ),
  48522. Math.floor( vp.width * pixelRatio ),
  48523. Math.floor( vp.height * pixelRatio ),
  48524. context.viewportValue.minDepth,
  48525. context.viewportValue.maxDepth
  48526. );
  48527. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  48528. draw();
  48529. }
  48530. }
  48531. } else {
  48532. draw();
  48533. }
  48534. }
  48535. // cache key
  48536. /**
  48537. * Returns `true` if the render pipeline requires an update.
  48538. *
  48539. * @param {RenderObject} renderObject - The render object.
  48540. * @return {boolean} Whether the render pipeline requires an update or not.
  48541. */
  48542. needsRenderUpdate( renderObject ) {
  48543. const data = this.get( renderObject );
  48544. const { object, material } = renderObject;
  48545. const utils = this.utils;
  48546. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  48547. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  48548. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  48549. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  48550. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  48551. let needsUpdate = false;
  48552. if ( data.material !== material || data.materialVersion !== material.version ||
  48553. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  48554. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  48555. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  48556. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  48557. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  48558. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  48559. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  48560. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  48561. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  48562. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  48563. data.primitiveTopology !== primitiveTopology ||
  48564. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  48565. ) {
  48566. data.material = material; data.materialVersion = material.version;
  48567. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  48568. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  48569. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  48570. data.colorWrite = material.colorWrite;
  48571. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  48572. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  48573. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  48574. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  48575. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  48576. data.sampleCount = sampleCount;
  48577. data.colorSpace = colorSpace;
  48578. data.colorFormat = colorFormat;
  48579. data.depthStencilFormat = depthStencilFormat;
  48580. data.primitiveTopology = primitiveTopology;
  48581. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  48582. needsUpdate = true;
  48583. }
  48584. return needsUpdate;
  48585. }
  48586. /**
  48587. * Returns a cache key that is used to identify render pipelines.
  48588. *
  48589. * @param {RenderObject} renderObject - The render object.
  48590. * @return {string} The cache key.
  48591. */
  48592. getRenderCacheKey( renderObject ) {
  48593. const { object, material } = renderObject;
  48594. const utils = this.utils;
  48595. const renderContext = renderObject.context;
  48596. return [
  48597. material.transparent, material.blending, material.premultipliedAlpha,
  48598. material.blendSrc, material.blendDst, material.blendEquation,
  48599. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  48600. material.colorWrite,
  48601. material.depthWrite, material.depthTest, material.depthFunc,
  48602. material.stencilWrite, material.stencilFunc,
  48603. material.stencilFail, material.stencilZFail, material.stencilZPass,
  48604. material.stencilFuncMask, material.stencilWriteMask,
  48605. material.side,
  48606. utils.getSampleCountRenderContext( renderContext ),
  48607. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  48608. utils.getPrimitiveTopology( object, material ),
  48609. renderObject.getGeometryCacheKey(),
  48610. renderObject.clippingContextCacheKey
  48611. ].join();
  48612. }
  48613. // textures
  48614. /**
  48615. * Creates a GPU sampler for the given texture.
  48616. *
  48617. * @param {Texture} texture - The texture to create the sampler for.
  48618. */
  48619. createSampler( texture ) {
  48620. this.textureUtils.createSampler( texture );
  48621. }
  48622. /**
  48623. * Destroys the GPU sampler for the given texture.
  48624. *
  48625. * @param {Texture} texture - The texture to destroy the sampler for.
  48626. */
  48627. destroySampler( texture ) {
  48628. this.textureUtils.destroySampler( texture );
  48629. }
  48630. /**
  48631. * Creates a default texture for the given texture that can be used
  48632. * as a placeholder until the actual texture is ready for usage.
  48633. *
  48634. * @param {Texture} texture - The texture to create a default texture for.
  48635. */
  48636. createDefaultTexture( texture ) {
  48637. this.textureUtils.createDefaultTexture( texture );
  48638. }
  48639. /**
  48640. * Defines a texture on the GPU for the given texture object.
  48641. *
  48642. * @param {Texture} texture - The texture.
  48643. * @param {Object} [options={}] - Optional configuration parameter.
  48644. */
  48645. createTexture( texture, options ) {
  48646. this.textureUtils.createTexture( texture, options );
  48647. }
  48648. /**
  48649. * Uploads the updated texture data to the GPU.
  48650. *
  48651. * @param {Texture} texture - The texture.
  48652. * @param {Object} [options={}] - Optional configuration parameter.
  48653. */
  48654. updateTexture( texture, options ) {
  48655. this.textureUtils.updateTexture( texture, options );
  48656. }
  48657. /**
  48658. * Generates mipmaps for the given texture.
  48659. *
  48660. * @param {Texture} texture - The texture.
  48661. */
  48662. generateMipmaps( texture ) {
  48663. this.textureUtils.generateMipmaps( texture );
  48664. }
  48665. /**
  48666. * Destroys the GPU data for the given texture object.
  48667. *
  48668. * @param {Texture} texture - The texture.
  48669. */
  48670. destroyTexture( texture ) {
  48671. this.textureUtils.destroyTexture( texture );
  48672. }
  48673. /**
  48674. * Returns texture data as a typed array.
  48675. *
  48676. * @async
  48677. * @param {Texture} texture - The texture to copy.
  48678. * @param {number} x - The x coordinate of the copy origin.
  48679. * @param {number} y - The y coordinate of the copy origin.
  48680. * @param {number} width - The width of the copy.
  48681. * @param {number} height - The height of the copy.
  48682. * @param {number} faceIndex - The face index.
  48683. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48684. */
  48685. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48686. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  48687. }
  48688. /**
  48689. * Inits a time stamp query for the given render context.
  48690. *
  48691. * @param {RenderContext} renderContext - The render context.
  48692. * @param {Object} descriptor - The query descriptor.
  48693. */
  48694. initTimestampQuery( renderContext, descriptor ) {
  48695. if ( ! this.trackTimestamp ) return;
  48696. const type = renderContext.isComputeNode ? 'compute' : 'render';
  48697. if ( ! this.timestampQueryPool[ type ] ) {
  48698. // TODO: Variable maxQueries?
  48699. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  48700. }
  48701. const timestampQueryPool = this.timestampQueryPool[ type ];
  48702. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  48703. descriptor.timestampWrites = {
  48704. querySet: timestampQueryPool.querySet,
  48705. beginningOfPassWriteIndex: baseOffset,
  48706. endOfPassWriteIndex: baseOffset + 1,
  48707. };
  48708. }
  48709. // node builder
  48710. /**
  48711. * Returns a node builder for the given render object.
  48712. *
  48713. * @param {RenderObject} object - The render object.
  48714. * @param {Renderer} renderer - The renderer.
  48715. * @return {WGSLNodeBuilder} The node builder.
  48716. */
  48717. createNodeBuilder( object, renderer ) {
  48718. return new WGSLNodeBuilder( object, renderer );
  48719. }
  48720. // program
  48721. /**
  48722. * Creates a shader program from the given programmable stage.
  48723. *
  48724. * @param {ProgrammableStage} program - The programmable stage.
  48725. */
  48726. createProgram( program ) {
  48727. const programGPU = this.get( program );
  48728. programGPU.module = {
  48729. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  48730. entryPoint: 'main'
  48731. };
  48732. }
  48733. /**
  48734. * Destroys the shader program of the given programmable stage.
  48735. *
  48736. * @param {ProgrammableStage} program - The programmable stage.
  48737. */
  48738. destroyProgram( program ) {
  48739. this.delete( program );
  48740. }
  48741. // pipelines
  48742. /**
  48743. * Creates a render pipeline for the given render object.
  48744. *
  48745. * @param {RenderObject} renderObject - The render object.
  48746. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48747. */
  48748. createRenderPipeline( renderObject, promises ) {
  48749. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  48750. }
  48751. /**
  48752. * Creates a compute pipeline for the given compute node.
  48753. *
  48754. * @param {ComputePipeline} computePipeline - The compute pipeline.
  48755. * @param {Array<BindGroup>} bindings - The bindings.
  48756. */
  48757. createComputePipeline( computePipeline, bindings ) {
  48758. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  48759. }
  48760. /**
  48761. * Prepares the state for encoding render bundles.
  48762. *
  48763. * @param {RenderContext} renderContext - The render context.
  48764. */
  48765. beginBundle( renderContext ) {
  48766. const renderContextData = this.get( renderContext );
  48767. renderContextData._currentPass = renderContextData.currentPass;
  48768. renderContextData._currentSets = renderContextData.currentSets;
  48769. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48770. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  48771. }
  48772. /**
  48773. * After processing render bundles this method finalizes related work.
  48774. *
  48775. * @param {RenderContext} renderContext - The render context.
  48776. * @param {RenderBundle} bundle - The render bundle.
  48777. */
  48778. finishBundle( renderContext, bundle ) {
  48779. const renderContextData = this.get( renderContext );
  48780. const bundleEncoder = renderContextData.currentPass;
  48781. const bundleGPU = bundleEncoder.finish();
  48782. this.get( bundle ).bundleGPU = bundleGPU;
  48783. // restore render pass state
  48784. renderContextData.currentSets = renderContextData._currentSets;
  48785. renderContextData.currentPass = renderContextData._currentPass;
  48786. }
  48787. /**
  48788. * Adds a render bundle to the render context data.
  48789. *
  48790. * @param {RenderContext} renderContext - The render context.
  48791. * @param {RenderBundle} bundle - The render bundle to add.
  48792. */
  48793. addBundle( renderContext, bundle ) {
  48794. const renderContextData = this.get( renderContext );
  48795. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  48796. }
  48797. // bindings
  48798. /**
  48799. * Creates bindings from the given bind group definition.
  48800. *
  48801. * @param {BindGroup} bindGroup - The bind group.
  48802. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48803. * @param {number} cacheIndex - The cache index.
  48804. * @param {number} version - The version.
  48805. */
  48806. createBindings( bindGroup, bindings, cacheIndex, version ) {
  48807. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  48808. }
  48809. /**
  48810. * Updates the given bind group definition.
  48811. *
  48812. * @param {BindGroup} bindGroup - The bind group.
  48813. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48814. * @param {number} cacheIndex - The cache index.
  48815. * @param {number} version - The version.
  48816. */
  48817. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  48818. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  48819. }
  48820. /**
  48821. * Updates a buffer binding.
  48822. *
  48823. * @param {Buffer} binding - The buffer binding to update.
  48824. */
  48825. updateBinding( binding ) {
  48826. this.bindingUtils.updateBinding( binding );
  48827. }
  48828. // attributes
  48829. /**
  48830. * Creates the buffer of an indexed shader attribute.
  48831. *
  48832. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48833. */
  48834. createIndexAttribute( attribute ) {
  48835. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48836. }
  48837. /**
  48838. * Creates the GPU buffer of a shader attribute.
  48839. *
  48840. * @param {BufferAttribute} attribute - The buffer attribute.
  48841. */
  48842. createAttribute( attribute ) {
  48843. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48844. }
  48845. /**
  48846. * Creates the GPU buffer of a storage attribute.
  48847. *
  48848. * @param {BufferAttribute} attribute - The buffer attribute.
  48849. */
  48850. createStorageAttribute( attribute ) {
  48851. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48852. }
  48853. /**
  48854. * Creates the GPU buffer of an indirect storage attribute.
  48855. *
  48856. * @param {BufferAttribute} attribute - The buffer attribute.
  48857. */
  48858. createIndirectStorageAttribute( attribute ) {
  48859. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48860. }
  48861. /**
  48862. * Updates the GPU buffer of a shader attribute.
  48863. *
  48864. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48865. */
  48866. updateAttribute( attribute ) {
  48867. this.attributeUtils.updateAttribute( attribute );
  48868. }
  48869. /**
  48870. * Destroys the GPU buffer of a shader attribute.
  48871. *
  48872. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48873. */
  48874. destroyAttribute( attribute ) {
  48875. this.attributeUtils.destroyAttribute( attribute );
  48876. }
  48877. // canvas
  48878. /**
  48879. * Triggers an update of the default render pass descriptor.
  48880. */
  48881. updateSize() {
  48882. this.colorBuffer = this.textureUtils.getColorBuffer();
  48883. this.defaultRenderPassdescriptor = null;
  48884. }
  48885. // utils public
  48886. /**
  48887. * Returns the maximum anisotropy texture filtering value.
  48888. *
  48889. * @return {number} The maximum anisotropy texture filtering value.
  48890. */
  48891. getMaxAnisotropy() {
  48892. return 16;
  48893. }
  48894. /**
  48895. * Checks if the given feature is supported by the backend.
  48896. *
  48897. * @param {string} name - The feature's name.
  48898. * @return {boolean} Whether the feature is supported or not.
  48899. */
  48900. hasFeature( name ) {
  48901. return this.device.features.has( name );
  48902. }
  48903. /**
  48904. * Copies data of the given source texture to the given destination texture.
  48905. *
  48906. * @param {Texture} srcTexture - The source texture.
  48907. * @param {Texture} dstTexture - The destination texture.
  48908. * @param {?Vector4} [srcRegion=null] - The region of the source texture to copy.
  48909. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48910. * @param {number} [level=0] - The mip level to copy.
  48911. */
  48912. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  48913. let dstX = 0;
  48914. let dstY = 0;
  48915. let dstLayer = 0;
  48916. let srcX = 0;
  48917. let srcY = 0;
  48918. let srcLayer = 0;
  48919. let srcWidth = srcTexture.image.width;
  48920. let srcHeight = srcTexture.image.height;
  48921. if ( srcRegion !== null ) {
  48922. srcX = srcRegion.x;
  48923. srcY = srcRegion.y;
  48924. srcLayer = srcRegion.z || 0;
  48925. srcWidth = srcRegion.width;
  48926. srcHeight = srcRegion.height;
  48927. }
  48928. if ( dstPosition !== null ) {
  48929. dstX = dstPosition.x;
  48930. dstY = dstPosition.y;
  48931. dstLayer = dstPosition.z || 0;
  48932. }
  48933. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  48934. const sourceGPU = this.get( srcTexture ).texture;
  48935. const destinationGPU = this.get( dstTexture ).texture;
  48936. encoder.copyTextureToTexture(
  48937. {
  48938. texture: sourceGPU,
  48939. mipLevel: level,
  48940. origin: { x: srcX, y: srcY, z: srcLayer }
  48941. },
  48942. {
  48943. texture: destinationGPU,
  48944. mipLevel: level,
  48945. origin: { x: dstX, y: dstY, z: dstLayer }
  48946. },
  48947. [
  48948. srcWidth,
  48949. srcHeight,
  48950. 1
  48951. ]
  48952. );
  48953. this.device.queue.submit( [ encoder.finish() ] );
  48954. }
  48955. /**
  48956. * Copies the current bound framebuffer to the given texture.
  48957. *
  48958. * @param {Texture} texture - The destination texture.
  48959. * @param {RenderContext} renderContext - The render context.
  48960. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48961. */
  48962. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48963. const renderContextData = this.get( renderContext );
  48964. let sourceGPU = null;
  48965. if ( renderContext.renderTarget ) {
  48966. if ( texture.isDepthTexture ) {
  48967. sourceGPU = this.get( renderContext.depthTexture ).texture;
  48968. } else {
  48969. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  48970. }
  48971. } else {
  48972. if ( texture.isDepthTexture ) {
  48973. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  48974. } else {
  48975. sourceGPU = this.context.getCurrentTexture();
  48976. }
  48977. }
  48978. const destinationGPU = this.get( texture ).texture;
  48979. if ( sourceGPU.format !== destinationGPU.format ) {
  48980. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  48981. return;
  48982. }
  48983. let encoder;
  48984. if ( renderContextData.currentPass ) {
  48985. renderContextData.currentPass.end();
  48986. encoder = renderContextData.encoder;
  48987. } else {
  48988. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  48989. }
  48990. encoder.copyTextureToTexture(
  48991. {
  48992. texture: sourceGPU,
  48993. origin: [ rectangle.x, rectangle.y, 0 ],
  48994. },
  48995. {
  48996. texture: destinationGPU
  48997. },
  48998. [
  48999. rectangle.z,
  49000. rectangle.w
  49001. ]
  49002. );
  49003. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  49004. if ( renderContextData.currentPass ) {
  49005. const { descriptor } = renderContextData;
  49006. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  49007. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  49008. }
  49009. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  49010. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  49011. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  49012. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49013. if ( renderContext.viewport ) {
  49014. this.updateViewport( renderContext );
  49015. }
  49016. if ( renderContext.scissor ) {
  49017. const { x, y, width, height } = renderContext.scissorValue;
  49018. renderContextData.currentPass.setScissorRect( x, y, width, height );
  49019. }
  49020. } else {
  49021. this.device.queue.submit( [ encoder.finish() ] );
  49022. }
  49023. }
  49024. }
  49025. class IESSpotLight extends SpotLight {
  49026. constructor( color, intensity, distance, angle, penumbra, decay ) {
  49027. super( color, intensity, distance, angle, penumbra, decay );
  49028. this.iesMap = null;
  49029. }
  49030. copy( source, recursive ) {
  49031. super.copy( source, recursive );
  49032. this.iesMap = source.iesMap;
  49033. return this;
  49034. }
  49035. }
  49036. /**
  49037. * This version of a node library represents the standard version
  49038. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  49039. * techniques and materials to node-based implementations.
  49040. *
  49041. * @private
  49042. * @augments NodeLibrary
  49043. */
  49044. class StandardNodeLibrary extends NodeLibrary {
  49045. /**
  49046. * Constructs a new standard node library.
  49047. */
  49048. constructor() {
  49049. super();
  49050. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  49051. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  49052. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  49053. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  49054. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  49055. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  49056. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  49057. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  49058. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  49059. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  49060. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  49061. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  49062. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  49063. this.addLight( PointLightNode, PointLight );
  49064. this.addLight( DirectionalLightNode, DirectionalLight );
  49065. this.addLight( RectAreaLightNode, RectAreaLight );
  49066. this.addLight( SpotLightNode, SpotLight );
  49067. this.addLight( AmbientLightNode, AmbientLight );
  49068. this.addLight( HemisphereLightNode, HemisphereLight );
  49069. this.addLight( LightProbeNode, LightProbe );
  49070. this.addLight( IESSpotLightNode, IESSpotLight );
  49071. this.addToneMapping( linearToneMapping, LinearToneMapping );
  49072. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  49073. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  49074. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  49075. this.addToneMapping( agxToneMapping, AgXToneMapping );
  49076. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  49077. }
  49078. }
  49079. /*
  49080. const debugHandler = {
  49081. get: function ( target, name ) {
  49082. // Add |update
  49083. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  49084. return target[ name ];
  49085. }
  49086. };
  49087. */
  49088. /**
  49089. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  49090. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  49091. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  49092. *
  49093. * @augments Renderer
  49094. */
  49095. class WebGPURenderer extends Renderer {
  49096. /**
  49097. * Constructs a new WebGPU renderer.
  49098. *
  49099. * @param {Object} parameters - The configuration parameter.
  49100. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49101. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49102. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49103. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49104. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49105. * @param {number} [parameters.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.
  49106. * @param {boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49107. * @param {number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49108. * @param {number} [parameters.colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  49109. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  49110. */
  49111. constructor( parameters = {} ) {
  49112. let BackendClass;
  49113. if ( parameters.forceWebGL ) {
  49114. BackendClass = WebGLBackend;
  49115. } else {
  49116. BackendClass = WebGPUBackend;
  49117. parameters.getFallback = () => {
  49118. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  49119. return new WebGLBackend( parameters );
  49120. };
  49121. }
  49122. const backend = new BackendClass( parameters );
  49123. //super( new Proxy( backend, debugHandler ) );
  49124. super( backend, parameters );
  49125. /**
  49126. * The generic default value is overwritten with the
  49127. * standard node library for type mapping.
  49128. *
  49129. * @type {StandardNodeLibrary}
  49130. */
  49131. this.library = new StandardNodeLibrary();
  49132. /**
  49133. * This flag can be used for type testing.
  49134. *
  49135. * @type {boolean}
  49136. * @readonly
  49137. * @default true
  49138. */
  49139. this.isWebGPURenderer = true;
  49140. }
  49141. }
  49142. /**
  49143. * A specialized group which enables applications access to the
  49144. * Render Bundle API of WebGPU. The group with all its descendant nodes
  49145. * are considered as one render bundle and processed as such by
  49146. * the renderer.
  49147. *
  49148. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  49149. * With a WebGL backend, the group can technically be rendered but without
  49150. * any performance improvements.
  49151. *
  49152. * @augments Group
  49153. */
  49154. class BundleGroup extends Group {
  49155. /**
  49156. * Constructs a new bundle group.
  49157. */
  49158. constructor() {
  49159. super();
  49160. /**
  49161. * This flag can be used for type testing.
  49162. *
  49163. * @type {boolean}
  49164. * @readonly
  49165. * @default true
  49166. */
  49167. this.isBundleGroup = true;
  49168. /**
  49169. * This property is only relevant for detecting types
  49170. * during serialization/deserialization. It should always
  49171. * match the class name.
  49172. *
  49173. * @type {string}
  49174. * @readonly
  49175. * @default 'BundleGroup'
  49176. */
  49177. this.type = 'BundleGroup';
  49178. /**
  49179. * Whether the bundle is static or not. When set to `true`, the structure
  49180. * is assumed to be static and does not change. E.g. no new objects are
  49181. * added to the group
  49182. *
  49183. * If a change is required, an update can still be forced by setting the
  49184. * `needsUpdate` flag to `true`.
  49185. *
  49186. * @type {boolean}
  49187. * @default true
  49188. */
  49189. this.static = true;
  49190. /**
  49191. * The bundle group's version.
  49192. *
  49193. * @type {number}
  49194. * @readonly
  49195. * @default 0
  49196. */
  49197. this.version = 0;
  49198. }
  49199. /**
  49200. * Set this property to `true` when the bundle group has changed.
  49201. *
  49202. * @type {boolean}
  49203. * @default false
  49204. * @param {boolean} value
  49205. */
  49206. set needsUpdate( value ) {
  49207. if ( value === true ) this.version ++;
  49208. }
  49209. }
  49210. /**
  49211. * This module is responsible to manage the post processing setups in apps.
  49212. * You usually create a single instance of this class and use it to define
  49213. * the output of your post processing effect chain.
  49214. * ```js
  49215. * const postProcessing = new PostProcessing( renderer );
  49216. *
  49217. * const scenePass = pass( scene, camera );
  49218. *
  49219. * postProcessing.outputNode = scenePass;
  49220. * ```
  49221. */
  49222. class PostProcessing {
  49223. /**
  49224. * Constructs a new post processing management module.
  49225. *
  49226. * @param {Renderer} renderer - A reference to the renderer.
  49227. * @param {Node<vec4>} outputNode - An optional output node.
  49228. */
  49229. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  49230. /**
  49231. * A reference to the renderer.
  49232. *
  49233. * @type {Renderer}
  49234. */
  49235. this.renderer = renderer;
  49236. /**
  49237. * A node which defines the final output of the post
  49238. * processing. This is usually the last node in a chain
  49239. * of effect nodes.
  49240. *
  49241. * @type {Node<vec4>}
  49242. */
  49243. this.outputNode = outputNode;
  49244. /**
  49245. * Whether the default output tone mapping and color
  49246. * space transformation should be enabled or not.
  49247. *
  49248. * It is enabled by default by it must be disabled when
  49249. * effects must be executed after tone mapping and color
  49250. * space conversion. A typical example is FXAA which
  49251. * requires sRGB input.
  49252. *
  49253. * When set to `false`, the app must control the output
  49254. * transformation with `RenderOutputNode`.
  49255. *
  49256. * ```js
  49257. * const outputPass = renderOutput( scenePass );
  49258. * ```
  49259. *
  49260. * @type {boolean}
  49261. */
  49262. this.outputColorTransform = true;
  49263. /**
  49264. * Must be set to `true` when the output node changes.
  49265. *
  49266. * @type {Node<vec4>}
  49267. */
  49268. this.needsUpdate = true;
  49269. const material = new NodeMaterial();
  49270. material.name = 'PostProcessing';
  49271. /**
  49272. * The full screen quad that is used to render
  49273. * the effects.
  49274. *
  49275. * @private
  49276. * @type {QuadMesh}
  49277. */
  49278. this._quadMesh = new QuadMesh( material );
  49279. }
  49280. /**
  49281. * When `PostProcessing` is used to apply post processing effects,
  49282. * the application must use this version of `render()` inside
  49283. * its animation loop (not the one from the renderer).
  49284. */
  49285. render() {
  49286. this._update();
  49287. const renderer = this.renderer;
  49288. const toneMapping = renderer.toneMapping;
  49289. const outputColorSpace = renderer.outputColorSpace;
  49290. renderer.toneMapping = NoToneMapping;
  49291. renderer.outputColorSpace = LinearSRGBColorSpace;
  49292. //
  49293. const currentXR = renderer.xr.enabled;
  49294. renderer.xr.enabled = false;
  49295. this._quadMesh.render( renderer );
  49296. renderer.xr.enabled = currentXR;
  49297. //
  49298. renderer.toneMapping = toneMapping;
  49299. renderer.outputColorSpace = outputColorSpace;
  49300. }
  49301. /**
  49302. * Frees internal resources.
  49303. */
  49304. dispose() {
  49305. this._quadMesh.material.dispose();
  49306. }
  49307. /**
  49308. * Updates the state of the module.
  49309. *
  49310. * @private
  49311. */
  49312. _update() {
  49313. if ( this.needsUpdate === true ) {
  49314. const renderer = this.renderer;
  49315. const toneMapping = renderer.toneMapping;
  49316. const outputColorSpace = renderer.outputColorSpace;
  49317. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  49318. this._quadMesh.material.needsUpdate = true;
  49319. this.needsUpdate = false;
  49320. }
  49321. }
  49322. /**
  49323. * When `PostProcessing` is used to apply post processing effects,
  49324. * the application must use this version of `renderAsync()` inside
  49325. * its animation loop (not the one from the renderer).
  49326. *
  49327. * @async
  49328. * @return {Promise} A Promise that resolves when the render has been finished.
  49329. */
  49330. async renderAsync() {
  49331. this._update();
  49332. const renderer = this.renderer;
  49333. const toneMapping = renderer.toneMapping;
  49334. const outputColorSpace = renderer.outputColorSpace;
  49335. renderer.toneMapping = NoToneMapping;
  49336. renderer.outputColorSpace = LinearSRGBColorSpace;
  49337. //
  49338. const currentXR = renderer.xr.enabled;
  49339. renderer.xr.enabled = false;
  49340. await this._quadMesh.renderAsync( renderer );
  49341. renderer.xr.enabled = currentXR;
  49342. //
  49343. renderer.toneMapping = toneMapping;
  49344. renderer.outputColorSpace = outputColorSpace;
  49345. }
  49346. }
  49347. /**
  49348. * This special type of texture is intended for compute shaders.
  49349. * It can be used to compute the data of a texture with a compute shader.
  49350. *
  49351. * Note: This type of texture can only be used with `WebGPURenderer`
  49352. * and a WebGPU backend.
  49353. *
  49354. * @augments Texture
  49355. */
  49356. class StorageTexture extends Texture {
  49357. /**
  49358. * Constructs a new storage texture.
  49359. *
  49360. * @param {number} [width=1] - The storage texture's width.
  49361. * @param {number} [height=1] - The storage texture's height.
  49362. */
  49363. constructor( width = 1, height = 1 ) {
  49364. super();
  49365. /**
  49366. * The image object which just represents the texture's dimension.
  49367. *
  49368. * @type {{width: number, height: number}}
  49369. */
  49370. this.image = { width, height };
  49371. /**
  49372. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  49373. *
  49374. * @type {number}
  49375. */
  49376. this.magFilter = LinearFilter;
  49377. /**
  49378. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  49379. *
  49380. * @type {number}
  49381. */
  49382. this.minFilter = LinearFilter;
  49383. /**
  49384. * This flag can be used for type testing.
  49385. *
  49386. * @type {boolean}
  49387. * @readonly
  49388. * @default true
  49389. */
  49390. this.isStorageTexture = true;
  49391. }
  49392. }
  49393. /**
  49394. * This special type of buffer attribute is intended for compute shaders.
  49395. * It can be used to encode draw parameters for indirect draw calls.
  49396. *
  49397. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  49398. * and a WebGPU backend.
  49399. *
  49400. * @augments StorageBufferAttribute
  49401. */
  49402. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  49403. /**
  49404. * Constructs a new storage buffer attribute.
  49405. *
  49406. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  49407. * The subsequent parameter is then obsolete.
  49408. * @param {number} itemSize - The item size.
  49409. */
  49410. constructor( count, itemSize ) {
  49411. super( count, itemSize, Uint32Array );
  49412. /**
  49413. * This flag can be used for type testing.
  49414. *
  49415. * @type {boolean}
  49416. * @readonly
  49417. * @default true
  49418. */
  49419. this.isIndirectStorageBufferAttribute = true;
  49420. }
  49421. }
  49422. /**
  49423. * A loader for loading node objects in the three.js JSON Object/Scene format.
  49424. *
  49425. * @augments Loader
  49426. */
  49427. class NodeLoader extends Loader {
  49428. /**
  49429. * Constructs a new node loader.
  49430. *
  49431. * @param {?LoadingManager} manager - A reference to a loading manager.
  49432. */
  49433. constructor( manager ) {
  49434. super( manager );
  49435. /**
  49436. * Represents a dictionary of textures.
  49437. *
  49438. * @type {Object<string,Texture>}
  49439. */
  49440. this.textures = {};
  49441. /**
  49442. * Represents a dictionary of node types.
  49443. *
  49444. * @type {Object<string,Node.constructor>}
  49445. */
  49446. this.nodes = {};
  49447. }
  49448. /**
  49449. * Loads the node definitions from the given URL.
  49450. *
  49451. * @param {string} url - The path/URL of the file to be loaded.
  49452. * @param {Function} onLoad - Will be called when load completes.
  49453. * @param {Function} onProgress - Will be called while load progresses.
  49454. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  49455. */
  49456. load( url, onLoad, onProgress, onError ) {
  49457. const loader = new FileLoader( this.manager );
  49458. loader.setPath( this.path );
  49459. loader.setRequestHeader( this.requestHeader );
  49460. loader.setWithCredentials( this.withCredentials );
  49461. loader.load( url, ( text ) => {
  49462. try {
  49463. onLoad( this.parse( JSON.parse( text ) ) );
  49464. } catch ( e ) {
  49465. if ( onError ) {
  49466. onError( e );
  49467. } else {
  49468. console.error( e );
  49469. }
  49470. this.manager.itemError( url );
  49471. }
  49472. }, onProgress, onError );
  49473. }
  49474. /**
  49475. * Parse the node dependencies for the loaded node.
  49476. *
  49477. * @param {Object} json - The JSON definition
  49478. * @return {Object<string,Node>} A dictionary with node dependencies.
  49479. */
  49480. parseNodes( json ) {
  49481. const nodes = {};
  49482. if ( json !== undefined ) {
  49483. for ( const nodeJSON of json ) {
  49484. const { uuid, type } = nodeJSON;
  49485. nodes[ uuid ] = this.createNodeFromType( type );
  49486. nodes[ uuid ].uuid = uuid;
  49487. }
  49488. const meta = { nodes, textures: this.textures };
  49489. for ( const nodeJSON of json ) {
  49490. nodeJSON.meta = meta;
  49491. const node = nodes[ nodeJSON.uuid ];
  49492. node.deserialize( nodeJSON );
  49493. delete nodeJSON.meta;
  49494. }
  49495. }
  49496. return nodes;
  49497. }
  49498. /**
  49499. * Parses the node from the given JSON.
  49500. *
  49501. * @param {Object} json - The JSON definition
  49502. * @return {Node} The parsed node.
  49503. */
  49504. parse( json ) {
  49505. const node = this.createNodeFromType( json.type );
  49506. node.uuid = json.uuid;
  49507. const nodes = this.parseNodes( json.nodes );
  49508. const meta = { nodes, textures: this.textures };
  49509. json.meta = meta;
  49510. node.deserialize( json );
  49511. delete json.meta;
  49512. return node;
  49513. }
  49514. /**
  49515. * Defines the dictionary of textures.
  49516. *
  49517. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  49518. * @return {NodeLoader} A reference to this loader.
  49519. */
  49520. setTextures( value ) {
  49521. this.textures = value;
  49522. return this;
  49523. }
  49524. /**
  49525. * Defines the dictionary of node types.
  49526. *
  49527. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  49528. * @return {NodeLoader} A reference to this loader.
  49529. */
  49530. setNodes( value ) {
  49531. this.nodes = value;
  49532. return this;
  49533. }
  49534. /**
  49535. * Creates a node object from the given type.
  49536. *
  49537. * @param {string} type - The node type.
  49538. * @return {Node} The created node instance.
  49539. */
  49540. createNodeFromType( type ) {
  49541. if ( this.nodes[ type ] === undefined ) {
  49542. console.error( 'THREE.NodeLoader: Node type not found:', type );
  49543. return float();
  49544. }
  49545. return nodeObject( new this.nodes[ type ]() );
  49546. }
  49547. }
  49548. /**
  49549. * A special type of material loader for loading node materials.
  49550. *
  49551. * @augments MaterialLoader
  49552. */
  49553. class NodeMaterialLoader extends MaterialLoader {
  49554. /**
  49555. * Constructs a new node material loader.
  49556. *
  49557. * @param {?LoadingManager} manager - A reference to a loading manager.
  49558. */
  49559. constructor( manager ) {
  49560. super( manager );
  49561. /**
  49562. * Represents a dictionary of node types.
  49563. *
  49564. * @type {Object<string,Node.constructor>}
  49565. */
  49566. this.nodes = {};
  49567. /**
  49568. * Represents a dictionary of node material types.
  49569. *
  49570. * @type {Object<string,NodeMaterial.constructor>}
  49571. */
  49572. this.nodeMaterials = {};
  49573. }
  49574. /**
  49575. * Parses the node material from the given JSON.
  49576. *
  49577. * @param {Object} json - The JSON definition
  49578. * @return {NodeMaterial}. The parsed material.
  49579. */
  49580. parse( json ) {
  49581. const material = super.parse( json );
  49582. const nodes = this.nodes;
  49583. const inputNodes = json.inputNodes;
  49584. for ( const property in inputNodes ) {
  49585. const uuid = inputNodes[ property ];
  49586. material[ property ] = nodes[ uuid ];
  49587. }
  49588. return material;
  49589. }
  49590. /**
  49591. * Defines the dictionary of node types.
  49592. *
  49593. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  49594. * @return {NodeLoader} A reference to this loader.
  49595. */
  49596. setNodes( value ) {
  49597. this.nodes = value;
  49598. return this;
  49599. }
  49600. /**
  49601. * Defines the dictionary of node material types.
  49602. *
  49603. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  49604. * @return {NodeLoader} A reference to this loader.
  49605. */
  49606. setNodeMaterials( value ) {
  49607. this.nodeMaterials = value;
  49608. return this;
  49609. }
  49610. /**
  49611. * Creates a node material from the given type.
  49612. *
  49613. * @param {string} type - The node material type.
  49614. * @return {Node} The created node material instance.
  49615. */
  49616. createMaterialFromType( type ) {
  49617. const materialClass = this.nodeMaterials[ type ];
  49618. if ( materialClass !== undefined ) {
  49619. return new materialClass();
  49620. }
  49621. return super.createMaterialFromType( type );
  49622. }
  49623. }
  49624. /**
  49625. * A special type of object loader for loading 3D objects using
  49626. * node materials.
  49627. *
  49628. * @augments ObjectLoader
  49629. */
  49630. class NodeObjectLoader extends ObjectLoader {
  49631. /**
  49632. * Constructs a new node object loader.
  49633. *
  49634. * @param {?LoadingManager} manager - A reference to a loading manager.
  49635. */
  49636. constructor( manager ) {
  49637. super( manager );
  49638. /**
  49639. * Represents a dictionary of node types.
  49640. *
  49641. * @type {Object<string,Node.constructor>}
  49642. */
  49643. this.nodes = {};
  49644. /**
  49645. * Represents a dictionary of node material types.
  49646. *
  49647. * @type {Object<string,NodeMaterial.constructor>}
  49648. */
  49649. this.nodeMaterials = {};
  49650. /**
  49651. * A reference to hold the `nodes` JSON property.
  49652. *
  49653. * @private
  49654. * @type {?Object}
  49655. */
  49656. this._nodesJSON = null;
  49657. }
  49658. /**
  49659. * Defines the dictionary of node types.
  49660. *
  49661. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  49662. * @return {NodeLoader} A reference to this loader.
  49663. */
  49664. setNodes( value ) {
  49665. this.nodes = value;
  49666. return this;
  49667. }
  49668. /**
  49669. * Defines the dictionary of node material types.
  49670. *
  49671. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  49672. * @return {NodeLoader} A reference to this loader.
  49673. */
  49674. setNodeMaterials( value ) {
  49675. this.nodeMaterials = value;
  49676. return this;
  49677. }
  49678. /**
  49679. * Parses the node objects from the given JSON.
  49680. *
  49681. * @param {Object} json - The JSON definition
  49682. * @param {Function} onLoad - The onLoad callback function.
  49683. * @return {Object3D}. The parsed 3D object.
  49684. */
  49685. parse( json, onLoad ) {
  49686. this._nodesJSON = json.nodes;
  49687. const data = super.parse( json, onLoad );
  49688. this._nodesJSON = null; // dispose
  49689. return data;
  49690. }
  49691. /**
  49692. * Parses the node objects from the given JSON and textures.
  49693. *
  49694. * @param {Object} json - The JSON definition
  49695. * @param {Object<string,Texture>} textures - The texture library.
  49696. * @return {Object<string,Node>}. The parsed nodes.
  49697. */
  49698. parseNodes( json, textures ) {
  49699. if ( json !== undefined ) {
  49700. const loader = new NodeLoader();
  49701. loader.setNodes( this.nodes );
  49702. loader.setTextures( textures );
  49703. return loader.parseNodes( json );
  49704. }
  49705. return {};
  49706. }
  49707. /**
  49708. * Parses the node objects from the given JSON and textures.
  49709. *
  49710. * @param {Object} json - The JSON definition
  49711. * @param {Object<string,Texture>} textures - The texture library.
  49712. * @return {Object<string,NodeMaterial>}. The parsed materials.
  49713. */
  49714. parseMaterials( json, textures ) {
  49715. const materials = {};
  49716. if ( json !== undefined ) {
  49717. const nodes = this.parseNodes( this._nodesJSON, textures );
  49718. const loader = new NodeMaterialLoader();
  49719. loader.setTextures( textures );
  49720. loader.setNodes( nodes );
  49721. loader.setNodeMaterials( this.nodeMaterials );
  49722. for ( let i = 0, l = json.length; i < l; i ++ ) {
  49723. const data = json[ i ];
  49724. materials[ data.uuid ] = loader.parse( data );
  49725. }
  49726. }
  49727. return materials;
  49728. }
  49729. }
  49730. /**
  49731. * In earlier three.js versions, clipping was defined globally
  49732. * on the renderer or on material level. This special version of
  49733. * `THREE.Group` allows to encode the clipping state into the scene
  49734. * graph. Meaning if you create an instance of this group, all
  49735. * descendant 3D objects will be affected by the respective clipping
  49736. * planes.
  49737. *
  49738. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  49739. *
  49740. * @augments Group
  49741. */
  49742. class ClippingGroup extends Group {
  49743. /**
  49744. * Constructs a new clipping group.
  49745. */
  49746. constructor() {
  49747. super();
  49748. /**
  49749. * This flag can be used for type testing.
  49750. *
  49751. * @type {boolean}
  49752. * @readonly
  49753. * @default true
  49754. */
  49755. this.isClippingGroup = true;
  49756. /**
  49757. * An array with clipping planes.
  49758. *
  49759. * @type {Array<Plane>}
  49760. */
  49761. this.clippingPlanes = [];
  49762. /**
  49763. * Whether clipping should be enabled or not.
  49764. *
  49765. * @type {boolean}
  49766. * @default true
  49767. */
  49768. this.enabled = true;
  49769. /**
  49770. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  49771. *
  49772. * @type {boolean}
  49773. * @default false
  49774. */
  49775. this.clipIntersection = false;
  49776. /**
  49777. * Whether shadows should be clipped or not.
  49778. *
  49779. * @type {boolean}
  49780. * @default false
  49781. */
  49782. this.clipShadows = false;
  49783. }
  49784. }
  49785. 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, DataArrayTexture, DataTexture, 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, 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, LuminanceAlphaFormat, LuminanceFormat, 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, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, 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, 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号