three.webgpu.nodes.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807
  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, DynamicDrawUsage, InterleavedBufferAttribute, 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, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, WebXRController, RAD2DEG, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, warnOnce, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, 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, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, 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. attributes: this.getAttributesData( geometry.attributes ),
  133. indexVersion: geometry.index ? geometry.index.version : null,
  134. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  135. },
  136. worldMatrix: object.matrixWorld.clone()
  137. };
  138. if ( object.center ) {
  139. data.center = object.center.clone();
  140. }
  141. if ( object.morphTargetInfluences ) {
  142. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  143. }
  144. if ( renderObject.bundle !== null ) {
  145. data.version = renderObject.bundle.version;
  146. }
  147. if ( data.material.transmission > 0 ) {
  148. const { width, height } = renderObject.context;
  149. data.bufferWidth = width;
  150. data.bufferHeight = height;
  151. }
  152. this.renderObjects.set( renderObject, data );
  153. }
  154. return data;
  155. }
  156. /**
  157. * Returns an attribute data structure holding the attributes versions for
  158. * monitoring.
  159. *
  160. * @param {Object} attributes - The geometry attributes.
  161. * @return {Object} An object for monitoring the versions of attributes.
  162. */
  163. getAttributesData( attributes ) {
  164. const attributesData = {};
  165. for ( const name in attributes ) {
  166. const attribute = attributes[ name ];
  167. attributesData[ name ] = {
  168. version: attribute.version
  169. };
  170. }
  171. return attributesData;
  172. }
  173. /**
  174. * Returns `true` if the node builder's material uses
  175. * node properties.
  176. *
  177. * @param {NodeBuilder} builder - The current node builder.
  178. * @return {Boolean} Whether the node builder's material uses node properties or not.
  179. */
  180. containsNode( builder ) {
  181. const material = builder.material;
  182. for ( const property in material ) {
  183. if ( material[ property ] && material[ property ].isNode )
  184. return true;
  185. }
  186. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  187. return true;
  188. return false;
  189. }
  190. /**
  191. * Returns a material data structure holding the material property values for
  192. * monitoring.
  193. *
  194. * @param {Material} material - The material.
  195. * @return {Object} An object for monitoring material properties.
  196. */
  197. getMaterialData( material ) {
  198. const data = {};
  199. for ( const property of this.refreshUniforms ) {
  200. const value = material[ property ];
  201. if ( value === null || value === undefined ) continue;
  202. if ( typeof value === 'object' && value.clone !== undefined ) {
  203. if ( value.isTexture === true ) {
  204. data[ property ] = { id: value.id, version: value.version };
  205. } else {
  206. data[ property ] = value.clone();
  207. }
  208. } else {
  209. data[ property ] = value;
  210. }
  211. }
  212. return data;
  213. }
  214. /**
  215. * Returns `true` if the given render object has not changed its state.
  216. *
  217. * @param {RenderObject} renderObject - The render object.
  218. * @return {Boolean} Whether the given render object has changed its state or not.
  219. */
  220. equals( renderObject ) {
  221. const { object, material, geometry } = renderObject;
  222. const renderObjectData = this.getRenderObjectData( renderObject );
  223. // world matrix
  224. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  225. renderObjectData.worldMatrix.copy( object.matrixWorld );
  226. return false;
  227. }
  228. // material
  229. const materialData = renderObjectData.material;
  230. for ( const property in materialData ) {
  231. const value = materialData[ property ];
  232. const mtlValue = material[ property ];
  233. if ( value.equals !== undefined ) {
  234. if ( value.equals( mtlValue ) === false ) {
  235. value.copy( mtlValue );
  236. return false;
  237. }
  238. } else if ( mtlValue.isTexture === true ) {
  239. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  240. value.id = mtlValue.id;
  241. value.version = mtlValue.version;
  242. return false;
  243. }
  244. } else if ( value !== mtlValue ) {
  245. materialData[ property ] = mtlValue;
  246. return false;
  247. }
  248. }
  249. if ( materialData.transmission > 0 ) {
  250. const { width, height } = renderObject.context;
  251. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  252. renderObjectData.bufferWidth = width;
  253. renderObjectData.bufferHeight = height;
  254. return false;
  255. }
  256. }
  257. // geometry
  258. const storedGeometryData = renderObjectData.geometry;
  259. const attributes = geometry.attributes;
  260. const storedAttributes = storedGeometryData.attributes;
  261. const storedAttributeNames = Object.keys( storedAttributes );
  262. const currentAttributeNames = Object.keys( attributes );
  263. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  264. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  265. return false;
  266. }
  267. // compare each attribute
  268. for ( const name of storedAttributeNames ) {
  269. const storedAttributeData = storedAttributes[ name ];
  270. const attribute = attributes[ name ];
  271. if ( attribute === undefined ) {
  272. // attribute was removed
  273. delete storedAttributes[ name ];
  274. return false;
  275. }
  276. if ( storedAttributeData.version !== attribute.version ) {
  277. storedAttributeData.version = attribute.version;
  278. return false;
  279. }
  280. }
  281. // check index
  282. const index = geometry.index;
  283. const storedIndexVersion = storedGeometryData.indexVersion;
  284. const currentIndexVersion = index ? index.version : null;
  285. if ( storedIndexVersion !== currentIndexVersion ) {
  286. storedGeometryData.indexVersion = currentIndexVersion;
  287. return false;
  288. }
  289. // check drawRange
  290. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  291. storedGeometryData.drawRange.start = geometry.drawRange.start;
  292. storedGeometryData.drawRange.count = geometry.drawRange.count;
  293. return false;
  294. }
  295. // morph targets
  296. if ( renderObjectData.morphTargetInfluences ) {
  297. let morphChanged = false;
  298. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  299. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  300. morphChanged = true;
  301. }
  302. }
  303. if ( morphChanged ) return true;
  304. }
  305. // center
  306. if ( renderObjectData.center ) {
  307. if ( renderObjectData.center.equals( object.center ) === false ) {
  308. renderObjectData.center.copy( object.center );
  309. return true;
  310. }
  311. }
  312. // bundle
  313. if ( renderObject.bundle !== null ) {
  314. renderObjectData.version = renderObject.bundle.version;
  315. }
  316. return true;
  317. }
  318. /**
  319. * Checks if the given render object requires a refresh.
  320. *
  321. * @param {RenderObject} renderObject - The render object.
  322. * @param {NodeFrame} nodeFrame - The current node frame.
  323. * @return {Boolean} Whether the given render object requires a refresh or not.
  324. */
  325. needsRefresh( renderObject, nodeFrame ) {
  326. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  327. return true;
  328. const { renderId } = nodeFrame;
  329. if ( this.renderId !== renderId ) {
  330. this.renderId = renderId;
  331. return true;
  332. }
  333. const isStatic = renderObject.object.static === true;
  334. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  335. if ( isStatic || isBundle )
  336. return false;
  337. const notEqual = this.equals( renderObject ) !== true;
  338. return notEqual;
  339. }
  340. }
  341. /** @module NodeUtils **/
  342. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  343. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  344. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  345. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  346. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  347. function cyrb53( value, seed = 0 ) {
  348. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  349. if ( value instanceof Array ) {
  350. for ( let i = 0, val; i < value.length; i ++ ) {
  351. val = value[ i ];
  352. h1 = Math.imul( h1 ^ val, 2654435761 );
  353. h2 = Math.imul( h2 ^ val, 1597334677 );
  354. }
  355. } else {
  356. for ( let i = 0, ch; i < value.length; i ++ ) {
  357. ch = value.charCodeAt( i );
  358. h1 = Math.imul( h1 ^ ch, 2654435761 );
  359. h2 = Math.imul( h2 ^ ch, 1597334677 );
  360. }
  361. }
  362. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  363. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  364. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  365. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  366. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  367. }
  368. /**
  369. * Computes a hash for the given string.
  370. *
  371. * @method
  372. * @param {String} str - The string to be hashed.
  373. * @return {Number} The hash.
  374. */
  375. const hashString = ( str ) => cyrb53( str );
  376. /**
  377. * Computes a hash for the given array.
  378. *
  379. * @method
  380. * @param {Array<Number>} array - The array to be hashed.
  381. * @return {Number} The hash.
  382. */
  383. const hashArray = ( array ) => cyrb53( array );
  384. /**
  385. * Computes a hash for the given list of parameters.
  386. *
  387. * @method
  388. * @param {...Number} params - A list of parameters.
  389. * @return {Number} The hash.
  390. */
  391. const hash$1 = ( ...params ) => cyrb53( params );
  392. /**
  393. * Computes a cache key for the given node.
  394. *
  395. * @method
  396. * @param {Object} object - The object to be hashed.
  397. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  398. * @return {Number} The hash.
  399. */
  400. function getCacheKey$1( object, force = false ) {
  401. const values = [];
  402. if ( object.isNode === true ) {
  403. values.push( object.id );
  404. object = object.getSelf();
  405. }
  406. for ( const { property, childNode } of getNodeChildren( object ) ) {
  407. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  408. }
  409. return cyrb53( values );
  410. }
  411. /**
  412. * This generator function can be used to iterate over the node children
  413. * of the given object.
  414. *
  415. * @generator
  416. * @param {Object} node - The object to be hashed.
  417. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  418. * @yields {Object} A result node holding the property, index (if available) and the child node.
  419. */
  420. function* getNodeChildren( node, toJSON = false ) {
  421. for ( const property in node ) {
  422. // Ignore private properties.
  423. if ( property.startsWith( '_' ) === true ) continue;
  424. const object = node[ property ];
  425. if ( Array.isArray( object ) === true ) {
  426. for ( let i = 0; i < object.length; i ++ ) {
  427. const child = object[ i ];
  428. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  429. yield { property, index: i, childNode: child };
  430. }
  431. }
  432. } else if ( object && object.isNode === true ) {
  433. yield { property, childNode: object };
  434. } else if ( typeof object === 'object' ) {
  435. for ( const subProperty in object ) {
  436. const child = object[ subProperty ];
  437. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  438. yield { property, index: subProperty, childNode: child };
  439. }
  440. }
  441. }
  442. }
  443. }
  444. const typeFromLength = /*@__PURE__*/ new Map( [
  445. [ 1, 'float' ],
  446. [ 2, 'vec2' ],
  447. [ 3, 'vec3' ],
  448. [ 4, 'vec4' ],
  449. [ 9, 'mat3' ],
  450. [ 16, 'mat4' ]
  451. ] );
  452. const dataFromObject = /*@__PURE__*/ new WeakMap();
  453. /**
  454. * Returns the data type for the given the length.
  455. *
  456. * @method
  457. * @param {Number} length - The length.
  458. * @return {String} The data type.
  459. */
  460. function getTypeFromLength( length ) {
  461. return typeFromLength.get( length );
  462. }
  463. /**
  464. * Returns the typed array for the given data type.
  465. *
  466. * @method
  467. * @param {String} type - The data type.
  468. * @return {TypedArray} The typed array.
  469. */
  470. function getTypedArrayFromType( type ) {
  471. // Handle component type for vectors and matrices
  472. if ( /[iu]?vec\d/.test( type ) ) {
  473. // Handle int vectors
  474. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  475. // Handle uint vectors
  476. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  477. // Default to float vectors
  478. return Float32Array;
  479. }
  480. // Handle matrices (always float)
  481. if ( /mat\d/.test( type ) ) return Float32Array;
  482. // Basic types
  483. if ( /float/.test( type ) ) return Float32Array;
  484. if ( /uint/.test( type ) ) return Uint32Array;
  485. if ( /int/.test( type ) ) return Int32Array;
  486. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  487. }
  488. /**
  489. * Returns the length for the given data type.
  490. *
  491. * @method
  492. * @param {String} type - The data type.
  493. * @return {Number} The length.
  494. */
  495. function getLengthFromType( type ) {
  496. if ( /float|int|uint/.test( type ) ) return 1;
  497. if ( /vec2/.test( type ) ) return 2;
  498. if ( /vec3/.test( type ) ) return 3;
  499. if ( /vec4/.test( type ) ) return 4;
  500. if ( /mat2/.test( type ) ) return 4;
  501. if ( /mat3/.test( type ) ) return 9;
  502. if ( /mat4/.test( type ) ) return 16;
  503. console.error( 'THREE.TSL: Unsupported type:', type );
  504. }
  505. /**
  506. * Returns the data type for the given value.
  507. *
  508. * @method
  509. * @param {Any} value - The value.
  510. * @return {String?} The data type.
  511. */
  512. function getValueType( value ) {
  513. if ( value === undefined || value === null ) return null;
  514. const typeOf = typeof value;
  515. if ( value.isNode === true ) {
  516. return 'node';
  517. } else if ( typeOf === 'number' ) {
  518. return 'float';
  519. } else if ( typeOf === 'boolean' ) {
  520. return 'bool';
  521. } else if ( typeOf === 'string' ) {
  522. return 'string';
  523. } else if ( typeOf === 'function' ) {
  524. return 'shader';
  525. } else if ( value.isVector2 === true ) {
  526. return 'vec2';
  527. } else if ( value.isVector3 === true ) {
  528. return 'vec3';
  529. } else if ( value.isVector4 === true ) {
  530. return 'vec4';
  531. } else if ( value.isMatrix2 === true ) {
  532. return 'mat2';
  533. } else if ( value.isMatrix3 === true ) {
  534. return 'mat3';
  535. } else if ( value.isMatrix4 === true ) {
  536. return 'mat4';
  537. } else if ( value.isColor === true ) {
  538. return 'color';
  539. } else if ( value instanceof ArrayBuffer ) {
  540. return 'ArrayBuffer';
  541. }
  542. return null;
  543. }
  544. /**
  545. * Returns the value/object for the given data type and parameters.
  546. *
  547. * @method
  548. * @param {String} type - The given type.
  549. * @param {...Any} params - A parameter list.
  550. * @return {Any} The value/object.
  551. */
  552. function getValueFromType( type, ...params ) {
  553. const last4 = type ? type.slice( -4 ) : undefined;
  554. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  555. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  556. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  557. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  558. }
  559. if ( type === 'color' ) {
  560. return new Color( ...params );
  561. } else if ( last4 === 'vec2' ) {
  562. return new Vector2( ...params );
  563. } else if ( last4 === 'vec3' ) {
  564. return new Vector3( ...params );
  565. } else if ( last4 === 'vec4' ) {
  566. return new Vector4( ...params );
  567. } else if ( last4 === 'mat2' ) {
  568. return new Matrix2( ...params );
  569. } else if ( last4 === 'mat3' ) {
  570. return new Matrix3( ...params );
  571. } else if ( last4 === 'mat4' ) {
  572. return new Matrix4( ...params );
  573. } else if ( type === 'bool' ) {
  574. return params[ 0 ] || false;
  575. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  576. return params[ 0 ] || 0;
  577. } else if ( type === 'string' ) {
  578. return params[ 0 ] || '';
  579. } else if ( type === 'ArrayBuffer' ) {
  580. return base64ToArrayBuffer( params[ 0 ] );
  581. }
  582. return null;
  583. }
  584. /**
  585. * Gets the object data that can be shared between different rendering steps.
  586. *
  587. * @param {Object} object - The object to get the data for.
  588. * @return {Object} The object data.
  589. */
  590. function getDataFromObject( object ) {
  591. let data = dataFromObject.get( object );
  592. if ( data === undefined ) {
  593. data = {};
  594. dataFromObject.set( object, data );
  595. }
  596. return data;
  597. }
  598. /**
  599. * Converts the given array buffer to a Base64 string.
  600. *
  601. * @method
  602. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  603. * @return {String} The Base64 string.
  604. */
  605. function arrayBufferToBase64( arrayBuffer ) {
  606. let chars = '';
  607. const array = new Uint8Array( arrayBuffer );
  608. for ( let i = 0; i < array.length; i ++ ) {
  609. chars += String.fromCharCode( array[ i ] );
  610. }
  611. return btoa( chars );
  612. }
  613. /**
  614. * Converts the given Base64 string to an array buffer.
  615. *
  616. * @method
  617. * @param {String} base64 - The Base64 string.
  618. * @return {ArrayBuffer} The array buffer.
  619. */
  620. function base64ToArrayBuffer( base64 ) {
  621. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  622. }
  623. var NodeUtils = /*#__PURE__*/Object.freeze({
  624. __proto__: null,
  625. arrayBufferToBase64: arrayBufferToBase64,
  626. base64ToArrayBuffer: base64ToArrayBuffer,
  627. getCacheKey: getCacheKey$1,
  628. getDataFromObject: getDataFromObject,
  629. getLengthFromType: getLengthFromType,
  630. getNodeChildren: getNodeChildren,
  631. getTypeFromLength: getTypeFromLength,
  632. getTypedArrayFromType: getTypedArrayFromType,
  633. getValueFromType: getValueFromType,
  634. getValueType: getValueType,
  635. hash: hash$1,
  636. hashArray: hashArray,
  637. hashString: hashString
  638. });
  639. /** @module NodeConstants **/
  640. /**
  641. * Possible shader stages.
  642. *
  643. * @property {string} VERTEX The vertex shader stage.
  644. * @property {string} FRAGMENT The fragment shader stage.
  645. */
  646. const NodeShaderStage = {
  647. VERTEX: 'vertex',
  648. FRAGMENT: 'fragment'
  649. };
  650. /**
  651. * Update types of a node.
  652. *
  653. * @property {string} NONE The update method is not executed.
  654. * @property {string} FRAME The update method is executed per frame.
  655. * @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.
  656. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  657. */
  658. const NodeUpdateType = {
  659. NONE: 'none',
  660. FRAME: 'frame',
  661. RENDER: 'render',
  662. OBJECT: 'object'
  663. };
  664. /**
  665. * Data types of a node.
  666. *
  667. * @property {string} BOOLEAN Boolean type.
  668. * @property {string} INTEGER Integer type.
  669. * @property {string} FLOAT Float type.
  670. * @property {string} VECTOR2 Two-dimensional vector type.
  671. * @property {string} VECTOR3 Three-dimensional vector type.
  672. * @property {string} VECTOR4 Four-dimensional vector type.
  673. * @property {string} MATRIX2 2x2 matrix type.
  674. * @property {string} MATRIX3 3x3 matrix type.
  675. * @property {string} MATRIX4 4x4 matrix type.
  676. */
  677. const NodeType = {
  678. BOOLEAN: 'bool',
  679. INTEGER: 'int',
  680. FLOAT: 'float',
  681. VECTOR2: 'vec2',
  682. VECTOR3: 'vec3',
  683. VECTOR4: 'vec4',
  684. MATRIX2: 'mat2',
  685. MATRIX3: 'mat3',
  686. MATRIX4: 'mat4'
  687. };
  688. /**
  689. * Access types of a node. These are relevant for compute and storage usage.
  690. *
  691. * @property {string} READ_ONLY Read-only access
  692. * @property {string} WRITE_ONLY Write-only access.
  693. * @property {string} READ_WRITE Read and write access.
  694. */
  695. const NodeAccess = {
  696. READ_ONLY: 'readOnly',
  697. WRITE_ONLY: 'writeOnly',
  698. READ_WRITE: 'readWrite',
  699. };
  700. const defaultShaderStages = [ 'fragment', 'vertex' ];
  701. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  702. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  703. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  704. let _nodeId = 0;
  705. /**
  706. * Base class for all nodes.
  707. *
  708. * @augments EventDispatcher
  709. */
  710. class Node extends EventDispatcher {
  711. static get type() {
  712. return 'Node';
  713. }
  714. /**
  715. * Constructs a new node.
  716. *
  717. * @param {String?} nodeType - The node type.
  718. */
  719. constructor( nodeType = null ) {
  720. super();
  721. /**
  722. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  723. *
  724. * @type {String?}
  725. * @default null
  726. */
  727. this.nodeType = nodeType;
  728. /**
  729. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  730. *
  731. * @type {String}
  732. * @default 'none'
  733. */
  734. this.updateType = NodeUpdateType.NONE;
  735. /**
  736. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  737. *
  738. * @type {String}
  739. * @default 'none'
  740. */
  741. this.updateBeforeType = NodeUpdateType.NONE;
  742. /**
  743. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  744. *
  745. * @type {String}
  746. * @default 'none'
  747. */
  748. this.updateAfterType = NodeUpdateType.NONE;
  749. /**
  750. * The UUID of the node.
  751. *
  752. * @type {String}
  753. * @readonly
  754. */
  755. this.uuid = MathUtils.generateUUID();
  756. /**
  757. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  758. *
  759. * @type {Number}
  760. * @readonly
  761. * @default 0
  762. */
  763. this.version = 0;
  764. /**
  765. * Whether this node is global or not. This property is relevant for the internal
  766. * node caching system. All nodes which should be declared just once should
  767. * set this flag to `true` (a typical example is {@link AttributeNode}).
  768. *
  769. * @type {Boolean}
  770. * @default false
  771. */
  772. this.global = false;
  773. /**
  774. * This flag can be used for type testing.
  775. *
  776. * @type {Boolean}
  777. * @readonly
  778. * @default true
  779. */
  780. this.isNode = true;
  781. // private
  782. /**
  783. * The cache key of this node.
  784. *
  785. * @private
  786. * @type {Number?}
  787. * @default null
  788. */
  789. this._cacheKey = null;
  790. /**
  791. * The cache key 's version.
  792. *
  793. * @private
  794. * @type {Number}
  795. * @default 0
  796. */
  797. this._cacheKeyVersion = 0;
  798. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  799. }
  800. /**
  801. * Set this property to `true` when the node should be regenerated.
  802. *
  803. * @type {Boolean}
  804. * @default false
  805. * @param {boolean} value
  806. */
  807. set needsUpdate( value ) {
  808. if ( value === true ) {
  809. this.version ++;
  810. }
  811. }
  812. /**
  813. * The type of the class. The value is usually the constructor name.
  814. *
  815. * @type {String}
  816. * @readonly
  817. */
  818. get type() {
  819. return this.constructor.type;
  820. }
  821. /**
  822. * Convenient method for defining {@link Node#update}.
  823. *
  824. * @param {Function} callback - The update method.
  825. * @param {String} updateType - The update type.
  826. * @return {Node} A reference to this node.
  827. */
  828. onUpdate( callback, updateType ) {
  829. this.updateType = updateType;
  830. this.update = callback.bind( this.getSelf() );
  831. return this;
  832. }
  833. /**
  834. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  835. * this method automatically sets the update type to `FRAME`.
  836. *
  837. * @param {Function} callback - The update method.
  838. * @return {Node} A reference to this node.
  839. */
  840. onFrameUpdate( callback ) {
  841. return this.onUpdate( callback, NodeUpdateType.FRAME );
  842. }
  843. /**
  844. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  845. * this method automatically sets the update type to `RENDER`.
  846. *
  847. * @param {Function} callback - The update method.
  848. * @return {Node} A reference to this node.
  849. */
  850. onRenderUpdate( callback ) {
  851. return this.onUpdate( callback, NodeUpdateType.RENDER );
  852. }
  853. /**
  854. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  855. * this method automatically sets the update type to `OBJECT`.
  856. *
  857. * @param {Function} callback - The update method.
  858. * @return {Node} A reference to this node.
  859. */
  860. onObjectUpdate( callback ) {
  861. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  862. }
  863. /**
  864. * Convenient method for defining {@link Node#updateReference}.
  865. *
  866. * @param {Function} callback - The update method.
  867. * @return {Node} A reference to this node.
  868. */
  869. onReference( callback ) {
  870. this.updateReference = callback.bind( this.getSelf() );
  871. return this;
  872. }
  873. /**
  874. * The `this` reference might point to a Proxy so this method can be used
  875. * to get the reference to the actual node instance.
  876. *
  877. * @return {Node} A reference to the node.
  878. */
  879. getSelf() {
  880. // Returns non-node object.
  881. return this.self || this;
  882. }
  883. /**
  884. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  885. * to such objects based on a given state (e.g. the current node frame or builder).
  886. *
  887. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  888. * @return {Any} The updated reference.
  889. */
  890. updateReference( /*state*/ ) {
  891. return this;
  892. }
  893. /**
  894. * By default this method returns the value of the {@link Node#global} flag. This method
  895. * can be overwritten in derived classes if an analytical way is required to determine the
  896. * global status.
  897. *
  898. * @param {NodeBuilder} builder - The current node builder.
  899. * @return {Boolean} Whether this node is global or not.
  900. */
  901. isGlobal( /*builder*/ ) {
  902. return this.global;
  903. }
  904. /**
  905. * Generator function that can be used to iterate over the child nodes.
  906. *
  907. * @generator
  908. * @yields {Node} A child node.
  909. */
  910. * getChildren() {
  911. for ( const { childNode } of getNodeChildren( this ) ) {
  912. yield childNode;
  913. }
  914. }
  915. /**
  916. * Calling this method dispatches the `dispose` event. This event can be used
  917. * to register event listeners for clean up tasks.
  918. */
  919. dispose() {
  920. this.dispatchEvent( { type: 'dispose' } );
  921. }
  922. /**
  923. * Callback for {@link Node#traverse}.
  924. *
  925. * @callback traverseCallback
  926. * @param {Node} node - The current node.
  927. */
  928. /**
  929. * Can be used to traverse through the node's hierarchy.
  930. *
  931. * @param {traverseCallback} callback - A callback that is executed per node.
  932. */
  933. traverse( callback ) {
  934. callback( this );
  935. for ( const childNode of this.getChildren() ) {
  936. childNode.traverse( callback );
  937. }
  938. }
  939. /**
  940. * Returns the cache key for this node.
  941. *
  942. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  943. * @return {Number} The cache key of the node.
  944. */
  945. getCacheKey( force = false ) {
  946. force = force || this.version !== this._cacheKeyVersion;
  947. if ( force === true || this._cacheKey === null ) {
  948. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  949. this._cacheKeyVersion = this.version;
  950. }
  951. return this._cacheKey;
  952. }
  953. /**
  954. * Generate a custom cache key for this node.
  955. *
  956. * @return {Number} The cache key of the node.
  957. */
  958. customCacheKey() {
  959. return 0;
  960. }
  961. /**
  962. * Returns the references to this node which is by default `this`.
  963. *
  964. * @return {Node} A reference to this node.
  965. */
  966. getScope() {
  967. return this;
  968. }
  969. /**
  970. * Returns the hash of the node which is used to identify the node. By default it's
  971. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  972. * depending on their implementation.
  973. *
  974. * @param {NodeBuilder} builder - The current node builder.
  975. * @return {String} The hash.
  976. */
  977. getHash( /*builder*/ ) {
  978. return this.uuid;
  979. }
  980. /**
  981. * Returns the update type of {@link Node#update}.
  982. *
  983. * @return {NodeUpdateType} The update type.
  984. */
  985. getUpdateType() {
  986. return this.updateType;
  987. }
  988. /**
  989. * Returns the update type of {@link Node#updateBefore}.
  990. *
  991. * @return {NodeUpdateType} The update type.
  992. */
  993. getUpdateBeforeType() {
  994. return this.updateBeforeType;
  995. }
  996. /**
  997. * Returns the update type of {@link Node#updateAfter}.
  998. *
  999. * @return {NodeUpdateType} The update type.
  1000. */
  1001. getUpdateAfterType() {
  1002. return this.updateAfterType;
  1003. }
  1004. /**
  1005. * Certain types are composed of multiple elements. For example a `vec3`
  1006. * is composed of three `float` values. This method returns the type of
  1007. * these elements.
  1008. *
  1009. * @param {NodeBuilder} builder - The current node builder.
  1010. * @return {String} The type of the node.
  1011. */
  1012. getElementType( builder ) {
  1013. const type = this.getNodeType( builder );
  1014. const elementType = builder.getElementType( type );
  1015. return elementType;
  1016. }
  1017. /**
  1018. * Returns the node's type.
  1019. *
  1020. * @param {NodeBuilder} builder - The current node builder.
  1021. * @return {String} The type of the node.
  1022. */
  1023. getNodeType( builder ) {
  1024. const nodeProperties = builder.getNodeProperties( this );
  1025. if ( nodeProperties.outputNode ) {
  1026. return nodeProperties.outputNode.getNodeType( builder );
  1027. }
  1028. return this.nodeType;
  1029. }
  1030. /**
  1031. * This method is used during the build process of a node and ensures
  1032. * equal nodes are not built multiple times but just once. For example if
  1033. * `attribute( 'uv' )` is used multiple times by the user, the build
  1034. * process makes sure to process just the first node.
  1035. *
  1036. * @param {NodeBuilder} builder - The current node builder.
  1037. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1038. */
  1039. getShared( builder ) {
  1040. const hash = this.getHash( builder );
  1041. const nodeFromHash = builder.getNodeFromHash( hash );
  1042. return nodeFromHash || this;
  1043. }
  1044. /**
  1045. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1046. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1047. * The output node must be returned in the `return` statement.
  1048. *
  1049. * @param {NodeBuilder} builder - The current node builder.
  1050. * @return {Node?} The output node.
  1051. */
  1052. setup( builder ) {
  1053. const nodeProperties = builder.getNodeProperties( this );
  1054. let index = 0;
  1055. for ( const childNode of this.getChildren() ) {
  1056. nodeProperties[ 'node' + index ++ ] = childNode;
  1057. }
  1058. // return a outputNode if exists or null
  1059. return nodeProperties.outputNode || null;
  1060. }
  1061. /**
  1062. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1063. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1064. *
  1065. * @param {NodeBuilder} builder - The current node builder.
  1066. */
  1067. analyze( builder ) {
  1068. const usageCount = builder.increaseUsage( this );
  1069. if ( usageCount === 1 ) {
  1070. // node flow children
  1071. const nodeProperties = builder.getNodeProperties( this );
  1072. for ( const childNode of Object.values( nodeProperties ) ) {
  1073. if ( childNode && childNode.isNode === true ) {
  1074. childNode.build( builder );
  1075. }
  1076. }
  1077. }
  1078. }
  1079. /**
  1080. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1081. * This state builds the output node and returns the resulting shader string.
  1082. *
  1083. * @param {NodeBuilder} builder - The current node builder.
  1084. * @param {String?} output - Can be used to define the output type.
  1085. * @return {String?} The generated shader string.
  1086. */
  1087. generate( builder, output ) {
  1088. const { outputNode } = builder.getNodeProperties( this );
  1089. if ( outputNode && outputNode.isNode === true ) {
  1090. return outputNode.build( builder, output );
  1091. }
  1092. }
  1093. /**
  1094. * The method can be implemented to update the node's internal state before it is used to render an object.
  1095. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1096. *
  1097. * @abstract
  1098. * @param {NodeFrame} frame - A reference to the current node frame.
  1099. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1100. */
  1101. updateBefore( /*frame*/ ) {
  1102. console.warn( 'Abstract function.' );
  1103. }
  1104. /**
  1105. * The method can be implemented to update the node's internal state after it was used to render an object.
  1106. * The {@link Node#updateAfterType} 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. updateAfter( /*frame*/ ) {
  1113. console.warn( 'Abstract function.' );
  1114. }
  1115. /**
  1116. * The method can be implemented to update the node's internal state when it is used to render an object.
  1117. * The {@link Node#updateType} 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. update( /*frame*/ ) {
  1124. console.warn( 'Abstract function.' );
  1125. }
  1126. /**
  1127. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1128. * on the current build stage (setup, analyze or generate).
  1129. *
  1130. * @param {NodeBuilder} builder - The current node builder.
  1131. * @param {String?} output - Can be used to define the output type.
  1132. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1133. */
  1134. build( builder, output = null ) {
  1135. const refNode = this.getShared( builder );
  1136. if ( this !== refNode ) {
  1137. return refNode.build( builder, output );
  1138. }
  1139. builder.addNode( this );
  1140. builder.addChain( this );
  1141. /* Build stages expected results:
  1142. - "setup" -> Node
  1143. - "analyze" -> null
  1144. - "generate" -> String
  1145. */
  1146. let result = null;
  1147. const buildStage = builder.getBuildStage();
  1148. if ( buildStage === 'setup' ) {
  1149. this.updateReference( builder );
  1150. const properties = builder.getNodeProperties( this );
  1151. if ( properties.initialized !== true ) {
  1152. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1153. properties.initialized = true;
  1154. const outputNode = this.setup( builder ); // return a node or null
  1155. const isNodeOutput = outputNode && outputNode.isNode === true;
  1156. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1157. // !! no outputNode !!
  1158. //outputNode = builder.stack;
  1159. }*/
  1160. for ( const childNode of Object.values( properties ) ) {
  1161. if ( childNode && childNode.isNode === true ) {
  1162. childNode.build( builder );
  1163. }
  1164. }
  1165. if ( isNodeOutput ) {
  1166. outputNode.build( builder );
  1167. }
  1168. properties.outputNode = outputNode;
  1169. }
  1170. } else if ( buildStage === 'analyze' ) {
  1171. this.analyze( builder );
  1172. } else if ( buildStage === 'generate' ) {
  1173. const isGenerateOnce = this.generate.length === 1;
  1174. if ( isGenerateOnce ) {
  1175. const type = this.getNodeType( builder );
  1176. const nodeData = builder.getDataFromNode( this );
  1177. result = nodeData.snippet;
  1178. if ( result === undefined ) {
  1179. result = this.generate( builder ) || '';
  1180. nodeData.snippet = result;
  1181. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1182. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1183. }
  1184. result = builder.format( result, type, output );
  1185. } else {
  1186. result = this.generate( builder, output ) || '';
  1187. }
  1188. }
  1189. builder.removeChain( this );
  1190. builder.addSequentialNode( this );
  1191. return result;
  1192. }
  1193. /**
  1194. * Returns the child nodes as a JSON object.
  1195. *
  1196. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1197. */
  1198. getSerializeChildren() {
  1199. return getNodeChildren( this );
  1200. }
  1201. /**
  1202. * Serializes the node to JSON.
  1203. *
  1204. * @param {Object} json - The output JSON object.
  1205. */
  1206. serialize( json ) {
  1207. const nodeChildren = this.getSerializeChildren();
  1208. const inputNodes = {};
  1209. for ( const { property, index, childNode } of nodeChildren ) {
  1210. if ( index !== undefined ) {
  1211. if ( inputNodes[ property ] === undefined ) {
  1212. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1213. }
  1214. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1215. } else {
  1216. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1217. }
  1218. }
  1219. if ( Object.keys( inputNodes ).length > 0 ) {
  1220. json.inputNodes = inputNodes;
  1221. }
  1222. }
  1223. /**
  1224. * Deserializes the node from the given JSON.
  1225. *
  1226. * @param {Object} json - The JSON object.
  1227. */
  1228. deserialize( json ) {
  1229. if ( json.inputNodes !== undefined ) {
  1230. const nodes = json.meta.nodes;
  1231. for ( const property in json.inputNodes ) {
  1232. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1233. const inputArray = [];
  1234. for ( const uuid of json.inputNodes[ property ] ) {
  1235. inputArray.push( nodes[ uuid ] );
  1236. }
  1237. this[ property ] = inputArray;
  1238. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1239. const inputObject = {};
  1240. for ( const subProperty in json.inputNodes[ property ] ) {
  1241. const uuid = json.inputNodes[ property ][ subProperty ];
  1242. inputObject[ subProperty ] = nodes[ uuid ];
  1243. }
  1244. this[ property ] = inputObject;
  1245. } else {
  1246. const uuid = json.inputNodes[ property ];
  1247. this[ property ] = nodes[ uuid ];
  1248. }
  1249. }
  1250. }
  1251. }
  1252. /**
  1253. * Serializes the node into the three.js JSON Object/Scene format.
  1254. *
  1255. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1256. * @return {Object} The serialized node.
  1257. */
  1258. toJSON( meta ) {
  1259. const { uuid, type } = this;
  1260. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1261. if ( isRoot ) {
  1262. meta = {
  1263. textures: {},
  1264. images: {},
  1265. nodes: {}
  1266. };
  1267. }
  1268. // serialize
  1269. let data = meta.nodes[ uuid ];
  1270. if ( data === undefined ) {
  1271. data = {
  1272. uuid,
  1273. type,
  1274. meta,
  1275. metadata: {
  1276. version: 4.6,
  1277. type: 'Node',
  1278. generator: 'Node.toJSON'
  1279. }
  1280. };
  1281. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1282. this.serialize( data );
  1283. delete data.meta;
  1284. }
  1285. // TODO: Copied from Object3D.toJSON
  1286. function extractFromCache( cache ) {
  1287. const values = [];
  1288. for ( const key in cache ) {
  1289. const data = cache[ key ];
  1290. delete data.metadata;
  1291. values.push( data );
  1292. }
  1293. return values;
  1294. }
  1295. if ( isRoot ) {
  1296. const textures = extractFromCache( meta.textures );
  1297. const images = extractFromCache( meta.images );
  1298. const nodes = extractFromCache( meta.nodes );
  1299. if ( textures.length > 0 ) data.textures = textures;
  1300. if ( images.length > 0 ) data.images = images;
  1301. if ( nodes.length > 0 ) data.nodes = nodes;
  1302. }
  1303. return data;
  1304. }
  1305. }
  1306. /**
  1307. * Base class for representing element access on an array-like
  1308. * node data structures.
  1309. *
  1310. * @augments Node
  1311. */
  1312. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1313. static get type() {
  1314. return 'ArrayElementNode';
  1315. }
  1316. /**
  1317. * Constructs an array element node.
  1318. *
  1319. * @param {Node} node - The array-like node.
  1320. * @param {Node} indexNode - The index node that defines the element access.
  1321. */
  1322. constructor( node, indexNode ) {
  1323. super();
  1324. /**
  1325. * The array-like node.
  1326. *
  1327. * @type {Node}
  1328. */
  1329. this.node = node;
  1330. /**
  1331. * The index node that defines the element access.
  1332. *
  1333. * @type {Node}
  1334. */
  1335. this.indexNode = indexNode;
  1336. /**
  1337. * This flag can be used for type testing.
  1338. *
  1339. * @type {Boolean}
  1340. * @readonly
  1341. * @default true
  1342. */
  1343. this.isArrayElementNode = true;
  1344. }
  1345. /**
  1346. * This method is overwritten since the node type is inferred from the array-like node.
  1347. *
  1348. * @param {NodeBuilder} builder - The current node builder.
  1349. * @return {String} The node type.
  1350. */
  1351. getNodeType( builder ) {
  1352. return this.node.getElementType( builder );
  1353. }
  1354. generate( builder ) {
  1355. const nodeSnippet = this.node.build( builder );
  1356. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1357. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1358. }
  1359. }
  1360. /**
  1361. * This module is part of the TSL core and usually not used in app level code.
  1362. * It represents a convert operation during the shader generation process
  1363. * meaning it converts the data type of a node to a target data type.
  1364. *
  1365. * @augments Node
  1366. */
  1367. class ConvertNode extends Node {
  1368. static get type() {
  1369. return 'ConvertNode';
  1370. }
  1371. /**
  1372. * Constructs a new convert node.
  1373. *
  1374. * @param {Node} node - The node which type should be converted.
  1375. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1376. */
  1377. constructor( node, convertTo ) {
  1378. super();
  1379. /**
  1380. * The node which type should be converted.
  1381. *
  1382. * @type {Node}
  1383. */
  1384. this.node = node;
  1385. /**
  1386. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1387. *
  1388. * @type {String}
  1389. */
  1390. this.convertTo = convertTo;
  1391. }
  1392. /**
  1393. * This method is overwritten since the implementation tries to infer the best
  1394. * matching type from the {@link ConvertNode#convertTo} property.
  1395. *
  1396. * @param {NodeBuilder} builder - The current node builder.
  1397. * @return {String} The node type.
  1398. */
  1399. getNodeType( builder ) {
  1400. const requestType = this.node.getNodeType( builder );
  1401. let convertTo = null;
  1402. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1403. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1404. convertTo = overloadingType;
  1405. }
  1406. }
  1407. return convertTo;
  1408. }
  1409. serialize( data ) {
  1410. super.serialize( data );
  1411. data.convertTo = this.convertTo;
  1412. }
  1413. deserialize( data ) {
  1414. super.deserialize( data );
  1415. this.convertTo = data.convertTo;
  1416. }
  1417. generate( builder, output ) {
  1418. const node = this.node;
  1419. const type = this.getNodeType( builder );
  1420. const snippet = node.build( builder, type );
  1421. return builder.format( snippet, type, output );
  1422. }
  1423. }
  1424. /**
  1425. * This module uses cache management to create temporary variables
  1426. * if the node is used more than once to prevent duplicate calculations.
  1427. *
  1428. * The class acts as a base class for many other nodes types.
  1429. *
  1430. * @augments Node
  1431. */
  1432. class TempNode extends Node {
  1433. static get type() {
  1434. return 'TempNode';
  1435. }
  1436. /**
  1437. * Constructs a temp node.
  1438. *
  1439. * @param {String?} nodeType - The node type.
  1440. */
  1441. constructor( nodeType = null ) {
  1442. super( nodeType );
  1443. /**
  1444. * This flag can be used for type testing.
  1445. *
  1446. * @type {Boolean}
  1447. * @readonly
  1448. * @default true
  1449. */
  1450. this.isTempNode = true;
  1451. }
  1452. /**
  1453. * Whether this node is used more than once in context of other nodes.
  1454. *
  1455. * @param {NodeBuilder} builder - The node builder.
  1456. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1457. */
  1458. hasDependencies( builder ) {
  1459. return builder.getDataFromNode( this ).usageCount > 1;
  1460. }
  1461. build( builder, output ) {
  1462. const buildStage = builder.getBuildStage();
  1463. if ( buildStage === 'generate' ) {
  1464. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1465. const nodeData = builder.getDataFromNode( this );
  1466. if ( nodeData.propertyName !== undefined ) {
  1467. return builder.format( nodeData.propertyName, type, output );
  1468. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1469. const snippet = super.build( builder, type );
  1470. const nodeVar = builder.getVarFromNode( this, null, type );
  1471. const propertyName = builder.getPropertyName( nodeVar );
  1472. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1473. nodeData.snippet = snippet;
  1474. nodeData.propertyName = propertyName;
  1475. return builder.format( nodeData.propertyName, type, output );
  1476. }
  1477. }
  1478. return super.build( builder, output );
  1479. }
  1480. }
  1481. /**
  1482. * This module is part of the TSL core and usually not used in app level code.
  1483. * It represents a join operation during the shader generation process.
  1484. * For example in can compose/join two single floats into a `vec2` type.
  1485. *
  1486. * @augments TempNode
  1487. */
  1488. class JoinNode extends TempNode {
  1489. static get type() {
  1490. return 'JoinNode';
  1491. }
  1492. /**
  1493. * Constructs a new join node.
  1494. *
  1495. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1496. * @param {String?} [nodeType=null] - The node type.
  1497. */
  1498. constructor( nodes = [], nodeType = null ) {
  1499. super( nodeType );
  1500. /**
  1501. * An array of nodes that should be joined.
  1502. *
  1503. * @type {Array<Node>}
  1504. */
  1505. this.nodes = nodes;
  1506. }
  1507. /**
  1508. * This method is overwritten since the node type must be inferred from the
  1509. * joined data length if not explicitly defined.
  1510. *
  1511. * @param {NodeBuilder} builder - The current node builder.
  1512. * @return {String} The node type.
  1513. */
  1514. getNodeType( builder ) {
  1515. if ( this.nodeType !== null ) {
  1516. return builder.getVectorType( this.nodeType );
  1517. }
  1518. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1519. }
  1520. generate( builder, output ) {
  1521. const type = this.getNodeType( builder );
  1522. const nodes = this.nodes;
  1523. const primitiveType = builder.getComponentType( type );
  1524. const snippetValues = [];
  1525. for ( const input of nodes ) {
  1526. let inputSnippet = input.build( builder );
  1527. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1528. if ( inputPrimitiveType !== primitiveType ) {
  1529. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1530. }
  1531. snippetValues.push( inputSnippet );
  1532. }
  1533. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1534. return builder.format( snippet, type, output );
  1535. }
  1536. }
  1537. const _stringVectorComponents = vectorComponents.join( '' );
  1538. /**
  1539. * This module is part of the TSL core and usually not used in app level code.
  1540. * `SplitNode` represents a property access operation which means it is
  1541. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1542. * For example:
  1543. * ```js
  1544. * const redValue = color.r;
  1545. * ```
  1546. *
  1547. * @augments Node
  1548. */
  1549. class SplitNode extends Node {
  1550. static get type() {
  1551. return 'SplitNode';
  1552. }
  1553. /**
  1554. * Constructs a new split node.
  1555. *
  1556. * @param {Node} node - The node that should be accessed.
  1557. * @param {String} [components='x'] - The components that should be accessed.
  1558. */
  1559. constructor( node, components = 'x' ) {
  1560. super();
  1561. /**
  1562. * The node that should be accessed.
  1563. *
  1564. * @type {Node}
  1565. */
  1566. this.node = node;
  1567. /**
  1568. * The components that should be accessed.
  1569. *
  1570. * @type {string}
  1571. */
  1572. this.components = components;
  1573. /**
  1574. * This flag can be used for type testing.
  1575. *
  1576. * @type {Boolean}
  1577. * @readonly
  1578. * @default true
  1579. */
  1580. this.isSplitNode = true;
  1581. }
  1582. /**
  1583. * Returns the vector length which is computed based on the requested components.
  1584. *
  1585. * @return {Number} The vector length.
  1586. */
  1587. getVectorLength() {
  1588. let vectorLength = this.components.length;
  1589. for ( const c of this.components ) {
  1590. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1591. }
  1592. return vectorLength;
  1593. }
  1594. /**
  1595. * Returns the component type of the node's type.
  1596. *
  1597. * @param {NodeBuilder} builder - The current node builder.
  1598. * @return {String} The component type.
  1599. */
  1600. getComponentType( builder ) {
  1601. return builder.getComponentType( this.node.getNodeType( builder ) );
  1602. }
  1603. /**
  1604. * This method is overwritten since the node type is inferred from requested components.
  1605. *
  1606. * @param {NodeBuilder} builder - The current node builder.
  1607. * @return {String} The node type.
  1608. */
  1609. getNodeType( builder ) {
  1610. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1611. }
  1612. generate( builder, output ) {
  1613. const node = this.node;
  1614. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1615. let snippet = null;
  1616. if ( nodeTypeLength > 1 ) {
  1617. let type = null;
  1618. const componentsLength = this.getVectorLength();
  1619. if ( componentsLength >= nodeTypeLength ) {
  1620. // needed expand the input node
  1621. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1622. }
  1623. const nodeSnippet = node.build( builder, type );
  1624. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1625. // unnecessary swizzle
  1626. snippet = builder.format( nodeSnippet, type, output );
  1627. } else {
  1628. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1629. }
  1630. } else {
  1631. // ignore .components if .node returns float/integer
  1632. snippet = node.build( builder, output );
  1633. }
  1634. return snippet;
  1635. }
  1636. serialize( data ) {
  1637. super.serialize( data );
  1638. data.components = this.components;
  1639. }
  1640. deserialize( data ) {
  1641. super.deserialize( data );
  1642. this.components = data.components;
  1643. }
  1644. }
  1645. /**
  1646. * This module is part of the TSL core and usually not used in app level code.
  1647. * `SetNode` represents a set operation which means it is used to implement any
  1648. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1649. * For example:
  1650. * ```js
  1651. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1652. * ```
  1653. *
  1654. * @augments TempNode
  1655. */
  1656. class SetNode extends TempNode {
  1657. static get type() {
  1658. return 'SetNode';
  1659. }
  1660. /**
  1661. * Constructs a new set node.
  1662. *
  1663. * @param {Node} sourceNode - The node that should be updated.
  1664. * @param {String} components - The components that should be updated.
  1665. * @param {Node} targetNode - The value node.
  1666. */
  1667. constructor( sourceNode, components, targetNode ) {
  1668. super();
  1669. /**
  1670. * The node that should be updated.
  1671. *
  1672. * @type {Node}
  1673. */
  1674. this.sourceNode = sourceNode;
  1675. /**
  1676. * The components that should be updated.
  1677. *
  1678. * @type {String}
  1679. */
  1680. this.components = components;
  1681. /**
  1682. * The value node.
  1683. *
  1684. * @type {Node}
  1685. */
  1686. this.targetNode = targetNode;
  1687. }
  1688. /**
  1689. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1690. *
  1691. * @param {NodeBuilder} builder - The current node builder.
  1692. * @return {String} The node type.
  1693. */
  1694. getNodeType( builder ) {
  1695. return this.sourceNode.getNodeType( builder );
  1696. }
  1697. generate( builder ) {
  1698. const { sourceNode, components, targetNode } = this;
  1699. const sourceType = this.getNodeType( builder );
  1700. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1701. const targetType = builder.getTypeFromLength( components.length, componentType );
  1702. const targetSnippet = targetNode.build( builder, targetType );
  1703. const sourceSnippet = sourceNode.build( builder, sourceType );
  1704. const length = builder.getTypeLength( sourceType );
  1705. const snippetValues = [];
  1706. for ( let i = 0; i < length; i ++ ) {
  1707. const component = vectorComponents[ i ];
  1708. if ( component === components[ 0 ] ) {
  1709. snippetValues.push( targetSnippet );
  1710. i += components.length - 1;
  1711. } else {
  1712. snippetValues.push( sourceSnippet + '.' + component );
  1713. }
  1714. }
  1715. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1716. }
  1717. }
  1718. /**
  1719. * This module is part of the TSL core and usually not used in app level code.
  1720. * It represents a flip operation during the shader generation process
  1721. * meaning it flips normalized values with the following formula:
  1722. * ```
  1723. * x = 1 - x;
  1724. * ```
  1725. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1726. * `flipSTPQ()` method invocations on node objects. For example:
  1727. * ```js
  1728. * uvNode = uvNode.flipY();
  1729. * ```
  1730. *
  1731. * @augments TempNode
  1732. */
  1733. class FlipNode extends TempNode {
  1734. static get type() {
  1735. return 'FlipNode';
  1736. }
  1737. /**
  1738. * Constructs a new flip node.
  1739. *
  1740. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1741. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1742. */
  1743. constructor( sourceNode, components ) {
  1744. super();
  1745. /**
  1746. * The node which component(s) should be flipped.
  1747. *
  1748. * @type {Node}
  1749. */
  1750. this.sourceNode = sourceNode;
  1751. /**
  1752. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1753. *
  1754. * @type {String}
  1755. */
  1756. this.components = components;
  1757. }
  1758. /**
  1759. * This method is overwritten since the node type is inferred from the source node.
  1760. *
  1761. * @param {NodeBuilder} builder - The current node builder.
  1762. * @return {String} The node type.
  1763. */
  1764. getNodeType( builder ) {
  1765. return this.sourceNode.getNodeType( builder );
  1766. }
  1767. generate( builder ) {
  1768. const { components, sourceNode } = this;
  1769. const sourceType = this.getNodeType( builder );
  1770. const sourceSnippet = sourceNode.build( builder );
  1771. const sourceCache = builder.getVarFromNode( this );
  1772. const sourceProperty = builder.getPropertyName( sourceCache );
  1773. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1774. const length = builder.getTypeLength( sourceType );
  1775. const snippetValues = [];
  1776. let componentIndex = 0;
  1777. for ( let i = 0; i < length; i ++ ) {
  1778. const component = vectorComponents[ i ];
  1779. if ( component === components[ componentIndex ] ) {
  1780. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1781. componentIndex ++;
  1782. } else {
  1783. snippetValues.push( sourceProperty + '.' + component );
  1784. }
  1785. }
  1786. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1787. }
  1788. }
  1789. /**
  1790. * Base class for representing data input nodes.
  1791. *
  1792. * @augments Node
  1793. */
  1794. class InputNode extends Node {
  1795. static get type() {
  1796. return 'InputNode';
  1797. }
  1798. /**
  1799. * Constructs a new input node.
  1800. *
  1801. * @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).
  1802. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1803. */
  1804. constructor( value, nodeType = null ) {
  1805. super( nodeType );
  1806. /**
  1807. * This flag can be used for type testing.
  1808. *
  1809. * @type {Boolean}
  1810. * @readonly
  1811. * @default true
  1812. */
  1813. this.isInputNode = true;
  1814. /**
  1815. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1816. *
  1817. * @type {Any}
  1818. */
  1819. this.value = value;
  1820. /**
  1821. * The precision of the value in the shader.
  1822. *
  1823. * @type {('low'|'medium'|'high')?}
  1824. * @default null
  1825. */
  1826. this.precision = null;
  1827. }
  1828. getNodeType( /*builder*/ ) {
  1829. if ( this.nodeType === null ) {
  1830. return getValueType( this.value );
  1831. }
  1832. return this.nodeType;
  1833. }
  1834. /**
  1835. * Returns the input type of the node which is by default the node type. Derived modules
  1836. * might overwrite this method and use a fixed type or compute one analytically.
  1837. *
  1838. * A typical example for different input and node types are textures. The input type of a
  1839. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1840. *
  1841. * @param {NodeBuilder} builder - The current node builder.
  1842. * @return {String} The input type.
  1843. */
  1844. getInputType( builder ) {
  1845. return this.getNodeType( builder );
  1846. }
  1847. /**
  1848. * Sets the precision to the given value. The method can be
  1849. * overwritten in derived classes if the final precision must be computed
  1850. * analytically.
  1851. *
  1852. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1853. * @return {InputNode} A reference to this node.
  1854. */
  1855. setPrecision( precision ) {
  1856. this.precision = precision;
  1857. return this;
  1858. }
  1859. serialize( data ) {
  1860. super.serialize( data );
  1861. data.value = this.value;
  1862. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1863. data.valueType = getValueType( this.value );
  1864. data.nodeType = this.nodeType;
  1865. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1866. data.precision = this.precision;
  1867. }
  1868. deserialize( data ) {
  1869. super.deserialize( data );
  1870. this.nodeType = data.nodeType;
  1871. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1872. this.precision = data.precision || null;
  1873. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1874. }
  1875. generate( /*builder, output*/ ) {
  1876. console.warn( 'Abstract function.' );
  1877. }
  1878. }
  1879. /**
  1880. * Class for representing a constant value in the shader.
  1881. *
  1882. * @augments InputNode
  1883. */
  1884. class ConstNode extends InputNode {
  1885. static get type() {
  1886. return 'ConstNode';
  1887. }
  1888. /**
  1889. * Constructs a new input node.
  1890. *
  1891. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1892. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1893. */
  1894. constructor( value, nodeType = null ) {
  1895. super( value, nodeType );
  1896. /**
  1897. * This flag can be used for type testing.
  1898. *
  1899. * @type {Boolean}
  1900. * @readonly
  1901. * @default true
  1902. */
  1903. this.isConstNode = true;
  1904. }
  1905. /**
  1906. * Generates the shader string of the value with the current node builder.
  1907. *
  1908. * @param {NodeBuilder} builder - The current node builder.
  1909. * @return {String} The generated value as a shader string.
  1910. */
  1911. generateConst( builder ) {
  1912. return builder.generateConst( this.getNodeType( builder ), this.value );
  1913. }
  1914. generate( builder, output ) {
  1915. const type = this.getNodeType( builder );
  1916. return builder.format( this.generateConst( builder ), type, output );
  1917. }
  1918. }
  1919. /** @module TSLCore **/
  1920. let currentStack = null;
  1921. const NodeElements = new Map();
  1922. function addMethodChaining( name, nodeElement ) {
  1923. if ( NodeElements.has( name ) ) {
  1924. console.warn( `Redefinition of method chaining ${ name }` );
  1925. return;
  1926. }
  1927. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1928. NodeElements.set( name, nodeElement );
  1929. }
  1930. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1931. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1932. const shaderNodeHandler = {
  1933. setup( NodeClosure, params ) {
  1934. const inputs = params.shift();
  1935. return NodeClosure( nodeObjects( inputs ), ...params );
  1936. },
  1937. get( node, prop, nodeObj ) {
  1938. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1939. if ( node.isStackNode !== true && prop === 'assign' ) {
  1940. return ( ...params ) => {
  1941. currentStack.assign( nodeObj, ...params );
  1942. return nodeObj;
  1943. };
  1944. } else if ( NodeElements.has( prop ) ) {
  1945. const nodeElement = NodeElements.get( prop );
  1946. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1947. } else if ( prop === 'self' ) {
  1948. return node;
  1949. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1950. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1951. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1952. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1953. // accessing properties ( swizzle )
  1954. prop = parseSwizzle( prop );
  1955. return nodeObject( new SplitNode( nodeObj, prop ) );
  1956. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1957. // set properties ( swizzle ) and sort to xyzw sequence
  1958. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1959. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1960. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1961. // set properties ( swizzle ) and sort to xyzw sequence
  1962. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1963. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1964. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1965. // accessing property
  1966. if ( prop === 'width' ) prop = 'x';
  1967. else if ( prop === 'height' ) prop = 'y';
  1968. else if ( prop === 'depth' ) prop = 'z';
  1969. return nodeObject( new SplitNode( node, prop ) );
  1970. } else if ( /^\d+$/.test( prop ) === true ) {
  1971. // accessing array
  1972. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1973. }
  1974. }
  1975. return Reflect.get( node, prop, nodeObj );
  1976. },
  1977. set( node, prop, value, nodeObj ) {
  1978. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1979. // setting properties
  1980. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1981. nodeObj[ prop ].assign( value );
  1982. return true;
  1983. }
  1984. }
  1985. return Reflect.set( node, prop, value, nodeObj );
  1986. }
  1987. };
  1988. const nodeObjectsCacheMap = new WeakMap();
  1989. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1990. const ShaderNodeObject = function ( obj, altType = null ) {
  1991. const type = getValueType( obj );
  1992. if ( type === 'node' ) {
  1993. let nodeObject = nodeObjectsCacheMap.get( obj );
  1994. if ( nodeObject === undefined ) {
  1995. nodeObject = new Proxy( obj, shaderNodeHandler );
  1996. nodeObjectsCacheMap.set( obj, nodeObject );
  1997. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1998. }
  1999. return nodeObject;
  2000. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2001. return nodeObject( getConstNode( obj, altType ) );
  2002. } else if ( type === 'shader' ) {
  2003. return Fn( obj );
  2004. }
  2005. return obj;
  2006. };
  2007. const ShaderNodeObjects = function ( objects, altType = null ) {
  2008. for ( const name in objects ) {
  2009. objects[ name ] = nodeObject( objects[ name ], altType );
  2010. }
  2011. return objects;
  2012. };
  2013. const ShaderNodeArray = function ( array, altType = null ) {
  2014. const len = array.length;
  2015. for ( let i = 0; i < len; i ++ ) {
  2016. array[ i ] = nodeObject( array[ i ], altType );
  2017. }
  2018. return array;
  2019. };
  2020. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2021. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2022. if ( scope === null ) {
  2023. return ( ...params ) => {
  2024. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2025. };
  2026. } else if ( factor !== null ) {
  2027. factor = nodeObject( factor );
  2028. return ( ...params ) => {
  2029. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2030. };
  2031. } else {
  2032. return ( ...params ) => {
  2033. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2034. };
  2035. }
  2036. };
  2037. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2038. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2039. };
  2040. class ShaderCallNodeInternal extends Node {
  2041. constructor( shaderNode, inputNodes ) {
  2042. super();
  2043. this.shaderNode = shaderNode;
  2044. this.inputNodes = inputNodes;
  2045. }
  2046. getNodeType( builder ) {
  2047. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2048. }
  2049. call( builder ) {
  2050. const { shaderNode, inputNodes } = this;
  2051. const properties = builder.getNodeProperties( shaderNode );
  2052. if ( properties.onceOutput ) return properties.onceOutput;
  2053. //
  2054. let result = null;
  2055. if ( shaderNode.layout ) {
  2056. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2057. if ( functionNodesCacheMap === undefined ) {
  2058. functionNodesCacheMap = new WeakMap();
  2059. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2060. }
  2061. let functionNode = functionNodesCacheMap.get( shaderNode );
  2062. if ( functionNode === undefined ) {
  2063. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2064. functionNodesCacheMap.set( shaderNode, functionNode );
  2065. }
  2066. if ( builder.currentFunctionNode !== null ) {
  2067. builder.currentFunctionNode.includes.push( functionNode );
  2068. }
  2069. result = nodeObject( functionNode.call( inputNodes ) );
  2070. } else {
  2071. const jsFunc = shaderNode.jsFunc;
  2072. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2073. result = nodeObject( outputNode );
  2074. }
  2075. if ( shaderNode.once ) {
  2076. properties.onceOutput = result;
  2077. }
  2078. return result;
  2079. }
  2080. getOutputNode( builder ) {
  2081. const properties = builder.getNodeProperties( this );
  2082. if ( properties.outputNode === null ) {
  2083. properties.outputNode = this.setupOutput( builder );
  2084. }
  2085. return properties.outputNode;
  2086. }
  2087. setup( builder ) {
  2088. return this.getOutputNode( builder );
  2089. }
  2090. setupOutput( builder ) {
  2091. builder.addStack();
  2092. builder.stack.outputNode = this.call( builder );
  2093. return builder.removeStack();
  2094. }
  2095. generate( builder, output ) {
  2096. const outputNode = this.getOutputNode( builder );
  2097. return outputNode.build( builder, output );
  2098. }
  2099. }
  2100. class ShaderNodeInternal extends Node {
  2101. constructor( jsFunc, nodeType ) {
  2102. super( nodeType );
  2103. this.jsFunc = jsFunc;
  2104. this.layout = null;
  2105. this.global = true;
  2106. this.once = false;
  2107. }
  2108. setLayout( layout ) {
  2109. this.layout = layout;
  2110. return this;
  2111. }
  2112. call( inputs = null ) {
  2113. nodeObjects( inputs );
  2114. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2115. }
  2116. setup() {
  2117. return this.call();
  2118. }
  2119. }
  2120. const bools = [ false, true ];
  2121. const uints = [ 0, 1, 2, 3 ];
  2122. const ints = [ -1, -2 ];
  2123. 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 ];
  2124. const boolsCacheMap = new Map();
  2125. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2126. const uintsCacheMap = new Map();
  2127. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2128. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2129. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2130. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2131. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2132. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2133. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2134. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2135. const getConstNode = ( value, type ) => {
  2136. if ( constNodesCacheMap.has( value ) ) {
  2137. return constNodesCacheMap.get( value );
  2138. } else if ( value.isNode === true ) {
  2139. return value;
  2140. } else {
  2141. return new ConstNode( value, type );
  2142. }
  2143. };
  2144. const safeGetNodeType = ( node ) => {
  2145. try {
  2146. return node.getNodeType();
  2147. } catch ( _ ) {
  2148. return undefined;
  2149. }
  2150. };
  2151. const ConvertType = function ( type, cacheMap = null ) {
  2152. return ( ...params ) => {
  2153. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2154. params = [ getValueFromType( type, ...params ) ];
  2155. }
  2156. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2157. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2158. }
  2159. if ( params.length === 1 ) {
  2160. const node = getConstNode( params[ 0 ], type );
  2161. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2162. return nodeObject( new ConvertNode( node, type ) );
  2163. }
  2164. const nodes = params.map( param => getConstNode( param ) );
  2165. return nodeObject( new JoinNode( nodes, type ) );
  2166. };
  2167. };
  2168. // exports
  2169. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2170. // utils
  2171. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2172. // shader node base
  2173. function ShaderNode( jsFunc, nodeType ) {
  2174. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2175. }
  2176. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2177. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2178. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2179. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2180. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2181. const Fn = ( jsFunc, nodeType ) => {
  2182. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2183. const fn = ( ...params ) => {
  2184. let inputs;
  2185. nodeObjects( params );
  2186. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2187. inputs = [ ...params ];
  2188. } else {
  2189. inputs = params[ 0 ];
  2190. }
  2191. return shaderNode.call( inputs );
  2192. };
  2193. fn.shaderNode = shaderNode;
  2194. fn.setLayout = ( layout ) => {
  2195. shaderNode.setLayout( layout );
  2196. return fn;
  2197. };
  2198. fn.once = () => {
  2199. shaderNode.once = true;
  2200. return fn;
  2201. };
  2202. return fn;
  2203. };
  2204. /**
  2205. * @function
  2206. * @deprecated since r168. Use {@link Fn} instead.
  2207. *
  2208. * @param {...any} params
  2209. * @returns {Function}
  2210. */
  2211. const tslFn = ( ...params ) => { // @deprecated, r168
  2212. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2213. return Fn( ...params );
  2214. };
  2215. //
  2216. addMethodChaining( 'toGlobal', ( node ) => {
  2217. node.global = true;
  2218. return node;
  2219. } );
  2220. //
  2221. const setCurrentStack = ( stack ) => {
  2222. currentStack = stack;
  2223. };
  2224. const getCurrentStack = () => currentStack;
  2225. const If = ( ...params ) => currentStack.If( ...params );
  2226. function append( node ) {
  2227. if ( currentStack ) currentStack.add( node );
  2228. return node;
  2229. }
  2230. addMethodChaining( 'append', append );
  2231. // types
  2232. const color = new ConvertType( 'color' );
  2233. const float = new ConvertType( 'float', cacheMaps.float );
  2234. const int = new ConvertType( 'int', cacheMaps.ints );
  2235. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2236. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2237. const vec2 = new ConvertType( 'vec2' );
  2238. const ivec2 = new ConvertType( 'ivec2' );
  2239. const uvec2 = new ConvertType( 'uvec2' );
  2240. const bvec2 = new ConvertType( 'bvec2' );
  2241. const vec3 = new ConvertType( 'vec3' );
  2242. const ivec3 = new ConvertType( 'ivec3' );
  2243. const uvec3 = new ConvertType( 'uvec3' );
  2244. const bvec3 = new ConvertType( 'bvec3' );
  2245. const vec4 = new ConvertType( 'vec4' );
  2246. const ivec4 = new ConvertType( 'ivec4' );
  2247. const uvec4 = new ConvertType( 'uvec4' );
  2248. const bvec4 = new ConvertType( 'bvec4' );
  2249. const mat2 = new ConvertType( 'mat2' );
  2250. const mat3 = new ConvertType( 'mat3' );
  2251. const mat4 = new ConvertType( 'mat4' );
  2252. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2253. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2254. addMethodChaining( 'toColor', color );
  2255. addMethodChaining( 'toFloat', float );
  2256. addMethodChaining( 'toInt', int );
  2257. addMethodChaining( 'toUint', uint );
  2258. addMethodChaining( 'toBool', bool );
  2259. addMethodChaining( 'toVec2', vec2 );
  2260. addMethodChaining( 'toIVec2', ivec2 );
  2261. addMethodChaining( 'toUVec2', uvec2 );
  2262. addMethodChaining( 'toBVec2', bvec2 );
  2263. addMethodChaining( 'toVec3', vec3 );
  2264. addMethodChaining( 'toIVec3', ivec3 );
  2265. addMethodChaining( 'toUVec3', uvec3 );
  2266. addMethodChaining( 'toBVec3', bvec3 );
  2267. addMethodChaining( 'toVec4', vec4 );
  2268. addMethodChaining( 'toIVec4', ivec4 );
  2269. addMethodChaining( 'toUVec4', uvec4 );
  2270. addMethodChaining( 'toBVec4', bvec4 );
  2271. addMethodChaining( 'toMat2', mat2 );
  2272. addMethodChaining( 'toMat3', mat3 );
  2273. addMethodChaining( 'toMat4', mat4 );
  2274. // basic nodes
  2275. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2276. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2277. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2278. addMethodChaining( 'element', element );
  2279. addMethodChaining( 'convert', convert );
  2280. /** @module ArrayNode **/
  2281. /**
  2282. * ArrayNode represents a collection of nodes, typically created using the {@link module:TSL~array} function.
  2283. * ```js
  2284. * const colors = array( [
  2285. * vec3( 1, 0, 0 ),
  2286. * vec3( 0, 1, 0 ),
  2287. * vec3( 0, 0, 1 )
  2288. * ] );
  2289. *
  2290. * const redColor = tintColors.element( 0 );
  2291. *
  2292. * @augments Node
  2293. */
  2294. class ArrayNode extends TempNode {
  2295. static get type() {
  2296. return 'ArrayNode';
  2297. }
  2298. /**
  2299. * Constructs a new array node.
  2300. *
  2301. * @param {String} [nodeType] - The data type of the elements.
  2302. * @param {Number} [count] - Size of the array.
  2303. * @param {Array<Node>?} [values=null] - Array default values.
  2304. */
  2305. constructor( nodeType, count, values = null ) {
  2306. super( nodeType );
  2307. /**
  2308. * Array size.
  2309. *
  2310. * @type {Array<Node>}
  2311. */
  2312. this.count = count;
  2313. /**
  2314. * Array default values.
  2315. *
  2316. * @type {Array<Node>}
  2317. */
  2318. this.values = values;
  2319. /**
  2320. * This flag can be used for type testing.
  2321. *
  2322. * @type {Boolean}
  2323. * @readonly
  2324. * @default true
  2325. */
  2326. this.isArrayNode = true;
  2327. }
  2328. getNodeType( builder ) {
  2329. if ( this.nodeType === null ) {
  2330. this.nodeType = this.values[ 0 ].getNodeType( builder );
  2331. }
  2332. return this.nodeType;
  2333. }
  2334. getElementType( builder ) {
  2335. return this.getNodeType( builder );
  2336. }
  2337. generate( builder ) {
  2338. const type = this.getNodeType( builder );
  2339. return builder.generateArray( type, this.count, this.values );
  2340. }
  2341. }
  2342. /**
  2343. * TSL function for creating an array node.
  2344. *
  2345. * @function
  2346. * @param {String|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  2347. * or an array containing the default values (e.g., [ vec3() ]).
  2348. * @param {Number?} [count] - Size of the array.
  2349. * @returns {ArrayNode}
  2350. */
  2351. const array = ( ...params ) => {
  2352. let node;
  2353. if ( params.length === 1 ) {
  2354. const values = params[ 0 ];
  2355. node = new ArrayNode( null, values.length, values );
  2356. } else {
  2357. const nodeType = params[ 0 ];
  2358. const count = params[ 1 ];
  2359. node = new ArrayNode( nodeType, count );
  2360. }
  2361. return nodeObject( node );
  2362. };
  2363. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  2364. /** @module UniformGroupNode **/
  2365. /**
  2366. * This node can be used to group single instances of {@link UniformNode}
  2367. * and manage them as a uniform buffer.
  2368. *
  2369. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2370. * will be used when defining the {@link UniformNode#groupNode} property.
  2371. *
  2372. * - `objectGroup`: Uniform buffer per object.
  2373. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2374. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2375. *
  2376. * @augments Node
  2377. */
  2378. class UniformGroupNode extends Node {
  2379. static get type() {
  2380. return 'UniformGroupNode';
  2381. }
  2382. /**
  2383. * Constructs a new uniform group node.
  2384. *
  2385. * @param {String} name - The name of the uniform group node.
  2386. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2387. * @param {Number} [order=1] - Influences the internal sorting.
  2388. */
  2389. constructor( name, shared = false, order = 1 ) {
  2390. super( 'string' );
  2391. /**
  2392. * The name of the uniform group node.
  2393. *
  2394. * @type {String}
  2395. */
  2396. this.name = name;
  2397. /**
  2398. * Whether this uniform group node is shared or not.
  2399. *
  2400. * @type {Boolean}
  2401. * @default false
  2402. */
  2403. this.shared = shared;
  2404. /**
  2405. * Influences the internal sorting.
  2406. * TODO: Add details when this property should be changed.
  2407. *
  2408. * @type {Number}
  2409. * @default 1
  2410. */
  2411. this.order = order;
  2412. /**
  2413. * This flag can be used for type testing.
  2414. *
  2415. * @type {Boolean}
  2416. * @readonly
  2417. * @default true
  2418. */
  2419. this.isUniformGroup = true;
  2420. }
  2421. serialize( data ) {
  2422. super.serialize( data );
  2423. data.name = this.name;
  2424. data.version = this.version;
  2425. data.shared = this.shared;
  2426. }
  2427. deserialize( data ) {
  2428. super.deserialize( data );
  2429. this.name = data.name;
  2430. this.version = data.version;
  2431. this.shared = data.shared;
  2432. }
  2433. }
  2434. /**
  2435. * TSL function for creating a uniform group node with the given name.
  2436. *
  2437. * @function
  2438. * @param {String} name - The name of the uniform group node.
  2439. * @returns {UniformGroupNode}
  2440. */
  2441. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2442. /**
  2443. * TSL function for creating a shared uniform group node with the given name and order.
  2444. *
  2445. * @function
  2446. * @param {String} name - The name of the uniform group node.
  2447. * @param {Number} [order=0] - Influences the internal sorting.
  2448. * @returns {UniformGroupNode}
  2449. */
  2450. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2451. /**
  2452. * TSL object that represents a shared uniform group node which is updated once per frame.
  2453. *
  2454. * @type {UniformGroupNode}
  2455. */
  2456. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2457. /**
  2458. * TSL object that represents a shared uniform group node which is updated once per render.
  2459. *
  2460. * @type {UniformGroupNode}
  2461. */
  2462. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2463. /**
  2464. * TSL object that represents a uniform group node which is updated once per object.
  2465. *
  2466. * @type {UniformGroupNode}
  2467. */
  2468. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2469. /** @module UniformNode **/
  2470. /**
  2471. * Class for representing a uniform.
  2472. *
  2473. * @augments InputNode
  2474. */
  2475. class UniformNode extends InputNode {
  2476. static get type() {
  2477. return 'UniformNode';
  2478. }
  2479. /**
  2480. * Constructs a new uniform node.
  2481. *
  2482. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2483. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2484. */
  2485. constructor( value, nodeType = null ) {
  2486. super( value, nodeType );
  2487. /**
  2488. * This flag can be used for type testing.
  2489. *
  2490. * @type {Boolean}
  2491. * @readonly
  2492. * @default true
  2493. */
  2494. this.isUniformNode = true;
  2495. /**
  2496. * The name or label of the uniform.
  2497. *
  2498. * @type {String}
  2499. * @default ''
  2500. */
  2501. this.name = '';
  2502. /**
  2503. * The uniform group of this uniform. By default, uniforms are
  2504. * managed per object but they might belong to a shared group
  2505. * which is updated per frame or render call.
  2506. *
  2507. * @type {UniformGroupNode}
  2508. */
  2509. this.groupNode = objectGroup;
  2510. }
  2511. /**
  2512. * Sets the {@link UniformNode#name} property.
  2513. *
  2514. * @param {String} name - The name of the uniform.
  2515. * @return {UniformNode} A reference to this node.
  2516. */
  2517. label( name ) {
  2518. this.name = name;
  2519. return this;
  2520. }
  2521. /**
  2522. * Sets the {@link UniformNode#groupNode} property.
  2523. *
  2524. * @param {UniformGroupNode} group - The uniform group.
  2525. * @return {UniformNode} A reference to this node.
  2526. */
  2527. setGroup( group ) {
  2528. this.groupNode = group;
  2529. return this;
  2530. }
  2531. /**
  2532. * Returns the {@link UniformNode#groupNode}.
  2533. *
  2534. * @return {UniformGroupNode} The uniform group.
  2535. */
  2536. getGroup() {
  2537. return this.groupNode;
  2538. }
  2539. /**
  2540. * By default, this method returns the result of {@link Node#getHash} but derived
  2541. * classes might overwrite this method with a different implementation.
  2542. *
  2543. * @param {NodeBuilder} builder - The current node builder.
  2544. * @return {String} The uniform hash.
  2545. */
  2546. getUniformHash( builder ) {
  2547. return this.getHash( builder );
  2548. }
  2549. onUpdate( callback, updateType ) {
  2550. const self = this.getSelf();
  2551. callback = callback.bind( self );
  2552. return super.onUpdate( ( frame ) => {
  2553. const value = callback( frame, self );
  2554. if ( value !== undefined ) {
  2555. this.value = value;
  2556. }
  2557. }, updateType );
  2558. }
  2559. generate( builder, output ) {
  2560. const type = this.getNodeType( builder );
  2561. const hash = this.getUniformHash( builder );
  2562. let sharedNode = builder.getNodeFromHash( hash );
  2563. if ( sharedNode === undefined ) {
  2564. builder.setHashNode( this, hash );
  2565. sharedNode = this;
  2566. }
  2567. const sharedNodeType = sharedNode.getInputType( builder );
  2568. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2569. const propertyName = builder.getPropertyName( nodeUniform );
  2570. if ( builder.context.label !== undefined ) delete builder.context.label;
  2571. return builder.format( propertyName, type, output );
  2572. }
  2573. }
  2574. /**
  2575. * TSL function for creating a uniform node.
  2576. *
  2577. * @function
  2578. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2579. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2580. * @returns {UniformNode}
  2581. */
  2582. const uniform = ( arg1, arg2 ) => {
  2583. const nodeType = getConstNodeType( arg2 || arg1 );
  2584. // @TODO: get ConstNode from .traverse() in the future
  2585. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2586. return nodeObject( new UniformNode( value, nodeType ) );
  2587. };
  2588. /** @module PropertyNode **/
  2589. /**
  2590. * This class represents a shader property. It can be used
  2591. * to explicitly define a property and assign a value to it.
  2592. *
  2593. * ```js
  2594. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2595. *```
  2596. * `PropertyNode` is used by the engine to predefined common material properties
  2597. * for TSL code.
  2598. *
  2599. * @augments Node
  2600. */
  2601. class PropertyNode extends Node {
  2602. static get type() {
  2603. return 'PropertyNode';
  2604. }
  2605. /**
  2606. * Constructs a new property node.
  2607. *
  2608. * @param {String} nodeType - The type of the node.
  2609. * @param {String?} [name=null] - The name of the property in the shader.
  2610. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2611. */
  2612. constructor( nodeType, name = null, varying = false ) {
  2613. super( nodeType );
  2614. /**
  2615. * The name of the property in the shader. If no name is defined,
  2616. * the node system auto-generates one.
  2617. *
  2618. * @type {String?}
  2619. * @default null
  2620. */
  2621. this.name = name;
  2622. /**
  2623. * Whether this property is a varying or not.
  2624. *
  2625. * @type {Boolean}
  2626. * @default false
  2627. */
  2628. this.varying = varying;
  2629. /**
  2630. * This flag can be used for type testing.
  2631. *
  2632. * @type {Boolean}
  2633. * @readonly
  2634. * @default true
  2635. */
  2636. this.isPropertyNode = true;
  2637. }
  2638. getHash( builder ) {
  2639. return this.name || super.getHash( builder );
  2640. }
  2641. /**
  2642. * The method is overwritten so it always returns `true`.
  2643. *
  2644. * @param {NodeBuilder} builder - The current node builder.
  2645. * @return {Boolean} Whether this node is global or not.
  2646. */
  2647. isGlobal( /*builder*/ ) {
  2648. return true;
  2649. }
  2650. generate( builder ) {
  2651. let nodeVar;
  2652. if ( this.varying === true ) {
  2653. nodeVar = builder.getVaryingFromNode( this, this.name );
  2654. nodeVar.needsInterpolation = true;
  2655. } else {
  2656. nodeVar = builder.getVarFromNode( this, this.name );
  2657. }
  2658. return builder.getPropertyName( nodeVar );
  2659. }
  2660. }
  2661. /**
  2662. * TSL function for creating a property node.
  2663. *
  2664. * @function
  2665. * @param {String} type - The type of the node.
  2666. * @param {String?} [name=null] - The name of the property in the shader.
  2667. * @returns {PropertyNode}
  2668. */
  2669. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2670. /**
  2671. * TSL function for creating a varying property node.
  2672. *
  2673. * @function
  2674. * @param {String} type - The type of the node.
  2675. * @param {String?} [name=null] - The name of the varying in the shader.
  2676. * @returns {PropertyNode}
  2677. */
  2678. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2679. /**
  2680. * TSL object that represents the shader variable `DiffuseColor`.
  2681. *
  2682. * @type {PropertyNode<vec4>}
  2683. */
  2684. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2685. /**
  2686. * TSL object that represents the shader variable `EmissiveColor`.
  2687. *
  2688. * @type {PropertyNode<vec3>}
  2689. */
  2690. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2691. /**
  2692. * TSL object that represents the shader variable `Roughness`.
  2693. *
  2694. * @type {PropertyNode<float>}
  2695. */
  2696. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2697. /**
  2698. * TSL object that represents the shader variable `Metalness`.
  2699. *
  2700. * @type {PropertyNode<float>}
  2701. */
  2702. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2703. /**
  2704. * TSL object that represents the shader variable `Clearcoat`.
  2705. *
  2706. * @type {PropertyNode<float>}
  2707. */
  2708. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2709. /**
  2710. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2711. *
  2712. * @type {PropertyNode<float>}
  2713. */
  2714. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2715. /**
  2716. * TSL object that represents the shader variable `Sheen`.
  2717. *
  2718. * @type {PropertyNode<vec3>}
  2719. */
  2720. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2721. /**
  2722. * TSL object that represents the shader variable `SheenRoughness`.
  2723. *
  2724. * @type {PropertyNode<float>}
  2725. */
  2726. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2727. /**
  2728. * TSL object that represents the shader variable `Iridescence`.
  2729. *
  2730. * @type {PropertyNode<float>}
  2731. */
  2732. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2733. /**
  2734. * TSL object that represents the shader variable `IridescenceIOR`.
  2735. *
  2736. * @type {PropertyNode<float>}
  2737. */
  2738. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2739. /**
  2740. * TSL object that represents the shader variable `IridescenceThickness`.
  2741. *
  2742. * @type {PropertyNode<float>}
  2743. */
  2744. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2745. /**
  2746. * TSL object that represents the shader variable `AlphaT`.
  2747. *
  2748. * @type {PropertyNode<float>}
  2749. */
  2750. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2751. /**
  2752. * TSL object that represents the shader variable `Anisotropy`.
  2753. *
  2754. * @type {PropertyNode<float>}
  2755. */
  2756. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2757. /**
  2758. * TSL object that represents the shader variable `AnisotropyT`.
  2759. *
  2760. * @type {PropertyNode<vec3>}
  2761. */
  2762. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2763. /**
  2764. * TSL object that represents the shader variable `AnisotropyB`.
  2765. *
  2766. * @type {PropertyNode<vec3>}
  2767. */
  2768. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2769. /**
  2770. * TSL object that represents the shader variable `SpecularColor`.
  2771. *
  2772. * @type {PropertyNode<color>}
  2773. */
  2774. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2775. /**
  2776. * TSL object that represents the shader variable `SpecularF90`.
  2777. *
  2778. * @type {PropertyNode<float>}
  2779. */
  2780. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2781. /**
  2782. * TSL object that represents the shader variable `Shininess`.
  2783. *
  2784. * @type {PropertyNode<float>}
  2785. */
  2786. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2787. /**
  2788. * TSL object that represents the shader variable `Output`.
  2789. *
  2790. * @type {PropertyNode<vec4>}
  2791. */
  2792. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2793. /**
  2794. * TSL object that represents the shader variable `dashSize`.
  2795. *
  2796. * @type {PropertyNode<float>}
  2797. */
  2798. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2799. /**
  2800. * TSL object that represents the shader variable `gapSize`.
  2801. *
  2802. * @type {PropertyNode<float>}
  2803. */
  2804. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2805. /**
  2806. * TSL object that represents the shader variable `pointWidth`.
  2807. *
  2808. * @type {PropertyNode<float>}
  2809. */
  2810. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2811. /**
  2812. * TSL object that represents the shader variable `IOR`.
  2813. *
  2814. * @type {PropertyNode<float>}
  2815. */
  2816. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2817. /**
  2818. * TSL object that represents the shader variable `Transmission`.
  2819. *
  2820. * @type {PropertyNode<float>}
  2821. */
  2822. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2823. /**
  2824. * TSL object that represents the shader variable `Thickness`.
  2825. *
  2826. * @type {PropertyNode<float>}
  2827. */
  2828. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2829. /**
  2830. * TSL object that represents the shader variable `AttenuationDistance`.
  2831. *
  2832. * @type {PropertyNode<float>}
  2833. */
  2834. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2835. /**
  2836. * TSL object that represents the shader variable `AttenuationColor`.
  2837. *
  2838. * @type {PropertyNode<color>}
  2839. */
  2840. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2841. /**
  2842. * TSL object that represents the shader variable `Dispersion`.
  2843. *
  2844. * @type {PropertyNode<float>}
  2845. */
  2846. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2847. /** @module AssignNode **/
  2848. /**
  2849. * These node represents an assign operation. Meaning a node is assigned
  2850. * to another node.
  2851. *
  2852. * @augments TempNode
  2853. */
  2854. class AssignNode extends TempNode {
  2855. static get type() {
  2856. return 'AssignNode';
  2857. }
  2858. /**
  2859. * Constructs a new assign node.
  2860. *
  2861. * @param {Node} targetNode - The target node.
  2862. * @param {Node} sourceNode - The source type.
  2863. */
  2864. constructor( targetNode, sourceNode ) {
  2865. super();
  2866. /**
  2867. * The target node.
  2868. *
  2869. * @type {Node}
  2870. */
  2871. this.targetNode = targetNode;
  2872. /**
  2873. * The source node.
  2874. *
  2875. * @type {Node}
  2876. */
  2877. this.sourceNode = sourceNode;
  2878. }
  2879. /**
  2880. * Whether this node is used more than once in context of other nodes. This method
  2881. * is overwritten since it always returns `false` (assigns are unique).
  2882. *
  2883. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2884. */
  2885. hasDependencies() {
  2886. return false;
  2887. }
  2888. getNodeType( builder, output ) {
  2889. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2890. }
  2891. /**
  2892. * Whether a split is required when assigning source to target. This can happen when the component length of
  2893. * target and source data type does not match.
  2894. *
  2895. * @param {NodeBuilder} builder - The current node builder.
  2896. * @return {Boolean} Whether a split is required when assigning source to target.
  2897. */
  2898. needsSplitAssign( builder ) {
  2899. const { targetNode } = this;
  2900. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2901. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2902. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2903. return assignDifferentVector;
  2904. }
  2905. return false;
  2906. }
  2907. generate( builder, output ) {
  2908. const { targetNode, sourceNode } = this;
  2909. const needsSplitAssign = this.needsSplitAssign( builder );
  2910. const targetType = targetNode.getNodeType( builder );
  2911. const target = targetNode.context( { assign: true } ).build( builder );
  2912. const source = sourceNode.build( builder, targetType );
  2913. const sourceType = sourceNode.getNodeType( builder );
  2914. const nodeData = builder.getDataFromNode( this );
  2915. //
  2916. let snippet;
  2917. if ( nodeData.initialized === true ) {
  2918. if ( output !== 'void' ) {
  2919. snippet = target;
  2920. }
  2921. } else if ( needsSplitAssign ) {
  2922. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2923. const sourceProperty = builder.getPropertyName( sourceVar );
  2924. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2925. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2926. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2927. const component = targetNode.components[ i ];
  2928. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2929. }
  2930. if ( output !== 'void' ) {
  2931. snippet = target;
  2932. }
  2933. } else {
  2934. snippet = `${ target } = ${ source }`;
  2935. if ( output === 'void' || sourceType === 'void' ) {
  2936. builder.addLineFlowCode( snippet, this );
  2937. if ( output !== 'void' ) {
  2938. snippet = target;
  2939. }
  2940. }
  2941. }
  2942. nodeData.initialized = true;
  2943. return builder.format( snippet, targetType, output );
  2944. }
  2945. }
  2946. /**
  2947. * TSL function for creating an assign node.
  2948. *
  2949. * @function
  2950. * @param {Node} targetNode - The target node.
  2951. * @param {Node} sourceNode - The source type.
  2952. * @returns {AssignNode}
  2953. */
  2954. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2955. addMethodChaining( 'assign', assign );
  2956. /**
  2957. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2958. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2959. * this logic.
  2960. *
  2961. * @augments TempNode
  2962. */
  2963. class FunctionCallNode extends TempNode {
  2964. static get type() {
  2965. return 'FunctionCallNode';
  2966. }
  2967. /**
  2968. * Constructs a new function call node.
  2969. *
  2970. * @param {FunctionNode?} functionNode - The function node.
  2971. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2972. */
  2973. constructor( functionNode = null, parameters = {} ) {
  2974. super();
  2975. /**
  2976. * The function node.
  2977. *
  2978. * @type {FunctionNode}
  2979. * @default null
  2980. */
  2981. this.functionNode = functionNode;
  2982. /**
  2983. * The parameters of the function call.
  2984. *
  2985. * @type {Object<String, Node>}
  2986. * @default {}
  2987. */
  2988. this.parameters = parameters;
  2989. }
  2990. /**
  2991. * Sets the parameters of the function call node.
  2992. *
  2993. * @param {Object<String, Node>} parameters - The parameters to set.
  2994. * @return {FunctionCallNode} A reference to this node.
  2995. */
  2996. setParameters( parameters ) {
  2997. this.parameters = parameters;
  2998. return this;
  2999. }
  3000. /**
  3001. * Returns the parameters of the function call node.
  3002. *
  3003. * @return {Object<String, Node>} The parameters of this node.
  3004. */
  3005. getParameters() {
  3006. return this.parameters;
  3007. }
  3008. getNodeType( builder ) {
  3009. return this.functionNode.getNodeType( builder );
  3010. }
  3011. generate( builder ) {
  3012. const params = [];
  3013. const functionNode = this.functionNode;
  3014. const inputs = functionNode.getInputs( builder );
  3015. const parameters = this.parameters;
  3016. const generateInput = ( node, inputNode ) => {
  3017. const type = inputNode.type;
  3018. const pointer = type === 'pointer';
  3019. let output;
  3020. if ( pointer ) output = '&' + node.build( builder );
  3021. else output = node.build( builder, type );
  3022. return output;
  3023. };
  3024. if ( Array.isArray( parameters ) ) {
  3025. for ( let i = 0; i < parameters.length; i ++ ) {
  3026. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3027. }
  3028. } else {
  3029. for ( const inputNode of inputs ) {
  3030. const node = parameters[ inputNode.name ];
  3031. if ( node !== undefined ) {
  3032. params.push( generateInput( node, inputNode ) );
  3033. } else {
  3034. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  3035. }
  3036. }
  3037. }
  3038. const functionName = functionNode.build( builder, 'property' );
  3039. return `${functionName}( ${params.join( ', ' )} )`;
  3040. }
  3041. }
  3042. const call = ( func, ...params ) => {
  3043. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3044. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3045. };
  3046. addMethodChaining( 'call', call );
  3047. /** @module OperatorNode **/
  3048. /**
  3049. * This node represents basic mathematical and logical operations like addition,
  3050. * subtraction or comparisons (e.g. `equal()`).
  3051. *
  3052. * @augments TempNode
  3053. */
  3054. class OperatorNode extends TempNode {
  3055. static get type() {
  3056. return 'OperatorNode';
  3057. }
  3058. /**
  3059. * Constructs a new operator node.
  3060. *
  3061. * @param {String} op - The operator.
  3062. * @param {Node} aNode - The first input.
  3063. * @param {Node} bNode - The second input.
  3064. * @param {...Node} params - Additional input parameters.
  3065. */
  3066. constructor( op, aNode, bNode, ...params ) {
  3067. super();
  3068. if ( params.length > 0 ) {
  3069. let finalOp = new OperatorNode( op, aNode, bNode );
  3070. for ( let i = 0; i < params.length - 1; i ++ ) {
  3071. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3072. }
  3073. aNode = finalOp;
  3074. bNode = params[ params.length - 1 ];
  3075. }
  3076. /**
  3077. * The operator.
  3078. *
  3079. * @type {String}
  3080. */
  3081. this.op = op;
  3082. /**
  3083. * The first input.
  3084. *
  3085. * @type {Node}
  3086. */
  3087. this.aNode = aNode;
  3088. /**
  3089. * The second input.
  3090. *
  3091. * @type {Node}
  3092. */
  3093. this.bNode = bNode;
  3094. /**
  3095. * This flag can be used for type testing.
  3096. *
  3097. * @type {Boolean}
  3098. * @readonly
  3099. * @default true
  3100. */
  3101. this.isOperatorNode = true;
  3102. }
  3103. /**
  3104. * This method is overwritten since the node type is inferred from the operator
  3105. * and the input node types.
  3106. *
  3107. * @param {NodeBuilder} builder - The current node builder.
  3108. * @param {String} output - The current output string.
  3109. * @return {String} The node type.
  3110. */
  3111. getNodeType( builder, output ) {
  3112. const op = this.op;
  3113. const aNode = this.aNode;
  3114. const bNode = this.bNode;
  3115. const typeA = aNode.getNodeType( builder );
  3116. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3117. if ( typeA === 'void' || typeB === 'void' ) {
  3118. return 'void';
  3119. } else if ( op === '%' ) {
  3120. return typeA;
  3121. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3122. return builder.getIntegerType( typeA );
  3123. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3124. return 'bool';
  3125. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3126. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3127. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3128. } else {
  3129. // Handle matrix operations
  3130. if ( builder.isMatrix( typeA ) ) {
  3131. if ( typeB === 'float' ) {
  3132. return typeA; // matrix * scalar = matrix
  3133. } else if ( builder.isVector( typeB ) ) {
  3134. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3135. } else if ( builder.isMatrix( typeB ) ) {
  3136. return typeA; // matrix * matrix
  3137. }
  3138. } else if ( builder.isMatrix( typeB ) ) {
  3139. if ( typeA === 'float' ) {
  3140. return typeB; // scalar * matrix = matrix
  3141. } else if ( builder.isVector( typeA ) ) {
  3142. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3143. }
  3144. }
  3145. // Handle non-matrix cases
  3146. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3147. // anytype x anytype: use the greater length vector
  3148. return typeB;
  3149. }
  3150. return typeA;
  3151. }
  3152. }
  3153. generate( builder, output ) {
  3154. const op = this.op;
  3155. const aNode = this.aNode;
  3156. const bNode = this.bNode;
  3157. const type = this.getNodeType( builder, output );
  3158. let typeA = null;
  3159. let typeB = null;
  3160. if ( type !== 'void' ) {
  3161. typeA = aNode.getNodeType( builder );
  3162. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3163. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3164. if ( builder.isVector( typeA ) ) {
  3165. typeB = typeA;
  3166. } else if ( typeA !== typeB ) {
  3167. typeA = typeB = 'float';
  3168. }
  3169. } else if ( op === '>>' || op === '<<' ) {
  3170. typeA = type;
  3171. typeB = builder.changeComponentType( typeB, 'uint' );
  3172. } else if ( builder.isMatrix( typeA ) ) {
  3173. if ( typeB === 'float' ) {
  3174. // Keep matrix type for typeA, but ensure typeB stays float
  3175. typeB = 'float';
  3176. } else if ( builder.isVector( typeB ) ) {
  3177. // matrix x vector
  3178. typeB = builder.getVectorFromMatrix( typeA );
  3179. } else if ( builder.isMatrix( typeB ) ) ; else {
  3180. typeA = typeB = type;
  3181. }
  3182. } else if ( builder.isMatrix( typeB ) ) {
  3183. if ( typeA === 'float' ) {
  3184. // Keep matrix type for typeB, but ensure typeA stays float
  3185. typeA = 'float';
  3186. } else if ( builder.isVector( typeA ) ) {
  3187. // vector x matrix
  3188. typeA = builder.getVectorFromMatrix( typeB );
  3189. } else {
  3190. typeA = typeB = type;
  3191. }
  3192. } else {
  3193. // anytype x anytype
  3194. typeA = typeB = type;
  3195. }
  3196. } else {
  3197. typeA = typeB = type;
  3198. }
  3199. const a = aNode.build( builder, typeA );
  3200. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3201. const outputLength = builder.getTypeLength( output );
  3202. const fnOpSnippet = builder.getFunctionOperator( op );
  3203. if ( output !== 'void' ) {
  3204. if ( op === '<' && outputLength > 1 ) {
  3205. if ( builder.useComparisonMethod ) {
  3206. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3207. } else {
  3208. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3209. }
  3210. } else if ( op === '<=' && outputLength > 1 ) {
  3211. if ( builder.useComparisonMethod ) {
  3212. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3213. } else {
  3214. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3215. }
  3216. } else if ( op === '>' && outputLength > 1 ) {
  3217. if ( builder.useComparisonMethod ) {
  3218. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3219. } else {
  3220. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3221. }
  3222. } else if ( op === '>=' && outputLength > 1 ) {
  3223. if ( builder.useComparisonMethod ) {
  3224. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3225. } else {
  3226. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3227. }
  3228. } else if ( op === '!' || op === '~' ) {
  3229. return builder.format( `(${op}${a})`, typeA, output );
  3230. } else if ( fnOpSnippet ) {
  3231. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3232. } else {
  3233. // Handle matrix operations
  3234. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3235. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3236. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3237. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3238. } else {
  3239. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3240. }
  3241. }
  3242. } else if ( typeA !== 'void' ) {
  3243. if ( fnOpSnippet ) {
  3244. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3245. } else {
  3246. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3247. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3248. } else {
  3249. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3250. }
  3251. }
  3252. }
  3253. }
  3254. serialize( data ) {
  3255. super.serialize( data );
  3256. data.op = this.op;
  3257. }
  3258. deserialize( data ) {
  3259. super.deserialize( data );
  3260. this.op = data.op;
  3261. }
  3262. }
  3263. /**
  3264. * Returns the addition of two or more value.
  3265. *
  3266. * @function
  3267. * @param {Node} aNode - The first input.
  3268. * @param {Node} bNode - The second input.
  3269. * @param {...Node} params - Additional input parameters.
  3270. * @returns {OperatorNode}
  3271. */
  3272. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3273. /**
  3274. * Returns the subtraction of two or more value.
  3275. *
  3276. * @function
  3277. * @param {Node} aNode - The first input.
  3278. * @param {Node} bNode - The second input.
  3279. * @param {...Node} params - Additional input parameters.
  3280. * @returns {OperatorNode}
  3281. */
  3282. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3283. /**
  3284. * Returns the multiplication of two or more value.
  3285. *
  3286. * @function
  3287. * @param {Node} aNode - The first input.
  3288. * @param {Node} bNode - The second input.
  3289. * @param {...Node} params - Additional input parameters.
  3290. * @returns {OperatorNode}
  3291. */
  3292. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3293. /**
  3294. * Returns the division of two or more value.
  3295. *
  3296. * @function
  3297. * @param {Node} aNode - The first input.
  3298. * @param {Node} bNode - The second input.
  3299. * @param {...Node} params - Additional input parameters.
  3300. * @returns {OperatorNode}
  3301. */
  3302. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3303. /**
  3304. * Computes the remainder of dividing the first node by the second, for integer values.
  3305. *
  3306. * @function
  3307. * @param {Node} aNode - The first input.
  3308. * @param {Node} bNode - The second input.
  3309. * @returns {OperatorNode}
  3310. */
  3311. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3312. /**
  3313. * Checks if two nodes are equal.
  3314. *
  3315. * @function
  3316. * @param {Node} aNode - The first input.
  3317. * @param {Node} bNode - The second input.
  3318. * @returns {OperatorNode}
  3319. */
  3320. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3321. /**
  3322. * Checks if two nodes are not equal.
  3323. *
  3324. * @function
  3325. * @param {Node} aNode - The first input.
  3326. * @param {Node} bNode - The second input.
  3327. * @returns {OperatorNode}
  3328. */
  3329. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3330. /**
  3331. * Checks if the first node is less than the second.
  3332. *
  3333. * @function
  3334. * @param {Node} aNode - The first input.
  3335. * @param {Node} bNode - The second input.
  3336. * @returns {OperatorNode}
  3337. */
  3338. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3339. /**
  3340. * Checks if the first node is greater than the second.
  3341. *
  3342. * @function
  3343. * @param {Node} aNode - The first input.
  3344. * @param {Node} bNode - The second input.
  3345. * @returns {OperatorNode}
  3346. */
  3347. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3348. /**
  3349. * Checks if the first node is less than or equal to the second.
  3350. *
  3351. * @function
  3352. * @param {Node} aNode - The first input.
  3353. * @param {Node} bNode - The second input.
  3354. * @returns {OperatorNode}
  3355. */
  3356. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3357. /**
  3358. * Checks if the first node is greater than or equal to the second.
  3359. *
  3360. * @function
  3361. * @param {Node} aNode - The first input.
  3362. * @param {Node} bNode - The second input.
  3363. * @returns {OperatorNode}
  3364. */
  3365. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3366. /**
  3367. * Performs logical AND on two nodes.
  3368. *
  3369. * @function
  3370. * @param {Node} aNode - The first input.
  3371. * @param {Node} bNode - The second input.
  3372. * @returns {OperatorNode}
  3373. */
  3374. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3375. /**
  3376. * Performs logical OR on two nodes.
  3377. *
  3378. * @function
  3379. * @param {Node} aNode - The first input.
  3380. * @param {Node} bNode - The second input.
  3381. * @returns {OperatorNode}
  3382. */
  3383. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3384. /**
  3385. * Performs logical NOT on a node.
  3386. *
  3387. * @function
  3388. * @param {Node} aNode - The first input.
  3389. * @param {Node} bNode - The second input.
  3390. * @returns {OperatorNode}
  3391. */
  3392. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3393. /**
  3394. * Performs logical XOR on two nodes.
  3395. *
  3396. * @function
  3397. * @param {Node} aNode - The first input.
  3398. * @param {Node} bNode - The second input.
  3399. * @returns {OperatorNode}
  3400. */
  3401. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3402. /**
  3403. * Performs bitwise AND on two nodes.
  3404. *
  3405. * @function
  3406. * @param {Node} aNode - The first input.
  3407. * @param {Node} bNode - The second input.
  3408. * @returns {OperatorNode}
  3409. */
  3410. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3411. /**
  3412. * Performs bitwise NOT on a node.
  3413. *
  3414. * @function
  3415. * @param {Node} aNode - The first input.
  3416. * @param {Node} bNode - The second input.
  3417. * @returns {OperatorNode}
  3418. */
  3419. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3420. /**
  3421. * Performs bitwise OR on two nodes.
  3422. *
  3423. * @function
  3424. * @param {Node} aNode - The first input.
  3425. * @param {Node} bNode - The second input.
  3426. * @returns {OperatorNode}
  3427. */
  3428. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3429. /**
  3430. * Performs bitwise XOR on two nodes.
  3431. *
  3432. * @function
  3433. * @param {Node} aNode - The first input.
  3434. * @param {Node} bNode - The second input.
  3435. * @returns {OperatorNode}
  3436. */
  3437. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3438. /**
  3439. * Shifts a node to the left.
  3440. *
  3441. * @function
  3442. * @param {Node} aNode - The node to shift.
  3443. * @param {Node} bNode - The value to shift.
  3444. * @returns {OperatorNode}
  3445. */
  3446. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3447. /**
  3448. * Shifts a node to the right.
  3449. *
  3450. * @function
  3451. * @param {Node} aNode - The node to shift.
  3452. * @param {Node} bNode - The value to shift.
  3453. * @returns {OperatorNode}
  3454. */
  3455. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3456. addMethodChaining( 'add', add );
  3457. addMethodChaining( 'sub', sub );
  3458. addMethodChaining( 'mul', mul );
  3459. addMethodChaining( 'div', div );
  3460. addMethodChaining( 'modInt', modInt );
  3461. addMethodChaining( 'equal', equal );
  3462. addMethodChaining( 'notEqual', notEqual );
  3463. addMethodChaining( 'lessThan', lessThan );
  3464. addMethodChaining( 'greaterThan', greaterThan );
  3465. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3466. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3467. addMethodChaining( 'and', and );
  3468. addMethodChaining( 'or', or );
  3469. addMethodChaining( 'not', not );
  3470. addMethodChaining( 'xor', xor );
  3471. addMethodChaining( 'bitAnd', bitAnd );
  3472. addMethodChaining( 'bitNot', bitNot );
  3473. addMethodChaining( 'bitOr', bitOr );
  3474. addMethodChaining( 'bitXor', bitXor );
  3475. addMethodChaining( 'shiftLeft', shiftLeft );
  3476. addMethodChaining( 'shiftRight', shiftRight );
  3477. /**
  3478. * @function
  3479. * @deprecated since r168. Use {@link modInt} instead.
  3480. *
  3481. * @param {...any} params
  3482. * @returns {Function}
  3483. */
  3484. const remainder = ( ...params ) => { // @deprecated, r168
  3485. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3486. return modInt( ...params );
  3487. };
  3488. addMethodChaining( 'remainder', remainder );
  3489. /** @module MathNode **/
  3490. /**
  3491. * This node represents a variety of mathematical methods available in shaders.
  3492. * They are divided into three categories:
  3493. *
  3494. * - Methods with one input like `sin`, `cos` or `normalize`.
  3495. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3496. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3497. *
  3498. * @augments TempNode
  3499. */
  3500. class MathNode extends TempNode {
  3501. static get type() {
  3502. return 'MathNode';
  3503. }
  3504. /**
  3505. * Constructs a new math node.
  3506. *
  3507. * @param {String} method - The method name.
  3508. * @param {Node} aNode - The first input.
  3509. * @param {Node?} [bNode=null] - The second input.
  3510. * @param {Node?} [cNode=null] - The third input.
  3511. */
  3512. constructor( method, aNode, bNode = null, cNode = null ) {
  3513. super();
  3514. /**
  3515. * The method name.
  3516. *
  3517. * @type {String}
  3518. */
  3519. this.method = method;
  3520. /**
  3521. * The first input.
  3522. *
  3523. * @type {Node}
  3524. */
  3525. this.aNode = aNode;
  3526. /**
  3527. * The second input.
  3528. *
  3529. * @type {Node?}
  3530. * @default null
  3531. */
  3532. this.bNode = bNode;
  3533. /**
  3534. * The third input.
  3535. *
  3536. * @type {Node?}
  3537. * @default null
  3538. */
  3539. this.cNode = cNode;
  3540. /**
  3541. * This flag can be used for type testing.
  3542. *
  3543. * @type {Boolean}
  3544. * @readonly
  3545. * @default true
  3546. */
  3547. this.isMathNode = true;
  3548. }
  3549. /**
  3550. * The input type is inferred from the node types of the input nodes.
  3551. *
  3552. * @param {NodeBuilder} builder - The current node builder.
  3553. * @return {String} The input type.
  3554. */
  3555. getInputType( builder ) {
  3556. const aType = this.aNode.getNodeType( builder );
  3557. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3558. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3559. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3560. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3561. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3562. if ( aLen > bLen && aLen > cLen ) {
  3563. return aType;
  3564. } else if ( bLen > cLen ) {
  3565. return bType;
  3566. } else if ( cLen > aLen ) {
  3567. return cType;
  3568. }
  3569. return aType;
  3570. }
  3571. /**
  3572. * The selected method as well as the input type determine the node type of this node.
  3573. *
  3574. * @param {NodeBuilder} builder - The current node builder.
  3575. * @return {String} The node type.
  3576. */
  3577. getNodeType( builder ) {
  3578. const method = this.method;
  3579. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3580. return 'float';
  3581. } else if ( method === MathNode.CROSS ) {
  3582. return 'vec3';
  3583. } else if ( method === MathNode.ALL ) {
  3584. return 'bool';
  3585. } else if ( method === MathNode.EQUALS ) {
  3586. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3587. } else if ( method === MathNode.MOD ) {
  3588. return this.aNode.getNodeType( builder );
  3589. } else {
  3590. return this.getInputType( builder );
  3591. }
  3592. }
  3593. generate( builder, output ) {
  3594. let method = this.method;
  3595. const type = this.getNodeType( builder );
  3596. const inputType = this.getInputType( builder );
  3597. const a = this.aNode;
  3598. const b = this.bNode;
  3599. const c = this.cNode;
  3600. const coordinateSystem = builder.renderer.coordinateSystem;
  3601. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3602. // dir can be either a direction vector or a normal vector
  3603. // upper-left 3x3 of matrix is assumed to be orthogonal
  3604. let tA = a;
  3605. let tB = b;
  3606. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3607. tB = vec4( vec3( tB ), 0.0 );
  3608. } else {
  3609. tA = vec4( vec3( tA ), 0.0 );
  3610. }
  3611. const mulNode = mul( tA, tB ).xyz;
  3612. return normalize( mulNode ).build( builder, output );
  3613. } else if ( method === MathNode.NEGATE ) {
  3614. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3615. } else if ( method === MathNode.ONE_MINUS ) {
  3616. return sub( 1.0, a ).build( builder, output );
  3617. } else if ( method === MathNode.RECIPROCAL ) {
  3618. return div( 1.0, a ).build( builder, output );
  3619. } else if ( method === MathNode.DIFFERENCE ) {
  3620. return abs( sub( a, b ) ).build( builder, output );
  3621. } else {
  3622. const params = [];
  3623. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3624. params.push(
  3625. a.build( builder, type ),
  3626. b.build( builder, type )
  3627. );
  3628. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3629. params.push(
  3630. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3631. b.build( builder, inputType )
  3632. );
  3633. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3634. params.push(
  3635. a.build( builder, inputType ),
  3636. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3637. );
  3638. } else if ( method === MathNode.REFRACT ) {
  3639. params.push(
  3640. a.build( builder, inputType ),
  3641. b.build( builder, inputType ),
  3642. c.build( builder, 'float' )
  3643. );
  3644. } else if ( method === MathNode.MIX ) {
  3645. params.push(
  3646. a.build( builder, inputType ),
  3647. b.build( builder, inputType ),
  3648. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3649. );
  3650. } else {
  3651. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3652. method = 'atan2';
  3653. }
  3654. params.push( a.build( builder, inputType ) );
  3655. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3656. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3657. }
  3658. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3659. }
  3660. }
  3661. serialize( data ) {
  3662. super.serialize( data );
  3663. data.method = this.method;
  3664. }
  3665. deserialize( data ) {
  3666. super.deserialize( data );
  3667. this.method = data.method;
  3668. }
  3669. }
  3670. // 1 input
  3671. MathNode.ALL = 'all';
  3672. MathNode.ANY = 'any';
  3673. MathNode.RADIANS = 'radians';
  3674. MathNode.DEGREES = 'degrees';
  3675. MathNode.EXP = 'exp';
  3676. MathNode.EXP2 = 'exp2';
  3677. MathNode.LOG = 'log';
  3678. MathNode.LOG2 = 'log2';
  3679. MathNode.SQRT = 'sqrt';
  3680. MathNode.INVERSE_SQRT = 'inversesqrt';
  3681. MathNode.FLOOR = 'floor';
  3682. MathNode.CEIL = 'ceil';
  3683. MathNode.NORMALIZE = 'normalize';
  3684. MathNode.FRACT = 'fract';
  3685. MathNode.SIN = 'sin';
  3686. MathNode.COS = 'cos';
  3687. MathNode.TAN = 'tan';
  3688. MathNode.ASIN = 'asin';
  3689. MathNode.ACOS = 'acos';
  3690. MathNode.ATAN = 'atan';
  3691. MathNode.ABS = 'abs';
  3692. MathNode.SIGN = 'sign';
  3693. MathNode.LENGTH = 'length';
  3694. MathNode.NEGATE = 'negate';
  3695. MathNode.ONE_MINUS = 'oneMinus';
  3696. MathNode.DFDX = 'dFdx';
  3697. MathNode.DFDY = 'dFdy';
  3698. MathNode.ROUND = 'round';
  3699. MathNode.RECIPROCAL = 'reciprocal';
  3700. MathNode.TRUNC = 'trunc';
  3701. MathNode.FWIDTH = 'fwidth';
  3702. MathNode.TRANSPOSE = 'transpose';
  3703. // 2 inputs
  3704. MathNode.BITCAST = 'bitcast';
  3705. MathNode.EQUALS = 'equals';
  3706. MathNode.MIN = 'min';
  3707. MathNode.MAX = 'max';
  3708. MathNode.MOD = 'mod';
  3709. MathNode.STEP = 'step';
  3710. MathNode.REFLECT = 'reflect';
  3711. MathNode.DISTANCE = 'distance';
  3712. MathNode.DIFFERENCE = 'difference';
  3713. MathNode.DOT = 'dot';
  3714. MathNode.CROSS = 'cross';
  3715. MathNode.POW = 'pow';
  3716. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3717. // 3 inputs
  3718. MathNode.MIX = 'mix';
  3719. MathNode.CLAMP = 'clamp';
  3720. MathNode.REFRACT = 'refract';
  3721. MathNode.SMOOTHSTEP = 'smoothstep';
  3722. MathNode.FACEFORWARD = 'faceforward';
  3723. // 1 inputs
  3724. /**
  3725. * A small value used to handle floating-point precision errors.
  3726. *
  3727. * @type {Node<float>}
  3728. */
  3729. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3730. /**
  3731. * Represents infinity.
  3732. *
  3733. * @type {Node<float>}
  3734. */
  3735. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3736. /**
  3737. * Represents PI.
  3738. *
  3739. * @type {Node<float>}
  3740. */
  3741. const PI = /*@__PURE__*/ float( Math.PI );
  3742. /**
  3743. * Represents PI * 2.
  3744. *
  3745. * @type {Node<float>}
  3746. */
  3747. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3748. /**
  3749. * Returns `true` if all components of `x` are `true`.
  3750. *
  3751. * @function
  3752. * @param {Node | Number} x - The parameter.
  3753. * @returns {Node<bool>}
  3754. */
  3755. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3756. /**
  3757. * Returns `true` if any components of `x` are `true`.
  3758. *
  3759. * @function
  3760. * @param {Node | Number} x - The parameter.
  3761. * @returns {Node<bool>}
  3762. */
  3763. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3764. /**
  3765. * Converts a quantity in degrees to radians.
  3766. *
  3767. * @function
  3768. * @param {Node | Number} x - The input in degrees.
  3769. * @returns {Node}
  3770. */
  3771. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3772. /**
  3773. * Convert a quantity in radians to degrees.
  3774. *
  3775. * @function
  3776. * @param {Node | Number} x - The input in radians.
  3777. * @returns {Node}
  3778. */
  3779. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3780. /**
  3781. * Returns the natural exponentiation of the parameter.
  3782. *
  3783. * @function
  3784. * @param {Node | Number} x - The parameter.
  3785. * @returns {Node}
  3786. */
  3787. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3788. /**
  3789. * Returns 2 raised to the power of the parameter.
  3790. *
  3791. * @function
  3792. * @param {Node | Number} x - The parameter.
  3793. * @returns {Node}
  3794. */
  3795. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3796. /**
  3797. * Returns the natural logarithm of the parameter.
  3798. *
  3799. * @function
  3800. * @param {Node | Number} x - The parameter.
  3801. * @returns {Node}
  3802. */
  3803. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3804. /**
  3805. * Returns the base 2 logarithm of the parameter.
  3806. *
  3807. * @function
  3808. * @param {Node | Number} x - The parameter.
  3809. * @returns {Node}
  3810. */
  3811. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3812. /**
  3813. * Returns the square root of the parameter.
  3814. *
  3815. * @function
  3816. * @param {Node | Number} x - The parameter.
  3817. * @returns {Node}
  3818. */
  3819. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3820. /**
  3821. * Returns the inverse of the square root of the parameter.
  3822. *
  3823. * @function
  3824. * @param {Node | Number} x - The parameter.
  3825. * @returns {Node}
  3826. */
  3827. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3828. /**
  3829. * Finds the nearest integer less than or equal to the parameter.
  3830. *
  3831. * @function
  3832. * @param {Node | Number} x - The parameter.
  3833. * @returns {Node}
  3834. */
  3835. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3836. /**
  3837. * Finds the nearest integer that is greater than or equal to the parameter.
  3838. *
  3839. * @function
  3840. * @param {Node | Number} x - The parameter.
  3841. * @returns {Node}
  3842. */
  3843. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3844. /**
  3845. * Calculates the unit vector in the same direction as the original vector.
  3846. *
  3847. * @function
  3848. * @param {Node} x - The input vector.
  3849. * @returns {Node}
  3850. */
  3851. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3852. /**
  3853. * Computes the fractional part of the parameter.
  3854. *
  3855. * @function
  3856. * @param {Node | Number} x - The parameter.
  3857. * @returns {Node}
  3858. */
  3859. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3860. /**
  3861. * Returns the sine of the parameter.
  3862. *
  3863. * @function
  3864. * @param {Node | Number} x - The parameter.
  3865. * @returns {Node}
  3866. */
  3867. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3868. /**
  3869. * Returns the cosine of the parameter.
  3870. *
  3871. * @function
  3872. * @param {Node | Number} x - The parameter.
  3873. * @returns {Node}
  3874. */
  3875. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3876. /**
  3877. * Returns the tangent of the parameter.
  3878. *
  3879. * @function
  3880. * @param {Node | Number} x - The parameter.
  3881. * @returns {Node}
  3882. */
  3883. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3884. /**
  3885. * Returns the arcsine of the parameter.
  3886. *
  3887. * @function
  3888. * @param {Node | Number} x - The parameter.
  3889. * @returns {Node}
  3890. */
  3891. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3892. /**
  3893. * Returns the arccosine of the parameter.
  3894. *
  3895. * @function
  3896. * @param {Node | Number} x - The parameter.
  3897. * @returns {Node}
  3898. */
  3899. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3900. /**
  3901. * Returns the arc-tangent of the parameter.
  3902. * If two parameters are provided, the result is `atan2(y/x)`.
  3903. *
  3904. * @function
  3905. * @param {Node | Number} y - The y parameter.
  3906. * @param {(Node | Number)?} x - The x parameter.
  3907. * @returns {Node}
  3908. */
  3909. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3910. /**
  3911. * Returns the absolute value of the parameter.
  3912. *
  3913. * @function
  3914. * @param {Node | Number} x - The parameter.
  3915. * @returns {Node}
  3916. */
  3917. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3918. /**
  3919. * Extracts the sign of the parameter.
  3920. *
  3921. * @function
  3922. * @param {Node | Number} x - The parameter.
  3923. * @returns {Node}
  3924. */
  3925. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3926. /**
  3927. * Calculates the length of a vector.
  3928. *
  3929. * @function
  3930. * @param {Node} x - The parameter.
  3931. * @returns {Node<float>}
  3932. */
  3933. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3934. /**
  3935. * Negates the value of the parameter (-x).
  3936. *
  3937. * @function
  3938. * @param {Node | Number} x - The parameter.
  3939. * @returns {Node}
  3940. */
  3941. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3942. /**
  3943. * Return `1` minus the parameter.
  3944. *
  3945. * @function
  3946. * @param {Node | Number} x - The parameter.
  3947. * @returns {Node}
  3948. */
  3949. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3950. /**
  3951. * Returns the partial derivative of the parameter with respect to x.
  3952. *
  3953. * @function
  3954. * @param {Node | Number} x - The parameter.
  3955. * @returns {Node}
  3956. */
  3957. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3958. /**
  3959. * Returns the partial derivative of the parameter with respect to y.
  3960. *
  3961. * @function
  3962. * @param {Node | Number} x - The parameter.
  3963. * @returns {Node}
  3964. */
  3965. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3966. /**
  3967. * Rounds the parameter to the nearest integer.
  3968. *
  3969. * @function
  3970. * @param {Node | Number} x - The parameter.
  3971. * @returns {Node}
  3972. */
  3973. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3974. /**
  3975. * Returns the reciprocal of the parameter `(1/x)`.
  3976. *
  3977. * @function
  3978. * @param {Node | Number} x - The parameter.
  3979. * @returns {Node}
  3980. */
  3981. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3982. /**
  3983. * Truncates the parameter, removing the fractional part.
  3984. *
  3985. * @function
  3986. * @param {Node | Number} x - The parameter.
  3987. * @returns {Node}
  3988. */
  3989. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3990. /**
  3991. * Returns the sum of the absolute derivatives in x and y.
  3992. *
  3993. * @function
  3994. * @param {Node | Number} x - The parameter.
  3995. * @returns {Node}
  3996. */
  3997. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3998. /**
  3999. * Returns the transpose of a matrix.
  4000. *
  4001. * @function
  4002. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4003. * @returns {Node}
  4004. */
  4005. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  4006. // 2 inputs
  4007. /**
  4008. * Reinterpret the bit representation of a value in one type as a value in another type.
  4009. *
  4010. * @function
  4011. * @param {Node | Number} x - The parameter.
  4012. * @param {String} y - The new type.
  4013. * @returns {Node}
  4014. */
  4015. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  4016. /**
  4017. * Returns `true` if `x` equals `y`.
  4018. *
  4019. * @function
  4020. * @param {Node | Number} x - The first parameter.
  4021. * @param {Node | Number} y - The second parameter.
  4022. * @returns {Node<bool>}
  4023. */
  4024. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  4025. /**
  4026. * Returns the lesser of two values.
  4027. *
  4028. * @function
  4029. * @param {Node | Number} x - The y parameter.
  4030. * @param {Node | Number} y - The x parameter.
  4031. * @returns {Node}
  4032. */
  4033. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  4034. /**
  4035. * Returns the greater of two values.
  4036. *
  4037. * @function
  4038. * @param {Node | Number} x - The y parameter.
  4039. * @param {Node | Number} y - The x parameter.
  4040. * @returns {Node}
  4041. */
  4042. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  4043. /**
  4044. * Computes the remainder of dividing the first node by the second one.
  4045. *
  4046. * @function
  4047. * @param {Node | Number} x - The y parameter.
  4048. * @param {Node | Number} y - The x parameter.
  4049. * @returns {Node}
  4050. */
  4051. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  4052. /**
  4053. * Generate a step function by comparing two values.
  4054. *
  4055. * @function
  4056. * @param {Node | Number} x - The y parameter.
  4057. * @param {Node | Number} y - The x parameter.
  4058. * @returns {Node}
  4059. */
  4060. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  4061. /**
  4062. * Calculates the reflection direction for an incident vector.
  4063. *
  4064. * @function
  4065. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4066. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4067. * @returns {Node<vec2|vec3|vec4>}
  4068. */
  4069. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  4070. /**
  4071. * Calculates the distance between two points.
  4072. *
  4073. * @function
  4074. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4075. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4076. * @returns {Node<float>}
  4077. */
  4078. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  4079. /**
  4080. * Calculates the absolute difference between two values.
  4081. *
  4082. * @function
  4083. * @param {Node | Number} x - The first parameter.
  4084. * @param {Node | Number} y - The second parameter.
  4085. * @returns {Node}
  4086. */
  4087. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  4088. /**
  4089. * Calculates the dot product of two vectors.
  4090. *
  4091. * @function
  4092. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4093. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4094. * @returns {Node<float>}
  4095. */
  4096. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  4097. /**
  4098. * Calculates the cross product of two vectors.
  4099. *
  4100. * @function
  4101. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4102. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4103. * @returns {Node<vec2|vec3|vec4>}
  4104. */
  4105. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  4106. /**
  4107. * Return the value of the first parameter raised to the power of the second one.
  4108. *
  4109. * @function
  4110. * @param {Node | Number} x - The first parameter.
  4111. * @param {Node | Number} y - The second parameter.
  4112. * @returns {Node}
  4113. */
  4114. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  4115. /**
  4116. * Returns the square of the parameter.
  4117. *
  4118. * @function
  4119. * @param {Node | Number} x - The first parameter.
  4120. * @returns {Node}
  4121. */
  4122. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4123. /**
  4124. * Returns the cube of the parameter.
  4125. *
  4126. * @function
  4127. * @param {Node | Number} x - The first parameter.
  4128. * @returns {Node}
  4129. */
  4130. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4131. /**
  4132. * Returns the fourth power of the parameter.
  4133. *
  4134. * @function
  4135. * @param {Node | Number} x - The first parameter.
  4136. * @returns {Node}
  4137. */
  4138. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4139. /**
  4140. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4141. *
  4142. * @function
  4143. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4144. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4145. * @returns {Node}
  4146. */
  4147. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4148. /**
  4149. * Returns the cube root of a number.
  4150. *
  4151. * @function
  4152. * @param {Node | Number} a - The first parameter.
  4153. * @returns {Node}
  4154. */
  4155. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4156. /**
  4157. * Calculate the squared length of a vector.
  4158. *
  4159. * @function
  4160. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4161. * @returns {Node<float>}
  4162. */
  4163. const lengthSq = ( a ) => dot( a, a );
  4164. /**
  4165. * Linearly interpolates between two values.
  4166. *
  4167. * @function
  4168. * @param {Node | Number} a - The first parameter.
  4169. * @param {Node | Number} b - The second parameter.
  4170. * @param {Node | Number} t - The interpolation value.
  4171. * @returns {Node}
  4172. */
  4173. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4174. /**
  4175. * Constrains a value to lie between two further values.
  4176. *
  4177. * @function
  4178. * @param {Node | Number} value - The value to constrain.
  4179. * @param {Node | Number} [low=0] - The lower bound.
  4180. * @param {Node | Number} [high=1] - The upper bound.
  4181. * @returns {Node}
  4182. */
  4183. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4184. /**
  4185. * Constrains a value between `0` and `1`.
  4186. *
  4187. * @function
  4188. * @param {Node | Number} value - The value to constrain.
  4189. * @returns {Node}
  4190. */
  4191. const saturate = ( value ) => clamp( value );
  4192. /**
  4193. * Calculates the refraction direction for an incident vector.
  4194. *
  4195. * @function
  4196. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4197. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4198. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4199. * @returns {Node<vec2|vec3|vec4>}
  4200. */
  4201. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4202. /**
  4203. * Performs a Hermite interpolation between two values.
  4204. *
  4205. * @function
  4206. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4207. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4208. * @param {Node | Number} x - The source value for interpolation.
  4209. * @returns {Node}
  4210. */
  4211. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4212. /**
  4213. * Returns a vector pointing in the same direction as another.
  4214. *
  4215. * @function
  4216. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4217. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4218. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4219. * @returns {Node<vec2|vec3|vec4>}
  4220. */
  4221. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4222. /**
  4223. * Returns a random value for the given uv.
  4224. *
  4225. * @function
  4226. * @param {Node<vec2>} uv - The uv node.
  4227. * @returns {Node<float>}
  4228. */
  4229. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4230. const a = 12.9898, b = 78.233, c = 43758.5453;
  4231. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4232. return fract( sin( sn ).mul( c ) );
  4233. } );
  4234. /**
  4235. * Alias for `mix()` with a different parameter order.
  4236. *
  4237. * @function
  4238. * @param {Node | Number} t - The interpolation value.
  4239. * @param {Node | Number} e1 - The first parameter.
  4240. * @param {Node | Number} e2 - The second parameter.
  4241. * @returns {Node}
  4242. */
  4243. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4244. /**
  4245. * Alias for `smoothstep()` with a different parameter order.
  4246. *
  4247. * @function
  4248. * @param {Node | Number} x - The source value for interpolation.
  4249. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4250. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4251. * @returns {Node}
  4252. */
  4253. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4254. /**
  4255. * Returns the arc-tangent of the quotient of its parameters.
  4256. *
  4257. * @function
  4258. * @deprecated since r172. Use {@link atan} instead.
  4259. *
  4260. * @param {Node | Number} y - The y parameter.
  4261. * @param {Node | Number} x - The x parameter.
  4262. * @returns {Node}
  4263. */
  4264. const atan2 = ( y, x ) => { // @deprecated, r172
  4265. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4266. return atan( y, x );
  4267. };
  4268. // GLSL alias function
  4269. const faceforward = faceForward;
  4270. const inversesqrt = inverseSqrt;
  4271. // Method chaining
  4272. addMethodChaining( 'all', all );
  4273. addMethodChaining( 'any', any );
  4274. addMethodChaining( 'equals', equals );
  4275. addMethodChaining( 'radians', radians );
  4276. addMethodChaining( 'degrees', degrees );
  4277. addMethodChaining( 'exp', exp );
  4278. addMethodChaining( 'exp2', exp2 );
  4279. addMethodChaining( 'log', log );
  4280. addMethodChaining( 'log2', log2 );
  4281. addMethodChaining( 'sqrt', sqrt );
  4282. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4283. addMethodChaining( 'floor', floor );
  4284. addMethodChaining( 'ceil', ceil );
  4285. addMethodChaining( 'normalize', normalize );
  4286. addMethodChaining( 'fract', fract );
  4287. addMethodChaining( 'sin', sin );
  4288. addMethodChaining( 'cos', cos );
  4289. addMethodChaining( 'tan', tan );
  4290. addMethodChaining( 'asin', asin );
  4291. addMethodChaining( 'acos', acos );
  4292. addMethodChaining( 'atan', atan );
  4293. addMethodChaining( 'abs', abs );
  4294. addMethodChaining( 'sign', sign );
  4295. addMethodChaining( 'length', length );
  4296. addMethodChaining( 'lengthSq', lengthSq );
  4297. addMethodChaining( 'negate', negate );
  4298. addMethodChaining( 'oneMinus', oneMinus );
  4299. addMethodChaining( 'dFdx', dFdx );
  4300. addMethodChaining( 'dFdy', dFdy );
  4301. addMethodChaining( 'round', round );
  4302. addMethodChaining( 'reciprocal', reciprocal );
  4303. addMethodChaining( 'trunc', trunc );
  4304. addMethodChaining( 'fwidth', fwidth );
  4305. addMethodChaining( 'atan2', atan2 );
  4306. addMethodChaining( 'min', min$1 );
  4307. addMethodChaining( 'max', max$1 );
  4308. addMethodChaining( 'mod', mod );
  4309. addMethodChaining( 'step', step );
  4310. addMethodChaining( 'reflect', reflect );
  4311. addMethodChaining( 'distance', distance );
  4312. addMethodChaining( 'dot', dot );
  4313. addMethodChaining( 'cross', cross );
  4314. addMethodChaining( 'pow', pow );
  4315. addMethodChaining( 'pow2', pow2 );
  4316. addMethodChaining( 'pow3', pow3 );
  4317. addMethodChaining( 'pow4', pow4 );
  4318. addMethodChaining( 'transformDirection', transformDirection );
  4319. addMethodChaining( 'mix', mixElement );
  4320. addMethodChaining( 'clamp', clamp );
  4321. addMethodChaining( 'refract', refract );
  4322. addMethodChaining( 'smoothstep', smoothstepElement );
  4323. addMethodChaining( 'faceForward', faceForward );
  4324. addMethodChaining( 'difference', difference );
  4325. addMethodChaining( 'saturate', saturate );
  4326. addMethodChaining( 'cbrt', cbrt );
  4327. addMethodChaining( 'transpose', transpose );
  4328. addMethodChaining( 'rand', rand );
  4329. /** @module ConditionalNode **/
  4330. /**
  4331. * Represents a logical `if/else` statement. Can be used as an alternative
  4332. * to the `If()`/`Else()` syntax.
  4333. *
  4334. * The corresponding TSL `select()` looks like so:
  4335. * ```js
  4336. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4337. * ```
  4338. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4339. * determine the outcome of the entire statement.
  4340. *
  4341. * @augments Node
  4342. */
  4343. class ConditionalNode extends Node {
  4344. static get type() {
  4345. return 'ConditionalNode';
  4346. }
  4347. /**
  4348. * Constructs a new conditional node.
  4349. *
  4350. * @param {Node} condNode - The node that defines the condition.
  4351. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4352. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4353. */
  4354. constructor( condNode, ifNode, elseNode = null ) {
  4355. super();
  4356. /**
  4357. * The node that defines the condition.
  4358. *
  4359. * @type {Node}
  4360. */
  4361. this.condNode = condNode;
  4362. /**
  4363. * The node that is evaluate when the condition ends up `true`.
  4364. *
  4365. * @type {Node}
  4366. */
  4367. this.ifNode = ifNode;
  4368. /**
  4369. * The node that is evaluate when the condition ends up `false`.
  4370. *
  4371. * @type {Node?}
  4372. * @default null
  4373. */
  4374. this.elseNode = elseNode;
  4375. }
  4376. /**
  4377. * This method is overwritten since the node type is inferred from the if/else
  4378. * nodes.
  4379. *
  4380. * @param {NodeBuilder} builder - The current node builder.
  4381. * @return {String} The node type.
  4382. */
  4383. getNodeType( builder ) {
  4384. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4385. if ( ifNode === undefined ) {
  4386. // fallback setup
  4387. this.setup( builder );
  4388. return this.getNodeType( builder );
  4389. }
  4390. const ifType = ifNode.getNodeType( builder );
  4391. if ( elseNode !== null ) {
  4392. const elseType = elseNode.getNodeType( builder );
  4393. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4394. return elseType;
  4395. }
  4396. }
  4397. return ifType;
  4398. }
  4399. setup( builder ) {
  4400. const condNode = this.condNode.cache();
  4401. const ifNode = this.ifNode.cache();
  4402. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4403. //
  4404. const currentNodeBlock = builder.context.nodeBlock;
  4405. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4406. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4407. //
  4408. const properties = builder.getNodeProperties( this );
  4409. properties.condNode = condNode;
  4410. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4411. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4412. }
  4413. generate( builder, output ) {
  4414. const type = this.getNodeType( builder );
  4415. const nodeData = builder.getDataFromNode( this );
  4416. if ( nodeData.nodeProperty !== undefined ) {
  4417. return nodeData.nodeProperty;
  4418. }
  4419. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4420. const needsOutput = output !== 'void';
  4421. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4422. nodeData.nodeProperty = nodeProperty;
  4423. const nodeSnippet = condNode.build( builder, 'bool' );
  4424. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4425. let ifSnippet = ifNode.build( builder, type );
  4426. if ( ifSnippet ) {
  4427. if ( needsOutput ) {
  4428. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4429. } else {
  4430. ifSnippet = 'return ' + ifSnippet + ';';
  4431. }
  4432. }
  4433. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4434. if ( elseNode !== null ) {
  4435. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4436. let elseSnippet = elseNode.build( builder, type );
  4437. if ( elseSnippet ) {
  4438. if ( needsOutput ) {
  4439. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4440. } else {
  4441. elseSnippet = 'return ' + elseSnippet + ';';
  4442. }
  4443. }
  4444. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4445. } else {
  4446. builder.addFlowCode( '\n\n' );
  4447. }
  4448. return builder.format( nodeProperty, type, output );
  4449. }
  4450. }
  4451. /**
  4452. * TSL function for creating a conditional node.
  4453. *
  4454. * @function
  4455. * @param {Node} condNode - The node that defines the condition.
  4456. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4457. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4458. * @returns {ConditionalNode}
  4459. */
  4460. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4461. addMethodChaining( 'select', select );
  4462. // Deprecated
  4463. /**
  4464. * @function
  4465. * @deprecated since r168. Use {@link select} instead.
  4466. *
  4467. * @param {...any} params
  4468. * @returns {ConditionalNode}
  4469. */
  4470. const cond = ( ...params ) => { // @deprecated, r168
  4471. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4472. return select( ...params );
  4473. };
  4474. addMethodChaining( 'cond', cond );
  4475. /** @module ContextNode **/
  4476. /**
  4477. * This node can be used as a context management component for another node.
  4478. * {@link NodeBuilder} performs its node building process in a specific context and
  4479. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4480. *
  4481. * ```js
  4482. *node.context( { getUV: () => customCoord } );
  4483. *```
  4484. * @augments Node
  4485. */
  4486. class ContextNode extends Node {
  4487. static get type() {
  4488. return 'ContextNode';
  4489. }
  4490. /**
  4491. * Constructs a new context node.
  4492. *
  4493. * @param {Node} node - The node whose context should be modified.
  4494. * @param {Object} [value={}] - The modified context data.
  4495. */
  4496. constructor( node, value = {} ) {
  4497. super();
  4498. /**
  4499. * This flag can be used for type testing.
  4500. *
  4501. * @type {Boolean}
  4502. * @readonly
  4503. * @default true
  4504. */
  4505. this.isContextNode = true;
  4506. /**
  4507. * The node whose context should be modified.
  4508. *
  4509. * @type {Node}
  4510. */
  4511. this.node = node;
  4512. /**
  4513. * The modified context data.
  4514. *
  4515. * @type {Object}
  4516. * @default {}
  4517. */
  4518. this.value = value;
  4519. }
  4520. /**
  4521. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4522. *
  4523. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4524. */
  4525. getScope() {
  4526. return this.node.getScope();
  4527. }
  4528. /**
  4529. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4530. *
  4531. * @param {NodeBuilder} builder - The current node builder.
  4532. * @return {String} The node type.
  4533. */
  4534. getNodeType( builder ) {
  4535. return this.node.getNodeType( builder );
  4536. }
  4537. analyze( builder ) {
  4538. this.node.build( builder );
  4539. }
  4540. setup( builder ) {
  4541. const previousContext = builder.getContext();
  4542. builder.setContext( { ...builder.context, ...this.value } );
  4543. const node = this.node.build( builder );
  4544. builder.setContext( previousContext );
  4545. return node;
  4546. }
  4547. generate( builder, output ) {
  4548. const previousContext = builder.getContext();
  4549. builder.setContext( { ...builder.context, ...this.value } );
  4550. const snippet = this.node.build( builder, output );
  4551. builder.setContext( previousContext );
  4552. return snippet;
  4553. }
  4554. }
  4555. /**
  4556. * TSL function for creating a context node.
  4557. *
  4558. * @function
  4559. * @param {Node} node - The node whose context should be modified.
  4560. * @param {Object} [value={}] - The modified context data.
  4561. * @returns {ContextNode}
  4562. */
  4563. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4564. /**
  4565. * TSL function for defining a label context value for a given node.
  4566. *
  4567. * @function
  4568. * @param {Node} node - The node whose context should be modified.
  4569. * @param {String} name - The name/label to set.
  4570. * @returns {ContextNode}
  4571. */
  4572. const label = ( node, name ) => context( node, { label: name } );
  4573. addMethodChaining( 'context', context );
  4574. addMethodChaining( 'label', label );
  4575. /** @module VarNode **/
  4576. /**
  4577. * Class for representing shader variables as nodes. Variables are created from
  4578. * existing nodes like the following:
  4579. *
  4580. * ```js
  4581. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4582. * ```
  4583. *
  4584. * @augments Node
  4585. */
  4586. class VarNode extends Node {
  4587. static get type() {
  4588. return 'VarNode';
  4589. }
  4590. /**
  4591. * Constructs a new variable node.
  4592. *
  4593. * @param {Node} node - The node for which a variable should be created.
  4594. * @param {String?} name - The name of the variable in the shader.
  4595. * @param {Boolean?} readOnly - The read-only flag.
  4596. */
  4597. constructor( node, name = null, readOnly = false ) {
  4598. super();
  4599. /**
  4600. * The node for which a variable should be created.
  4601. *
  4602. * @type {Node}
  4603. */
  4604. this.node = node;
  4605. /**
  4606. * The name of the variable in the shader. If no name is defined,
  4607. * the node system auto-generates one.
  4608. *
  4609. * @type {String?}
  4610. * @default null
  4611. */
  4612. this.name = name;
  4613. /**
  4614. * `VarNode` sets this property to `true` by default.
  4615. *
  4616. * @type {Boolean}
  4617. * @default true
  4618. */
  4619. this.global = true;
  4620. /**
  4621. * This flag can be used for type testing.
  4622. *
  4623. * @type {Boolean}
  4624. * @readonly
  4625. * @default true
  4626. */
  4627. this.isVarNode = true;
  4628. /**
  4629. *
  4630. * The read-only flag.
  4631. *
  4632. * @type {Boolean}
  4633. * @default false
  4634. */
  4635. this.readOnly = readOnly;
  4636. }
  4637. getHash( builder ) {
  4638. return this.name || super.getHash( builder );
  4639. }
  4640. getElementType( builder ) {
  4641. return this.node.getElementType( builder );
  4642. }
  4643. getNodeType( builder ) {
  4644. return this.node.getNodeType( builder );
  4645. }
  4646. generate( builder ) {
  4647. const { node, name, readOnly } = this;
  4648. const { renderer } = builder;
  4649. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4650. let isDeterministic = false;
  4651. let shouldTreatAsReadOnly = false;
  4652. if ( readOnly ) {
  4653. isDeterministic = builder.isDeterministic( node );
  4654. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4655. }
  4656. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4657. const snippet = node.build( builder, vectorType );
  4658. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4659. const propertyName = builder.getPropertyName( nodeVar );
  4660. let declarationPrefix = propertyName;
  4661. if ( shouldTreatAsReadOnly ) {
  4662. if ( isWebGPUBackend ) {
  4663. declarationPrefix = isDeterministic
  4664. ? `const ${ propertyName }`
  4665. : `let ${ propertyName }`;
  4666. } else {
  4667. const count = builder.getArrayCount( node );
  4668. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  4669. }
  4670. }
  4671. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4672. return propertyName;
  4673. }
  4674. }
  4675. /**
  4676. * TSL function for creating a var node.
  4677. *
  4678. * @function
  4679. * @param {Node} node - The node for which a variable should be created.
  4680. * @param {String?} name - The name of the variable in the shader.
  4681. * @returns {VarNode}
  4682. */
  4683. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4684. /**
  4685. * TSL function for creating a var node.
  4686. *
  4687. * @function
  4688. * @param {Node} node - The node for which a variable should be created.
  4689. * @param {String?} name - The name of the variable in the shader.
  4690. * @returns {VarNode}
  4691. */
  4692. const Var = ( node, name = null ) => createVar( node, name ).append();
  4693. /**
  4694. * TSL function for creating a const node.
  4695. *
  4696. * @function
  4697. * @param {Node} node - The node for which a constant should be created.
  4698. * @param {String?} name - The name of the constant in the shader.
  4699. * @returns {VarNode}
  4700. */
  4701. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4702. // Method chaining
  4703. addMethodChaining( 'toVar', Var );
  4704. addMethodChaining( 'toConst', Const );
  4705. // Deprecated
  4706. /**
  4707. * @function
  4708. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4709. *
  4710. * @param {Any} node
  4711. * @returns {VarNode}
  4712. */
  4713. const temp = ( node ) => { // @deprecated, r170
  4714. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4715. return createVar( node );
  4716. };
  4717. addMethodChaining( 'temp', temp );
  4718. /** @module VaryingNode **/
  4719. /**
  4720. * Class for representing shader varyings as nodes. Varyings are create from
  4721. * existing nodes like the following:
  4722. *
  4723. * ```js
  4724. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4725. * ```
  4726. *
  4727. * @augments Node
  4728. */
  4729. class VaryingNode extends Node {
  4730. static get type() {
  4731. return 'VaryingNode';
  4732. }
  4733. /**
  4734. * Constructs a new varying node.
  4735. *
  4736. * @param {Node} node - The node for which a varying should be created.
  4737. * @param {String?} name - The name of the varying in the shader.
  4738. */
  4739. constructor( node, name = null ) {
  4740. super();
  4741. /**
  4742. * The node for which a varying should be created.
  4743. *
  4744. * @type {Node}
  4745. */
  4746. this.node = node;
  4747. /**
  4748. * The name of the varying in the shader. If no name is defined,
  4749. * the node system auto-generates one.
  4750. *
  4751. * @type {String?}
  4752. * @default null
  4753. */
  4754. this.name = name;
  4755. /**
  4756. * This flag can be used for type testing.
  4757. *
  4758. * @type {Boolean}
  4759. * @readonly
  4760. * @default true
  4761. */
  4762. this.isVaryingNode = true;
  4763. }
  4764. /**
  4765. * The method is overwritten so it always returns `true`.
  4766. *
  4767. * @param {NodeBuilder} builder - The current node builder.
  4768. * @return {Boolean} Whether this node is global or not.
  4769. */
  4770. isGlobal( /*builder*/ ) {
  4771. return true;
  4772. }
  4773. getHash( builder ) {
  4774. return this.name || super.getHash( builder );
  4775. }
  4776. getNodeType( builder ) {
  4777. // VaryingNode is auto type
  4778. return this.node.getNodeType( builder );
  4779. }
  4780. /**
  4781. * This method performs the setup of a varying node with the current node builder.
  4782. *
  4783. * @param {NodeBuilder} builder - The current node builder.
  4784. * @return {NodeVarying} The node varying from the node builder.
  4785. */
  4786. setupVarying( builder ) {
  4787. const properties = builder.getNodeProperties( this );
  4788. let varying = properties.varying;
  4789. if ( varying === undefined ) {
  4790. const name = this.name;
  4791. const type = this.getNodeType( builder );
  4792. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4793. properties.node = this.node;
  4794. }
  4795. // this property can be used to check if the varying can be optimized for a variable
  4796. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4797. return varying;
  4798. }
  4799. setup( builder ) {
  4800. this.setupVarying( builder );
  4801. }
  4802. analyze( builder ) {
  4803. this.setupVarying( builder );
  4804. return this.node.analyze( builder );
  4805. }
  4806. generate( builder ) {
  4807. const properties = builder.getNodeProperties( this );
  4808. const varying = this.setupVarying( builder );
  4809. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4810. if ( properties.propertyName === undefined || needsReassign ) {
  4811. const type = this.getNodeType( builder );
  4812. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4813. // force node run in vertex stage
  4814. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4815. properties.propertyName = propertyName;
  4816. if ( needsReassign ) {
  4817. // once reassign varying in fragment stage
  4818. properties.reassignPosition = false;
  4819. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4820. properties.reassignPosition = true;
  4821. }
  4822. }
  4823. return builder.getPropertyName( varying );
  4824. }
  4825. }
  4826. /**
  4827. * TSL function for creating a varying node.
  4828. *
  4829. * @function
  4830. * @param {Node} node - The node for which a varying should be created.
  4831. * @param {String?} name - The name of the varying in the shader.
  4832. * @returns {VaryingNode}
  4833. */
  4834. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4835. /**
  4836. * Computes a node in the vertex stage.
  4837. *
  4838. * @function
  4839. * @param {Node} node - The node which should be executed in the vertex stage.
  4840. * @returns {VaryingNode}
  4841. */
  4842. const vertexStage = ( node ) => varying( node );
  4843. addMethodChaining( 'toVarying', varying );
  4844. addMethodChaining( 'toVertexStage', vertexStage );
  4845. // Deprecated
  4846. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  4847. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  4848. return varying( ...params );
  4849. } );
  4850. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  4851. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  4852. return varying( ...params );
  4853. } );
  4854. /** @module ColorSpaceFunctions **/
  4855. /**
  4856. * Converts the given color value from sRGB to linear-sRGB color space.
  4857. *
  4858. * @method
  4859. * @param {Node<vec3>} color - The sRGB color.
  4860. * @return {Node<vec3>} The linear-sRGB color.
  4861. */
  4862. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4863. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4864. const b = color.mul( 0.0773993808 );
  4865. const factor = color.lessThanEqual( 0.04045 );
  4866. const rgbResult = mix( a, b, factor );
  4867. return rgbResult;
  4868. } ).setLayout( {
  4869. name: 'sRGBTransferEOTF',
  4870. type: 'vec3',
  4871. inputs: [
  4872. { name: 'color', type: 'vec3' }
  4873. ]
  4874. } );
  4875. /**
  4876. * Converts the given color value from linear-sRGB to sRGB color space.
  4877. *
  4878. * @method
  4879. * @param {Node<vec3>} color - The linear-sRGB color.
  4880. * @return {Node<vec3>} The sRGB color.
  4881. */
  4882. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4883. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4884. const b = color.mul( 12.92 );
  4885. const factor = color.lessThanEqual( 0.0031308 );
  4886. const rgbResult = mix( a, b, factor );
  4887. return rgbResult;
  4888. } ).setLayout( {
  4889. name: 'sRGBTransferOETF',
  4890. type: 'vec3',
  4891. inputs: [
  4892. { name: 'color', type: 'vec3' }
  4893. ]
  4894. } );
  4895. /** @module ColorSpaceNode **/
  4896. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4897. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4898. /**
  4899. * This node represents a color space conversion. Meaning it converts
  4900. * a color value from a source to a target color space.
  4901. *
  4902. * @augments TempNode
  4903. */
  4904. class ColorSpaceNode extends TempNode {
  4905. static get type() {
  4906. return 'ColorSpaceNode';
  4907. }
  4908. /**
  4909. * Constructs a new color space node.
  4910. *
  4911. * @param {Node} colorNode - Represents the color to convert.
  4912. * @param {String} source - The source color space.
  4913. * @param {String} target - The target color space.
  4914. */
  4915. constructor( colorNode, source, target ) {
  4916. super( 'vec4' );
  4917. /**
  4918. * Represents the color to convert.
  4919. *
  4920. * @type {Node}
  4921. */
  4922. this.colorNode = colorNode;
  4923. /**
  4924. * The source color space.
  4925. *
  4926. * @type {String}
  4927. */
  4928. this.source = source;
  4929. /**
  4930. * The target color space.
  4931. *
  4932. * @type {String}
  4933. */
  4934. this.target = target;
  4935. }
  4936. /**
  4937. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4938. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4939. * color management and renderer.
  4940. *
  4941. * @param {NodeBuilder} builder - The current node builder.
  4942. * @param {String} colorSpace - The color space to resolve.
  4943. * @return {String} The resolved color space.
  4944. */
  4945. resolveColorSpace( builder, colorSpace ) {
  4946. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4947. return ColorManagement.workingColorSpace;
  4948. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4949. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4950. }
  4951. return colorSpace;
  4952. }
  4953. setup( builder ) {
  4954. const { colorNode } = this;
  4955. const source = this.resolveColorSpace( builder, this.source );
  4956. const target = this.resolveColorSpace( builder, this.target );
  4957. let outputNode = colorNode;
  4958. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4959. return outputNode;
  4960. }
  4961. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4962. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4963. }
  4964. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4965. outputNode = vec4(
  4966. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4967. outputNode.a
  4968. );
  4969. }
  4970. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4971. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4972. }
  4973. return outputNode;
  4974. }
  4975. }
  4976. /**
  4977. * TSL function for converting a given color node to the current output color space.
  4978. *
  4979. * @function
  4980. * @param {Node} node - Represents the node to convert.
  4981. * @returns {ColorSpaceNode}
  4982. */
  4983. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4984. /**
  4985. * TSL function for converting a given color node to the current working color space.
  4986. *
  4987. * @function
  4988. * @param {Node} node - Represents the node to convert.
  4989. * @returns {ColorSpaceNode}
  4990. */
  4991. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4992. /**
  4993. * TSL function for converting a given color node from the current working color space to the given color space.
  4994. *
  4995. * @function
  4996. * @param {Node} node - Represents the node to convert.
  4997. * @param {String} colorSpace - The target color space.
  4998. * @returns {ColorSpaceNode}
  4999. */
  5000. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5001. /**
  5002. * TSL function for converting a given color node from the given color space to the current working color space.
  5003. *
  5004. * @function
  5005. * @param {Node} node - Represents the node to convert.
  5006. * @param {String} colorSpace - The source color space.
  5007. * @returns {ColorSpaceNode}
  5008. */
  5009. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5010. /**
  5011. * TSL function for converting a given color node from one color space to another one.
  5012. *
  5013. * @function
  5014. * @param {Node} node - Represents the node to convert.
  5015. * @param {String} sourceColorSpace - The source color space.
  5016. * @param {String} targetColorSpace - The target color space.
  5017. * @returns {ColorSpaceNode}
  5018. */
  5019. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5020. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5021. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5022. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5023. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5024. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5025. /** @module ReferenceBaseNode **/
  5026. /**
  5027. * This class is only relevant if the referenced property is array-like.
  5028. * In this case, `ReferenceElementNode` allows to refer to a specific
  5029. * element inside the data structure via an index.
  5030. *
  5031. * @augments ArrayElementNode
  5032. */
  5033. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5034. static get type() {
  5035. return 'ReferenceElementNode';
  5036. }
  5037. /**
  5038. * Constructs a new reference element node.
  5039. *
  5040. * @param {ReferenceBaseNode?} referenceNode - The reference node.
  5041. * @param {Node} indexNode - The index node that defines the element access.
  5042. */
  5043. constructor( referenceNode, indexNode ) {
  5044. super( referenceNode, indexNode );
  5045. /**
  5046. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  5047. * property references to the current node.
  5048. *
  5049. * @type {ReferenceBaseNode?}
  5050. * @default null
  5051. */
  5052. this.referenceNode = referenceNode;
  5053. /**
  5054. * This flag can be used for type testing.
  5055. *
  5056. * @type {Boolean}
  5057. * @readonly
  5058. * @default true
  5059. */
  5060. this.isReferenceElementNode = true;
  5061. }
  5062. /**
  5063. * This method is overwritten since the node type is inferred from
  5064. * the uniform type of the reference node.
  5065. *
  5066. * @return {String} The node type.
  5067. */
  5068. getNodeType() {
  5069. return this.referenceNode.uniformType;
  5070. }
  5071. generate( builder ) {
  5072. const snippet = super.generate( builder );
  5073. const arrayType = this.referenceNode.getNodeType();
  5074. const elementType = this.getNodeType();
  5075. return builder.format( snippet, arrayType, elementType );
  5076. }
  5077. };
  5078. /**
  5079. * Base class for nodes which establishes a reference to a property of another object.
  5080. * In this way, the value of the node is automatically linked to the value of
  5081. * referenced object. Reference nodes internally represent the linked value
  5082. * as a uniform.
  5083. *
  5084. * @augments Node
  5085. */
  5086. class ReferenceBaseNode extends Node {
  5087. static get type() {
  5088. return 'ReferenceBaseNode';
  5089. }
  5090. /**
  5091. * Constructs a new reference base node.
  5092. *
  5093. * @param {String} property - The name of the property the node refers to.
  5094. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  5095. * @param {Object?} [object=null] - The object the property belongs to.
  5096. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5097. */
  5098. constructor( property, uniformType, object = null, count = null ) {
  5099. super();
  5100. /**
  5101. * The name of the property the node refers to.
  5102. *
  5103. * @type {String}
  5104. */
  5105. this.property = property;
  5106. /**
  5107. * The uniform type that should be used to represent the property value.
  5108. *
  5109. * @type {String}
  5110. */
  5111. this.uniformType = uniformType;
  5112. /**
  5113. * The object the property belongs to.
  5114. *
  5115. * @type {Object?}
  5116. * @default null
  5117. */
  5118. this.object = object;
  5119. /**
  5120. * When the linked property is an array, this parameter defines its length.
  5121. *
  5122. * @type {Number?}
  5123. * @default null
  5124. */
  5125. this.count = count;
  5126. /**
  5127. * The property name might have dots so nested properties can be referred.
  5128. * The hierarchy of the names is stored inside this array.
  5129. *
  5130. * @type {Array<String>}
  5131. */
  5132. this.properties = property.split( '.' );
  5133. /**
  5134. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  5135. * since the final reference might be updated from calling code.
  5136. *
  5137. * @type {Object?}
  5138. * @default null
  5139. */
  5140. this.reference = object;
  5141. /**
  5142. * The uniform node that holds the value of the reference node.
  5143. *
  5144. * @type {UniformNode}
  5145. * @default null
  5146. */
  5147. this.node = null;
  5148. /**
  5149. * The uniform group of the internal uniform.
  5150. *
  5151. * @type {UniformGroupNode}
  5152. * @default null
  5153. */
  5154. this.group = null;
  5155. /**
  5156. * Overwritten since reference nodes are updated per object.
  5157. *
  5158. * @type {String}
  5159. * @default 'object'
  5160. */
  5161. this.updateType = NodeUpdateType.OBJECT;
  5162. }
  5163. /**
  5164. * Sets the uniform group for this reference node.
  5165. *
  5166. * @param {UniformGroupNode} group - The uniform group to set.
  5167. * @return {ReferenceBaseNode} A reference to this node.
  5168. */
  5169. setGroup( group ) {
  5170. this.group = group;
  5171. return this;
  5172. }
  5173. /**
  5174. * When the referred property is array-like, this method can be used
  5175. * to access elements via an index node.
  5176. *
  5177. * @param {IndexNode} indexNode - indexNode.
  5178. * @return {ReferenceElementNode} A reference to an element.
  5179. */
  5180. element( indexNode ) {
  5181. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5182. }
  5183. /**
  5184. * Sets the node type which automatically defines the internal
  5185. * uniform type.
  5186. *
  5187. * @param {String} uniformType - The type to set.
  5188. */
  5189. setNodeType( uniformType ) {
  5190. const node = uniform( null, uniformType ).getSelf();
  5191. if ( this.group !== null ) {
  5192. node.setGroup( this.group );
  5193. }
  5194. this.node = node;
  5195. }
  5196. /**
  5197. * This method is overwritten since the node type is inferred from
  5198. * the type of the reference node.
  5199. *
  5200. * @param {NodeBuilder} builder - The current node builder.
  5201. * @return {String} The node type.
  5202. */
  5203. getNodeType( builder ) {
  5204. if ( this.node === null ) {
  5205. this.updateReference( builder );
  5206. this.updateValue();
  5207. }
  5208. return this.node.getNodeType( builder );
  5209. }
  5210. /**
  5211. * Returns the property value from the given referred object.
  5212. *
  5213. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5214. * @return {Any} The value.
  5215. */
  5216. getValueFromReference( object = this.reference ) {
  5217. const { properties } = this;
  5218. let value = object[ properties[ 0 ] ];
  5219. for ( let i = 1; i < properties.length; i ++ ) {
  5220. value = value[ properties[ i ] ];
  5221. }
  5222. return value;
  5223. }
  5224. /**
  5225. * Allows to update the reference based on the given state. The state is only
  5226. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  5227. *
  5228. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5229. * @return {Object} The updated reference.
  5230. */
  5231. updateReference( state ) {
  5232. this.reference = this.object !== null ? this.object : state.object;
  5233. return this.reference;
  5234. }
  5235. /**
  5236. * The output of the reference node is the internal uniform node.
  5237. *
  5238. * @return {UniformNode} The output node.
  5239. */
  5240. setup() {
  5241. this.updateValue();
  5242. return this.node;
  5243. }
  5244. /**
  5245. * Overwritten to to update the internal uniform value.
  5246. *
  5247. * @param {NodeFrame} frame - A reference to the current node frame.
  5248. */
  5249. update( /*frame*/ ) {
  5250. this.updateValue();
  5251. }
  5252. /**
  5253. * Retrieves the value from the referred object property and uses it
  5254. * to updated the internal uniform.
  5255. */
  5256. updateValue() {
  5257. if ( this.node === null ) this.setNodeType( this.uniformType );
  5258. const value = this.getValueFromReference();
  5259. if ( Array.isArray( value ) ) {
  5260. this.node.array = value;
  5261. } else {
  5262. this.node.value = value;
  5263. }
  5264. }
  5265. }
  5266. /**
  5267. * TSL function for creating a reference base node.
  5268. *
  5269. * @function
  5270. * @param {String} name - The name of the property the node refers to.
  5271. * @param {String} type - The uniform type that should be used to represent the property value.
  5272. * @param {Object} object - The object the property belongs to.
  5273. * @returns {ReferenceBaseNode}
  5274. */
  5275. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5276. /** @module RendererReferenceNode **/
  5277. /**
  5278. * This node is a special type of reference node which is intended
  5279. * for linking renderer properties with node values.
  5280. * ```js
  5281. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5282. * ```
  5283. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5284. * automatically be updated.
  5285. *
  5286. * @augments ReferenceBaseNode
  5287. */
  5288. class RendererReferenceNode extends ReferenceBaseNode {
  5289. static get type() {
  5290. return 'RendererReferenceNode';
  5291. }
  5292. /**
  5293. * Constructs a new renderer reference node.
  5294. *
  5295. * @param {String} property - The name of the property the node refers to.
  5296. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5297. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5298. * the node refers to the renderer of the current state.
  5299. */
  5300. constructor( property, inputType, renderer = null ) {
  5301. super( property, inputType, renderer );
  5302. /**
  5303. * The renderer the property belongs to. When no renderer is set,
  5304. * the node refers to the renderer of the current state.
  5305. *
  5306. * @type {Renderer?}
  5307. * @default null
  5308. */
  5309. this.renderer = renderer;
  5310. this.setGroup( renderGroup );
  5311. }
  5312. /**
  5313. * Updates the reference based on the given state. The state is only evaluated
  5314. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5315. *
  5316. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5317. * @return {Object} The updated reference.
  5318. */
  5319. updateReference( state ) {
  5320. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5321. return this.reference;
  5322. }
  5323. }
  5324. /**
  5325. * TSL function for creating a renderer reference node.
  5326. *
  5327. * @function
  5328. * @param {String} name - The name of the property the node refers to.
  5329. * @param {String} type - The uniform type that should be used to represent the property value.
  5330. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5331. * the node refers to the renderer of the current state.
  5332. * @returns {RendererReferenceNode}
  5333. */
  5334. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5335. /** @module ToneMappingNode **/
  5336. /**
  5337. * This node represents a tone mapping operation.
  5338. *
  5339. * @augments TempNode
  5340. */
  5341. class ToneMappingNode extends TempNode {
  5342. static get type() {
  5343. return 'ToneMappingNode';
  5344. }
  5345. /**
  5346. * Constructs a new tone mapping node.
  5347. *
  5348. * @param {Number} toneMapping - The tone mapping type.
  5349. * @param {Node} exposureNode - The tone mapping exposure.
  5350. * @param {Node} [colorNode=null] - The color node to process.
  5351. */
  5352. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5353. super( 'vec3' );
  5354. /**
  5355. * The tone mapping type.
  5356. *
  5357. * @type {Number}
  5358. */
  5359. this.toneMapping = toneMapping;
  5360. /**
  5361. * The tone mapping exposure.
  5362. *
  5363. * @type {Node}
  5364. * @default null
  5365. */
  5366. this.exposureNode = exposureNode;
  5367. /**
  5368. * Represents the color to process.
  5369. *
  5370. * @type {Node?}
  5371. * @default null
  5372. */
  5373. this.colorNode = colorNode;
  5374. }
  5375. /**
  5376. * Overwrites the default `customCacheKey()` implementation by including the tone
  5377. * mapping type into the cache key.
  5378. *
  5379. * @return {Number} The hash.
  5380. */
  5381. customCacheKey() {
  5382. return hash$1( this.toneMapping );
  5383. }
  5384. setup( builder ) {
  5385. const colorNode = this.colorNode || builder.context.color;
  5386. const toneMapping = this.toneMapping;
  5387. if ( toneMapping === NoToneMapping ) return colorNode;
  5388. let outputNode = null;
  5389. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5390. if ( toneMappingFn !== null ) {
  5391. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5392. } else {
  5393. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5394. outputNode = colorNode;
  5395. }
  5396. return outputNode;
  5397. }
  5398. }
  5399. /**
  5400. * TSL function for creating a tone mapping node.
  5401. *
  5402. * @function
  5403. * @param {Number} mapping - The tone mapping type.
  5404. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5405. * @param {Node<vec3> | Color} color - The color node to process.
  5406. * @returns {ToneMappingNode<vec3>}
  5407. */
  5408. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5409. /**
  5410. * TSL object that represents the global tone mapping exposure of the renderer.
  5411. *
  5412. * @type {RendererReferenceNode<vec3>}
  5413. */
  5414. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5415. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5416. /** @module BufferAttributeNode **/
  5417. /**
  5418. * In earlier `three.js` versions it was only possible to define attribute data
  5419. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5420. * on the node level.
  5421. * ```js
  5422. * const geometry = new THREE.PlaneGeometry();
  5423. * const positionAttribute = geometry.getAttribute( 'position' );
  5424. *
  5425. * const colors = [];
  5426. * for ( let i = 0; i < position.count; i ++ ) {
  5427. * colors.push( 1, 0, 0 );
  5428. * }
  5429. *
  5430. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5431. * ```
  5432. * This new approach is especially interesting when geometry data are generated via
  5433. * compute shaders. The below line converts a storage buffer into an attribute node.
  5434. * ```js
  5435. * material.positionNode = positionBuffer.toAttribute();
  5436. * ```
  5437. * @augments InputNode
  5438. */
  5439. class BufferAttributeNode extends InputNode {
  5440. static get type() {
  5441. return 'BufferAttributeNode';
  5442. }
  5443. /**
  5444. * Constructs a new buffer attribute node.
  5445. *
  5446. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5447. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5448. * @param {Number} [bufferStride=0] - The buffer stride.
  5449. * @param {Number} [bufferOffset=0] - The buffer offset.
  5450. */
  5451. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5452. super( value, bufferType );
  5453. /**
  5454. * This flag can be used for type testing.
  5455. *
  5456. * @type {Boolean}
  5457. * @readonly
  5458. * @default true
  5459. */
  5460. this.isBufferNode = true;
  5461. /**
  5462. * The buffer type (e.g. `'vec3'`).
  5463. *
  5464. * @type {String}
  5465. * @default null
  5466. */
  5467. this.bufferType = bufferType;
  5468. /**
  5469. * The buffer stride.
  5470. *
  5471. * @type {Number}
  5472. * @default 0
  5473. */
  5474. this.bufferStride = bufferStride;
  5475. /**
  5476. * The buffer offset.
  5477. *
  5478. * @type {Number}
  5479. * @default 0
  5480. */
  5481. this.bufferOffset = bufferOffset;
  5482. /**
  5483. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5484. * if you are planning to update the attribute data per frame.
  5485. *
  5486. * @type {Number}
  5487. * @default StaticDrawUsage
  5488. */
  5489. this.usage = StaticDrawUsage;
  5490. /**
  5491. * Whether the attribute is instanced or not.
  5492. *
  5493. * @type {Boolean}
  5494. * @default false
  5495. */
  5496. this.instanced = false;
  5497. /**
  5498. * A reference to the buffer attribute.
  5499. *
  5500. * @type {BufferAttribute?}
  5501. * @default null
  5502. */
  5503. this.attribute = null;
  5504. /**
  5505. * `BufferAttributeNode` sets this property to `true` by default.
  5506. *
  5507. * @type {Boolean}
  5508. * @default true
  5509. */
  5510. this.global = true;
  5511. if ( value && value.isBufferAttribute === true ) {
  5512. this.attribute = value;
  5513. this.usage = value.usage;
  5514. this.instanced = value.isInstancedBufferAttribute;
  5515. }
  5516. }
  5517. /**
  5518. * This method is overwritten since the attribute data might be shared
  5519. * and thus the hash should be shared as well.
  5520. *
  5521. * @param {NodeBuilder} builder - The current node builder.
  5522. * @return {String} The hash.
  5523. */
  5524. getHash( builder ) {
  5525. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5526. let bufferData = builder.globalCache.getData( this.value );
  5527. if ( bufferData === undefined ) {
  5528. bufferData = {
  5529. node: this
  5530. };
  5531. builder.globalCache.setData( this.value, bufferData );
  5532. }
  5533. return bufferData.node.uuid;
  5534. }
  5535. return this.uuid;
  5536. }
  5537. /**
  5538. * This method is overwritten since the node type is inferred from
  5539. * the buffer attribute.
  5540. *
  5541. * @param {NodeBuilder} builder - The current node builder.
  5542. * @return {String} The node type.
  5543. */
  5544. getNodeType( builder ) {
  5545. if ( this.bufferType === null ) {
  5546. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5547. }
  5548. return this.bufferType;
  5549. }
  5550. /**
  5551. * Depending on which value was passed to the node, `setup()` behaves
  5552. * differently. If no instance of `BufferAttribute` was passed, the method
  5553. * creates an internal attribute and configures it respectively.
  5554. *
  5555. * @param {NodeBuilder} builder - The current node builder.
  5556. */
  5557. setup( builder ) {
  5558. if ( this.attribute !== null ) return;
  5559. const type = this.getNodeType( builder );
  5560. const array = this.value;
  5561. const itemSize = builder.getTypeLength( type );
  5562. const stride = this.bufferStride || itemSize;
  5563. const offset = this.bufferOffset;
  5564. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5565. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5566. buffer.setUsage( this.usage );
  5567. this.attribute = bufferAttribute;
  5568. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5569. }
  5570. /**
  5571. * Generates the code snippet of the buffer attribute node.
  5572. *
  5573. * @param {NodeBuilder} builder - The current node builder.
  5574. * @return {String} The generated code snippet.
  5575. */
  5576. generate( builder ) {
  5577. const nodeType = this.getNodeType( builder );
  5578. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5579. const propertyName = builder.getPropertyName( nodeAttribute );
  5580. let output = null;
  5581. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5582. this.name = propertyName;
  5583. output = propertyName;
  5584. } else {
  5585. const nodeVarying = varying( this );
  5586. output = nodeVarying.build( builder, nodeType );
  5587. }
  5588. return output;
  5589. }
  5590. /**
  5591. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5592. *
  5593. * @param {NodeBuilder} builder - The current node builder.
  5594. * @return {String} The input type.
  5595. */
  5596. getInputType( /*builder*/ ) {
  5597. return 'bufferAttribute';
  5598. }
  5599. /**
  5600. * Sets the `usage` property to the given value.
  5601. *
  5602. * @param {Number} value - The usage to set.
  5603. * @return {BufferAttributeNode} A reference to this node.
  5604. */
  5605. setUsage( value ) {
  5606. this.usage = value;
  5607. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5608. this.attribute.usage = value;
  5609. }
  5610. return this;
  5611. }
  5612. /**
  5613. * Sets the `instanced` property to the given value.
  5614. *
  5615. * @param {Boolean} value - The value to set.
  5616. * @return {BufferAttributeNode} A reference to this node.
  5617. */
  5618. setInstanced( value ) {
  5619. this.instanced = value;
  5620. return this;
  5621. }
  5622. }
  5623. /**
  5624. * TSL function for creating a buffer attribute node.
  5625. *
  5626. * @function
  5627. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5628. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5629. * @param {Number} [stride=0] - The buffer stride.
  5630. * @param {Number} [offset=0] - The buffer offset.
  5631. * @returns {BufferAttributeNode}
  5632. */
  5633. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5634. /**
  5635. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5636. * Use this function if attribute data are updated per frame.
  5637. *
  5638. * @function
  5639. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5640. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5641. * @param {Number} [stride=0] - The buffer stride.
  5642. * @param {Number} [offset=0] - The buffer offset.
  5643. * @returns {BufferAttributeNode}
  5644. */
  5645. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5646. /**
  5647. * TSL function for creating a buffer attribute node but with enabled instancing
  5648. *
  5649. * @function
  5650. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5651. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5652. * @param {Number} [stride=0] - The buffer stride.
  5653. * @param {Number} [offset=0] - The buffer offset.
  5654. * @returns {BufferAttributeNode}
  5655. */
  5656. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5657. /**
  5658. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5659. *
  5660. * @function
  5661. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5662. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5663. * @param {Number} [stride=0] - The buffer stride.
  5664. * @param {Number} [offset=0] - The buffer offset.
  5665. * @returns {BufferAttributeNode}
  5666. */
  5667. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5668. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5669. /** @module ComputeNode **/
  5670. /**
  5671. * TODO
  5672. *
  5673. * @augments Node
  5674. */
  5675. class ComputeNode extends Node {
  5676. static get type() {
  5677. return 'ComputeNode';
  5678. }
  5679. /**
  5680. * Constructs a new compute node.
  5681. *
  5682. * @param {Node} computeNode - TODO
  5683. * @param {Number} count - TODO.
  5684. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5685. */
  5686. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5687. super( 'void' );
  5688. /**
  5689. * This flag can be used for type testing.
  5690. *
  5691. * @type {Boolean}
  5692. * @readonly
  5693. * @default true
  5694. */
  5695. this.isComputeNode = true;
  5696. /**
  5697. * TODO
  5698. *
  5699. * @type {Node}
  5700. */
  5701. this.computeNode = computeNode;
  5702. /**
  5703. * TODO
  5704. *
  5705. * @type {Number}
  5706. */
  5707. this.count = count;
  5708. /**
  5709. * TODO
  5710. *
  5711. * @type {Array<Number>}
  5712. * @default [64]
  5713. */
  5714. this.workgroupSize = workgroupSize;
  5715. /**
  5716. * TODO
  5717. *
  5718. * @type {Number}
  5719. */
  5720. this.dispatchCount = 0;
  5721. /**
  5722. * TODO
  5723. *
  5724. * @type {Number}
  5725. */
  5726. this.version = 1;
  5727. /**
  5728. * The name or label of the uniform.
  5729. *
  5730. * @type {String}
  5731. * @default ''
  5732. */
  5733. this.name = '';
  5734. /**
  5735. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5736. * is executed once per object by default.
  5737. *
  5738. * @type {String}
  5739. * @default 'object'
  5740. */
  5741. this.updateBeforeType = NodeUpdateType.OBJECT;
  5742. /**
  5743. * TODO
  5744. *
  5745. * @type {Function}
  5746. */
  5747. this.onInitFunction = null;
  5748. this.updateDispatchCount();
  5749. }
  5750. /**
  5751. * Executes the `dispose` event for this node.
  5752. */
  5753. dispose() {
  5754. this.dispatchEvent( { type: 'dispose' } );
  5755. }
  5756. /**
  5757. * Sets the {@link ComputeNode#name} property.
  5758. *
  5759. * @param {String} name - The name of the uniform.
  5760. * @return {ComputeNode} A reference to this node.
  5761. */
  5762. label( name ) {
  5763. this.name = name;
  5764. return this;
  5765. }
  5766. /**
  5767. * TODO
  5768. */
  5769. updateDispatchCount() {
  5770. const { count, workgroupSize } = this;
  5771. let size = workgroupSize[ 0 ];
  5772. for ( let i = 1; i < workgroupSize.length; i ++ )
  5773. size *= workgroupSize[ i ];
  5774. this.dispatchCount = Math.ceil( count / size );
  5775. }
  5776. /**
  5777. * TODO
  5778. *
  5779. * @param {Function} callback - TODO.
  5780. * @return {ComputeNode} A reference to this node.
  5781. */
  5782. onInit( callback ) {
  5783. this.onInitFunction = callback;
  5784. return this;
  5785. }
  5786. /**
  5787. * The method execute the compute for this node.
  5788. *
  5789. * @param {NodeFrame} frame - A reference to the current node frame.
  5790. */
  5791. updateBefore( { renderer } ) {
  5792. renderer.compute( this );
  5793. }
  5794. generate( builder ) {
  5795. const { shaderStage } = builder;
  5796. if ( shaderStage === 'compute' ) {
  5797. const snippet = this.computeNode.build( builder, 'void' );
  5798. if ( snippet !== '' ) {
  5799. builder.addLineFlowCode( snippet, this );
  5800. }
  5801. }
  5802. }
  5803. }
  5804. /**
  5805. * TSL function for creating a compute node.
  5806. *
  5807. * @function
  5808. * @param {Node} node - TODO
  5809. * @param {Number} count - TODO.
  5810. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5811. * @returns {AtomicFunctionNode}
  5812. */
  5813. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5814. addMethodChaining( 'compute', compute );
  5815. /** @module CacheNode **/
  5816. /**
  5817. * This node can be used as a cache management component for another node.
  5818. * Caching is in general used by default in {@link NodeBuilder} but this node
  5819. * allows the usage of a shared parent cache during the build process.
  5820. *
  5821. * @augments Node
  5822. */
  5823. class CacheNode extends Node {
  5824. static get type() {
  5825. return 'CacheNode';
  5826. }
  5827. /**
  5828. * Constructs a new cache node.
  5829. *
  5830. * @param {Node} node - The node that should be cached.
  5831. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5832. */
  5833. constructor( node, parent = true ) {
  5834. super();
  5835. /**
  5836. * The node that should be cached.
  5837. *
  5838. * @type {Node}
  5839. */
  5840. this.node = node;
  5841. /**
  5842. * Whether this node refers to a shared parent cache or not.
  5843. *
  5844. * @type {Boolean}
  5845. * @default true
  5846. */
  5847. this.parent = parent;
  5848. /**
  5849. * This flag can be used for type testing.
  5850. *
  5851. * @type {Boolean}
  5852. * @readonly
  5853. * @default true
  5854. */
  5855. this.isCacheNode = true;
  5856. }
  5857. getNodeType( builder ) {
  5858. const previousCache = builder.getCache();
  5859. const cache = builder.getCacheFromNode( this, this.parent );
  5860. builder.setCache( cache );
  5861. const nodeType = this.node.getNodeType( builder );
  5862. builder.setCache( previousCache );
  5863. return nodeType;
  5864. }
  5865. build( builder, ...params ) {
  5866. const previousCache = builder.getCache();
  5867. const cache = builder.getCacheFromNode( this, this.parent );
  5868. builder.setCache( cache );
  5869. const data = this.node.build( builder, ...params );
  5870. builder.setCache( previousCache );
  5871. return data;
  5872. }
  5873. }
  5874. /**
  5875. * TSL function for creating a cache node.
  5876. *
  5877. * @function
  5878. * @param {Node} node - The node that should be cached.
  5879. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5880. * @returns {CacheNode}
  5881. */
  5882. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5883. addMethodChaining( 'cache', cache );
  5884. /** @module BypassNode **/
  5885. /**
  5886. * The class generates the code of a given node but returns another node in the output.
  5887. * This can be used to call a method or node that does not return a value, i.e.
  5888. * type `void` on an input where returning a value is required. Example:
  5889. *
  5890. * ```js
  5891. * material.colorNode = myColor.bypass( runVoidFn() )
  5892. *```
  5893. *
  5894. * @augments Node
  5895. */
  5896. class BypassNode extends Node {
  5897. static get type() {
  5898. return 'BypassNode';
  5899. }
  5900. /**
  5901. * Constructs a new bypass node.
  5902. *
  5903. * @param {Node} outputNode - The output node.
  5904. * @param {Node} callNode - The call node.
  5905. */
  5906. constructor( outputNode, callNode ) {
  5907. super();
  5908. /**
  5909. * This flag can be used for type testing.
  5910. *
  5911. * @type {Boolean}
  5912. * @readonly
  5913. * @default true
  5914. */
  5915. this.isBypassNode = true;
  5916. /**
  5917. * The output node.
  5918. *
  5919. * @type {Node}
  5920. */
  5921. this.outputNode = outputNode;
  5922. /**
  5923. * The call node.
  5924. *
  5925. * @type {Node}
  5926. */
  5927. this.callNode = callNode;
  5928. }
  5929. getNodeType( builder ) {
  5930. return this.outputNode.getNodeType( builder );
  5931. }
  5932. generate( builder ) {
  5933. const snippet = this.callNode.build( builder, 'void' );
  5934. if ( snippet !== '' ) {
  5935. builder.addLineFlowCode( snippet, this );
  5936. }
  5937. return this.outputNode.build( builder );
  5938. }
  5939. }
  5940. /**
  5941. * TSL function for creating a bypass node.
  5942. *
  5943. * @function
  5944. * @param {Node} outputNode - The output node.
  5945. * @param {Node} callNode - The call node.
  5946. * @returns {BypassNode}
  5947. */
  5948. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5949. addMethodChaining( 'bypass', bypass );
  5950. /** @module RemapNode **/
  5951. /**
  5952. * This node allows to remap a node value from one range into another. E.g a value of
  5953. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5954. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5955. *
  5956. * @augments Node
  5957. */
  5958. class RemapNode extends Node {
  5959. static get type() {
  5960. return 'RemapNode';
  5961. }
  5962. /**
  5963. * Constructs a new remap node.
  5964. *
  5965. * @param {Node} node - The node that should be remapped.
  5966. * @param {Node} inLowNode - The source or current lower bound of the range.
  5967. * @param {Node} inHighNode - The source or current upper bound of the range.
  5968. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5969. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5970. */
  5971. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5972. super();
  5973. /**
  5974. * The node that should be remapped.
  5975. *
  5976. * @type {Node}
  5977. */
  5978. this.node = node;
  5979. /**
  5980. * The source or current lower bound of the range.
  5981. *
  5982. * @type {Node}
  5983. */
  5984. this.inLowNode = inLowNode;
  5985. /**
  5986. * The source or current upper bound of the range.
  5987. *
  5988. * @type {Node}
  5989. */
  5990. this.inHighNode = inHighNode;
  5991. /**
  5992. * The target lower bound of the range.
  5993. *
  5994. * @type {Node}
  5995. * @default float(0)
  5996. */
  5997. this.outLowNode = outLowNode;
  5998. /**
  5999. * The target upper bound of the range.
  6000. *
  6001. * @type {Node}
  6002. * @default float(1)
  6003. */
  6004. this.outHighNode = outHighNode;
  6005. /**
  6006. * Whether the node value should be clamped before
  6007. * remapping it to the target range.
  6008. *
  6009. * @type {Boolean}
  6010. * @default true
  6011. */
  6012. this.doClamp = true;
  6013. }
  6014. setup() {
  6015. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6016. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6017. if ( doClamp === true ) t = t.clamp();
  6018. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6019. }
  6020. }
  6021. /**
  6022. * TSL function for creating a remap node.
  6023. *
  6024. * @function
  6025. * @param {Node} node - The node that should be remapped.
  6026. * @param {Node} inLowNode - The source or current lower bound of the range.
  6027. * @param {Node} inHighNode - The source or current upper bound of the range.
  6028. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6029. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6030. * @returns {RemapNode}
  6031. */
  6032. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  6033. /**
  6034. * TSL function for creating a remap node, but with enabled clamping.
  6035. *
  6036. * @function
  6037. * @param {Node} node - The node that should be remapped.
  6038. * @param {Node} inLowNode - The source or current lower bound of the range.
  6039. * @param {Node} inHighNode - The source or current upper bound of the range.
  6040. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6041. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6042. * @returns {RemapNode}
  6043. */
  6044. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  6045. addMethodChaining( 'remap', remap );
  6046. addMethodChaining( 'remapClamp', remapClamp );
  6047. /** @module ExpressionNode **/
  6048. /**
  6049. * This class can be used to implement basic expressions in shader code.
  6050. * Basic examples for that are `return`, `continue` or `discard` statements.
  6051. *
  6052. * @augments Node
  6053. */
  6054. class ExpressionNode extends Node {
  6055. static get type() {
  6056. return 'ExpressionNode';
  6057. }
  6058. /**
  6059. * Constructs a new expression node.
  6060. *
  6061. * @param {String} [snippet=''] - The native code snippet.
  6062. * @param {String} [nodeType='void'] - The node type.
  6063. */
  6064. constructor( snippet = '', nodeType = 'void' ) {
  6065. super( nodeType );
  6066. /**
  6067. * The native code snippet.
  6068. *
  6069. * @type {String}
  6070. * @default ''
  6071. */
  6072. this.snippet = snippet;
  6073. }
  6074. generate( builder, output ) {
  6075. const type = this.getNodeType( builder );
  6076. const snippet = this.snippet;
  6077. if ( type === 'void' ) {
  6078. builder.addLineFlowCode( snippet, this );
  6079. } else {
  6080. return builder.format( `( ${ snippet } )`, type, output );
  6081. }
  6082. }
  6083. }
  6084. /**
  6085. * TSL function for creating an expression node.
  6086. *
  6087. * @function
  6088. * @param {String} [snippet=''] - The native code snippet.
  6089. * @param {String} [nodeType='void'] - The node type.
  6090. * @returns {ExpressionNode}
  6091. */
  6092. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  6093. /** @module Discard **/
  6094. /**
  6095. * Represents a `discard` shader operation in TSL.
  6096. *
  6097. * @method
  6098. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6099. * @return {Node} The `discard` expression.
  6100. */
  6101. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  6102. /**
  6103. * Represents a `return` shader operation in TSL.
  6104. *
  6105. * @method
  6106. * @return {ExpressionNode} The `return` expression.
  6107. */
  6108. const Return = () => expression( 'return' ).append();
  6109. addMethodChaining( 'discard', Discard );
  6110. /** @module RenderOutputNode **/
  6111. /**
  6112. * Normally, tone mapping and color conversion happens automatically
  6113. * before outputting pixel too the default (screen) framebuffer. In certain
  6114. * post processing setups this happens to late because certain effects
  6115. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6116. * to apply tone mapping and color space conversion at an arbitrary point
  6117. * in the effect chain.
  6118. *
  6119. * When applying tone mapping and color space conversion manually with this node,
  6120. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6121. *
  6122. * ```js
  6123. * const postProcessing = new PostProcessing( renderer );
  6124. * postProcessing.outputColorTransform = false;
  6125. *
  6126. * const scenePass = pass( scene, camera );
  6127. * const outputPass = renderOutput( scenePass );
  6128. *
  6129. * postProcessing.outputNode = outputPass;
  6130. * ```
  6131. *
  6132. * @augments TempNode
  6133. */
  6134. class RenderOutputNode extends TempNode {
  6135. static get type() {
  6136. return 'RenderOutputNode';
  6137. }
  6138. /**
  6139. * Constructs a new render output node.
  6140. *
  6141. * @param {Node} colorNode - The color node to process.
  6142. * @param {Number} toneMapping - The tone mapping type.
  6143. * @param {String} outputColorSpace - The output color space.
  6144. */
  6145. constructor( colorNode, toneMapping, outputColorSpace ) {
  6146. super( 'vec4' );
  6147. /**
  6148. * The color node to process.
  6149. *
  6150. * @type {Node}
  6151. */
  6152. this.colorNode = colorNode;
  6153. /**
  6154. * The tone mapping type.
  6155. *
  6156. * @type {Number?}
  6157. */
  6158. this.toneMapping = toneMapping;
  6159. /**
  6160. * The output color space.
  6161. *
  6162. * @type {String?}
  6163. */
  6164. this.outputColorSpace = outputColorSpace;
  6165. /**
  6166. * This flag can be used for type testing.
  6167. *
  6168. * @type {Boolean}
  6169. * @readonly
  6170. * @default true
  6171. */
  6172. this.isRenderOutputNode = true;
  6173. }
  6174. setup( { context } ) {
  6175. let outputNode = this.colorNode || context.color;
  6176. // tone mapping
  6177. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6178. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6179. if ( toneMapping !== NoToneMapping ) {
  6180. outputNode = outputNode.toneMapping( toneMapping );
  6181. }
  6182. // working to output color space
  6183. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6184. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6185. }
  6186. return outputNode;
  6187. }
  6188. }
  6189. /**
  6190. * TSL function for creating a posterize node.
  6191. *
  6192. * @function
  6193. * @param {Node} color - The color node to process.
  6194. * @param {Number?} [toneMapping=null] - The tone mapping type.
  6195. * @param {String?} [outputColorSpace=null] - The output color space.
  6196. * @returns {RenderOutputNode}
  6197. */
  6198. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6199. addMethodChaining( 'renderOutput', renderOutput );
  6200. // Non-PURE exports list, side-effects are required here.
  6201. // TSL Base Syntax
  6202. function addNodeElement( name/*, nodeElement*/ ) {
  6203. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6204. }
  6205. /** @module AttributeNode **/
  6206. /**
  6207. * Base class for representing shader attributes as nodes.
  6208. *
  6209. * @augments Node
  6210. */
  6211. class AttributeNode extends Node {
  6212. static get type() {
  6213. return 'AttributeNode';
  6214. }
  6215. /**
  6216. * Constructs a new attribute node.
  6217. *
  6218. * @param {String} attributeName - The name of the attribute.
  6219. * @param {String?} nodeType - The node type.
  6220. */
  6221. constructor( attributeName, nodeType = null ) {
  6222. super( nodeType );
  6223. /**
  6224. * `AttributeNode` sets this property to `true` by default.
  6225. *
  6226. * @type {Boolean}
  6227. * @default true
  6228. */
  6229. this.global = true;
  6230. this._attributeName = attributeName;
  6231. }
  6232. getHash( builder ) {
  6233. return this.getAttributeName( builder );
  6234. }
  6235. getNodeType( builder ) {
  6236. let nodeType = this.nodeType;
  6237. if ( nodeType === null ) {
  6238. const attributeName = this.getAttributeName( builder );
  6239. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6240. const attribute = builder.geometry.getAttribute( attributeName );
  6241. nodeType = builder.getTypeFromAttribute( attribute );
  6242. } else {
  6243. nodeType = 'float';
  6244. }
  6245. }
  6246. return nodeType;
  6247. }
  6248. /**
  6249. * Sets the attribute name to the given value. The method can be
  6250. * overwritten in derived classes if the final name must be computed
  6251. * analytically.
  6252. *
  6253. * @param {String} attributeName - The name of the attribute.
  6254. * @return {AttributeNode} A reference to this node.
  6255. */
  6256. setAttributeName( attributeName ) {
  6257. this._attributeName = attributeName;
  6258. return this;
  6259. }
  6260. /**
  6261. * Returns the attribute name of this node. The method can be
  6262. * overwritten in derived classes if the final name must be computed
  6263. * analytically.
  6264. *
  6265. * @param {NodeBuilder} builder - The current node builder.
  6266. * @return {String} The attribute name.
  6267. */
  6268. getAttributeName( /*builder*/ ) {
  6269. return this._attributeName;
  6270. }
  6271. generate( builder ) {
  6272. const attributeName = this.getAttributeName( builder );
  6273. const nodeType = this.getNodeType( builder );
  6274. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6275. if ( geometryAttribute === true ) {
  6276. const attribute = builder.geometry.getAttribute( attributeName );
  6277. const attributeType = builder.getTypeFromAttribute( attribute );
  6278. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6279. if ( builder.shaderStage === 'vertex' ) {
  6280. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6281. } else {
  6282. const nodeVarying = varying( this );
  6283. return nodeVarying.build( builder, nodeType );
  6284. }
  6285. } else {
  6286. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6287. return builder.generateConst( nodeType );
  6288. }
  6289. }
  6290. serialize( data ) {
  6291. super.serialize( data );
  6292. data.global = this.global;
  6293. data._attributeName = this._attributeName;
  6294. }
  6295. deserialize( data ) {
  6296. super.deserialize( data );
  6297. this.global = data.global;
  6298. this._attributeName = data._attributeName;
  6299. }
  6300. }
  6301. /**
  6302. * TSL function for creating an attribute node.
  6303. *
  6304. * @function
  6305. * @param {String} name - The name of the attribute.
  6306. * @param {String?} nodeType - The node type.
  6307. * @returns {AttributeNode}
  6308. */
  6309. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6310. /** @module UV **/
  6311. /**
  6312. * TSL function for creating an uv attribute node with the given index.
  6313. *
  6314. * @function
  6315. * @param {Number} [index=0] - The uv index.
  6316. * @return {AttributeNode<vec2>} The uv attribute node.
  6317. */
  6318. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6319. /** @module TextureSizeNode **/
  6320. /**
  6321. * A node that represents the dimensions of a texture. The texture size is
  6322. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6323. * or `textureSize()`.
  6324. *
  6325. * @augments Node
  6326. */
  6327. class TextureSizeNode extends Node {
  6328. static get type() {
  6329. return 'TextureSizeNode';
  6330. }
  6331. /**
  6332. * Constructs a new texture size node.
  6333. *
  6334. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6335. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6336. */
  6337. constructor( textureNode, levelNode = null ) {
  6338. super( 'uvec2' );
  6339. /**
  6340. * This flag can be used for type testing.
  6341. *
  6342. * @type {Boolean}
  6343. * @readonly
  6344. * @default true
  6345. */
  6346. this.isTextureSizeNode = true;
  6347. /**
  6348. * A texture node which size should be retrieved.
  6349. *
  6350. * @type {TextureNode}
  6351. */
  6352. this.textureNode = textureNode;
  6353. /**
  6354. * A level node which defines the requested mip.
  6355. *
  6356. * @type {Node<int>}
  6357. * @default null
  6358. */
  6359. this.levelNode = levelNode;
  6360. }
  6361. generate( builder, output ) {
  6362. const textureProperty = this.textureNode.build( builder, 'property' );
  6363. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6364. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6365. }
  6366. }
  6367. /**
  6368. * TSL function for creating a texture size node.
  6369. *
  6370. * @function
  6371. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6372. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6373. * @returns {TextureSizeNode}
  6374. */
  6375. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6376. /** @module MatcapUVNode **/
  6377. /**
  6378. * A special type of uniform node that computes the
  6379. * maximum mipmap level for a given texture node.
  6380. *
  6381. * ```js
  6382. * const level = maxMipLevel( textureNode );
  6383. * ```
  6384. *
  6385. * @augments module:UniformNode~UniformNode
  6386. */
  6387. class MaxMipLevelNode extends UniformNode {
  6388. static get type() {
  6389. return 'MaxMipLevelNode';
  6390. }
  6391. /**
  6392. * Constructs a new max mip level node.
  6393. *
  6394. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6395. */
  6396. constructor( textureNode ) {
  6397. super( 0 );
  6398. /**
  6399. * The texture node to compute the max mip level for.
  6400. *
  6401. * @private
  6402. * @type {TextureNode}
  6403. */
  6404. this._textureNode = textureNode;
  6405. /**
  6406. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6407. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6408. *
  6409. * @type {String}
  6410. * @default 'frame'
  6411. */
  6412. this.updateType = NodeUpdateType.FRAME;
  6413. }
  6414. /**
  6415. * The texture node to compute the max mip level for.
  6416. *
  6417. * @readonly
  6418. * @type {TextureNode}
  6419. */
  6420. get textureNode() {
  6421. return this._textureNode;
  6422. }
  6423. /**
  6424. * The texture.
  6425. *
  6426. * @readonly
  6427. * @type {Texture}
  6428. */
  6429. get texture() {
  6430. return this._textureNode.value;
  6431. }
  6432. update() {
  6433. const texture = this.texture;
  6434. const images = texture.images;
  6435. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6436. if ( image && image.width !== undefined ) {
  6437. const { width, height } = image;
  6438. this.value = Math.log2( Math.max( width, height ) );
  6439. }
  6440. }
  6441. }
  6442. /**
  6443. * TSL function for creating a max mip level node.
  6444. *
  6445. * @function
  6446. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6447. * @returns {MaxMipLevelNode}
  6448. */
  6449. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6450. /** @module TextureNode **/
  6451. /**
  6452. * This type of uniform node represents a 2D texture.
  6453. *
  6454. * @augments module:UniformNode~UniformNode
  6455. */
  6456. class TextureNode extends UniformNode {
  6457. static get type() {
  6458. return 'TextureNode';
  6459. }
  6460. /**
  6461. * Constructs a new texture node.
  6462. *
  6463. * @param {Texture} value - The texture.
  6464. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6465. * @param {Node<int>?} [levelNode=null] - The level node.
  6466. * @param {Node<float>?} [biasNode=null] - The bias node.
  6467. */
  6468. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6469. super( value );
  6470. /**
  6471. * This flag can be used for type testing.
  6472. *
  6473. * @type {Boolean}
  6474. * @readonly
  6475. * @default true
  6476. */
  6477. this.isTextureNode = true;
  6478. /**
  6479. * Represents the texture coordinates.
  6480. *
  6481. * @type {Node<vec2|vec3>?}
  6482. * @default null
  6483. */
  6484. this.uvNode = uvNode;
  6485. /**
  6486. * Represents the mip level that should be selected.
  6487. *
  6488. * @type {Node<int>?}
  6489. * @default null
  6490. */
  6491. this.levelNode = levelNode;
  6492. /**
  6493. * Represents the bias to be applied during level-of-detail computation.
  6494. *
  6495. * @type {Node<float>?}
  6496. * @default null
  6497. */
  6498. this.biasNode = biasNode;
  6499. /**
  6500. * Represents a reference value a texture sample is compared to.
  6501. *
  6502. * @type {Node<float>?}
  6503. * @default null
  6504. */
  6505. this.compareNode = null;
  6506. /**
  6507. * When using texture arrays, the depth node defines the layer to select.
  6508. *
  6509. * @type {Node<int>?}
  6510. * @default null
  6511. */
  6512. this.depthNode = null;
  6513. /**
  6514. * When defined, a texture is sampled using explicit gradients.
  6515. *
  6516. * @type {Array<Node<vec2>>?}
  6517. * @default null
  6518. */
  6519. this.gradNode = null;
  6520. /**
  6521. * Whether texture values should be sampled or fetched.
  6522. *
  6523. * @type {Boolean}
  6524. * @default true
  6525. */
  6526. this.sampler = true;
  6527. /**
  6528. * Whether the uv transformation matrix should be
  6529. * automatically updated or not. Use `setUpdateMatrix()`
  6530. * if you want to change the value of the property.
  6531. *
  6532. * @type {Boolean}
  6533. * @default false
  6534. */
  6535. this.updateMatrix = false;
  6536. /**
  6537. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6538. * sets the value to `frame` when the uv transformation matrix should
  6539. * automatically be updated.
  6540. *
  6541. * @type {String}
  6542. * @default 'none'
  6543. */
  6544. this.updateType = NodeUpdateType.NONE;
  6545. /**
  6546. * The reference node.
  6547. *
  6548. * @type {Node?}
  6549. * @default null
  6550. */
  6551. this.referenceNode = null;
  6552. /**
  6553. * The texture value is stored in a private property.
  6554. *
  6555. * @private
  6556. * @type {Texture}
  6557. */
  6558. this._value = value;
  6559. /**
  6560. * The uniform node that represents the uv transformation matrix.
  6561. *
  6562. * @private
  6563. * @type {UniformNode<mat3>?}
  6564. */
  6565. this._matrixUniform = null;
  6566. this.setUpdateMatrix( uvNode === null );
  6567. }
  6568. set value( value ) {
  6569. if ( this.referenceNode ) {
  6570. this.referenceNode.value = value;
  6571. } else {
  6572. this._value = value;
  6573. }
  6574. }
  6575. /**
  6576. * The texture value.
  6577. *
  6578. * @type {Texture}
  6579. */
  6580. get value() {
  6581. return this.referenceNode ? this.referenceNode.value : this._value;
  6582. }
  6583. /**
  6584. * Overwritten since the uniform hash is defined by the texture's UUID.
  6585. *
  6586. * @param {NodeBuilder} builder - The current node builder.
  6587. * @return {String} The uniform hash.
  6588. */
  6589. getUniformHash( /*builder*/ ) {
  6590. return this.value.uuid;
  6591. }
  6592. /**
  6593. * Overwritten since the node type is inferred from the texture type.
  6594. *
  6595. * @param {NodeBuilder} builder - The current node builder.
  6596. * @return {String} The node type.
  6597. */
  6598. getNodeType( /*builder*/ ) {
  6599. if ( this.value.isDepthTexture === true ) return 'float';
  6600. if ( this.value.type === UnsignedIntType ) {
  6601. return 'uvec4';
  6602. } else if ( this.value.type === IntType ) {
  6603. return 'ivec4';
  6604. }
  6605. return 'vec4';
  6606. }
  6607. /**
  6608. * Overwrites the default implementation to return a fixed value `'texture'`.
  6609. *
  6610. * @param {NodeBuilder} builder - The current node builder.
  6611. * @return {String} The input type.
  6612. */
  6613. getInputType( /*builder*/ ) {
  6614. return 'texture';
  6615. }
  6616. /**
  6617. * Returns a default uvs based on the current texture's channel.
  6618. *
  6619. * @return {AttributeNode<vec2>} The default uvs.
  6620. */
  6621. getDefaultUV() {
  6622. return uv( this.value.channel );
  6623. }
  6624. /**
  6625. * Overwritten to always return the texture reference of the node.
  6626. *
  6627. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6628. * @return {Texture} The texture reference.
  6629. */
  6630. updateReference( /*state*/ ) {
  6631. return this.value;
  6632. }
  6633. /**
  6634. * Transforms the given uv node with the texture transformation matrix.
  6635. *
  6636. * @param {Node} uvNode - The uv node to transform.
  6637. * @return {Node} The transformed uv node.
  6638. */
  6639. getTransformedUV( uvNode ) {
  6640. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6641. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6642. }
  6643. /**
  6644. * Defines whether the uv transformation matrix should automatically be updated or not.
  6645. *
  6646. * @param {Boolean} value - The update toggle.
  6647. * @return {TextureNode} A reference to this node.
  6648. */
  6649. setUpdateMatrix( value ) {
  6650. this.updateMatrix = value;
  6651. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6652. return this;
  6653. }
  6654. /**
  6655. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6656. * to modify the uv node for correct sampling.
  6657. *
  6658. * @param {NodeBuilder} builder - The current node builder.
  6659. * @param {Node} uvNode - The uv node to setup.
  6660. * @return {Node} The updated uv node.
  6661. */
  6662. setupUV( builder, uvNode ) {
  6663. const texture = this.value;
  6664. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6665. if ( this.sampler ) {
  6666. uvNode = uvNode.flipY();
  6667. } else {
  6668. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6669. }
  6670. }
  6671. return uvNode;
  6672. }
  6673. /**
  6674. * Setups texture node by preparing the internal nodes for code generation.
  6675. *
  6676. * @param {NodeBuilder} builder - The current node builder.
  6677. */
  6678. setup( builder ) {
  6679. const properties = builder.getNodeProperties( this );
  6680. properties.referenceNode = this.referenceNode;
  6681. //
  6682. const texture = this.value;
  6683. if ( ! texture || texture.isTexture !== true ) {
  6684. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6685. }
  6686. //
  6687. let uvNode = this.uvNode;
  6688. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6689. uvNode = builder.context.getUV( this );
  6690. }
  6691. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6692. if ( this.updateMatrix === true ) {
  6693. uvNode = this.getTransformedUV( uvNode );
  6694. }
  6695. uvNode = this.setupUV( builder, uvNode );
  6696. //
  6697. let levelNode = this.levelNode;
  6698. if ( levelNode === null && builder.context.getTextureLevel ) {
  6699. levelNode = builder.context.getTextureLevel( this );
  6700. }
  6701. //
  6702. properties.uvNode = uvNode;
  6703. properties.levelNode = levelNode;
  6704. properties.biasNode = this.biasNode;
  6705. properties.compareNode = this.compareNode;
  6706. properties.gradNode = this.gradNode;
  6707. properties.depthNode = this.depthNode;
  6708. }
  6709. /**
  6710. * Generates the uv code snippet.
  6711. *
  6712. * @param {NodeBuilder} builder - The current node builder.
  6713. * @param {Node} uvNode - The uv node to generate code for.
  6714. * @return {String} The generated code snippet.
  6715. */
  6716. generateUV( builder, uvNode ) {
  6717. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6718. }
  6719. /**
  6720. * Generates the snippet for the texture sampling.
  6721. *
  6722. * @param {NodeBuilder} builder - The current node builder.
  6723. * @param {String} textureProperty - The texture property.
  6724. * @param {String} uvSnippet - The uv snippet.
  6725. * @param {String?} levelSnippet - The level snippet.
  6726. * @param {String?} biasSnippet - The bias snippet.
  6727. * @param {String?} depthSnippet - The depth snippet.
  6728. * @param {String?} compareSnippet - The compare snippet.
  6729. * @param {Array<String>?} gradSnippet - The grad snippet.
  6730. * @return {String} The generated code snippet.
  6731. */
  6732. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6733. const texture = this.value;
  6734. let snippet;
  6735. if ( levelSnippet ) {
  6736. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6737. } else if ( biasSnippet ) {
  6738. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6739. } else if ( gradSnippet ) {
  6740. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6741. } else if ( compareSnippet ) {
  6742. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6743. } else if ( this.sampler === false ) {
  6744. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6745. } else {
  6746. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6747. }
  6748. return snippet;
  6749. }
  6750. /**
  6751. * Generates the code snippet of the texture node.
  6752. *
  6753. * @param {NodeBuilder} builder - The current node builder.
  6754. * @param {String} output - The current output.
  6755. * @return {String} The generated code snippet.
  6756. */
  6757. generate( builder, output ) {
  6758. const texture = this.value;
  6759. const properties = builder.getNodeProperties( this );
  6760. const textureProperty = super.generate( builder, 'property' );
  6761. if ( output === 'sampler' ) {
  6762. return textureProperty + '_sampler';
  6763. } else if ( builder.isReference( output ) ) {
  6764. return textureProperty;
  6765. } else {
  6766. const nodeData = builder.getDataFromNode( this );
  6767. let propertyName = nodeData.propertyName;
  6768. if ( propertyName === undefined ) {
  6769. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6770. const uvSnippet = this.generateUV( builder, uvNode );
  6771. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6772. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6773. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6774. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6775. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6776. const nodeVar = builder.getVarFromNode( this );
  6777. propertyName = builder.getPropertyName( nodeVar );
  6778. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6779. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6780. nodeData.snippet = snippet;
  6781. nodeData.propertyName = propertyName;
  6782. }
  6783. let snippet = propertyName;
  6784. const nodeType = this.getNodeType( builder );
  6785. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6786. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6787. }
  6788. return builder.format( snippet, nodeType, output );
  6789. }
  6790. }
  6791. /**
  6792. * Sets the sampler value.
  6793. *
  6794. * @param {Boolean} value - The sampler value to set.
  6795. * @return {TextureNode} A reference to this texture node.
  6796. */
  6797. setSampler( value ) {
  6798. this.sampler = value;
  6799. return this;
  6800. }
  6801. /**
  6802. * Returns the sampler value.
  6803. *
  6804. * @return {Boolean} The sampler value.
  6805. */
  6806. getSampler() {
  6807. return this.sampler;
  6808. }
  6809. // @TODO: Move to TSL
  6810. /**
  6811. * @function
  6812. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  6813. *
  6814. * @param {Node} uvNode - The uv node.
  6815. * @return {TextureNode} A texture node representing the texture sample.
  6816. */
  6817. uv( uvNode ) { // @deprecated, r172
  6818. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6819. return this.sample( uvNode );
  6820. }
  6821. /**
  6822. * Samples the texture with the given uv node.
  6823. *
  6824. * @param {Node} uvNode - The uv node.
  6825. * @return {TextureNode} A texture node representing the texture sample.
  6826. */
  6827. sample( uvNode ) {
  6828. const textureNode = this.clone();
  6829. textureNode.uvNode = nodeObject( uvNode );
  6830. textureNode.referenceNode = this.getSelf();
  6831. return nodeObject( textureNode );
  6832. }
  6833. /**
  6834. * Samples a blurred version of the texture by defining an internal bias.
  6835. *
  6836. * @param {Node<float>} amountNode - How blurred the texture should be.
  6837. * @return {TextureNode} A texture node representing the texture sample.
  6838. */
  6839. blur( amountNode ) {
  6840. const textureNode = this.clone();
  6841. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6842. textureNode.referenceNode = this.getSelf();
  6843. return nodeObject( textureNode );
  6844. }
  6845. /**
  6846. * Samples a specific mip of the texture.
  6847. *
  6848. * @param {Node<int>} levelNode - The mip level to sample.
  6849. * @return {TextureNode} A texture node representing the texture sample.
  6850. */
  6851. level( levelNode ) {
  6852. const textureNode = this.clone();
  6853. textureNode.levelNode = nodeObject( levelNode );
  6854. textureNode.referenceNode = this.getSelf();
  6855. return nodeObject( textureNode );
  6856. }
  6857. /**
  6858. * Returns the texture size of the requested level.
  6859. *
  6860. * @param {Node<int>} levelNode - The level to compute the size for.
  6861. * @return {TextureSizeNode} The texture size.
  6862. */
  6863. size( levelNode ) {
  6864. return textureSize( this, levelNode );
  6865. }
  6866. /**
  6867. * Samples the texture with the given bias.
  6868. *
  6869. * @param {Node<float>} biasNode - The bias node.
  6870. * @return {TextureNode} A texture node representing the texture sample.
  6871. */
  6872. bias( biasNode ) {
  6873. const textureNode = this.clone();
  6874. textureNode.biasNode = nodeObject( biasNode );
  6875. textureNode.referenceNode = this.getSelf();
  6876. return nodeObject( textureNode );
  6877. }
  6878. /**
  6879. * Samples the texture by executing a compare operation.
  6880. *
  6881. * @param {Node<float>} compareNode - The node that defines the compare value.
  6882. * @return {TextureNode} A texture node representing the texture sample.
  6883. */
  6884. compare( compareNode ) {
  6885. const textureNode = this.clone();
  6886. textureNode.compareNode = nodeObject( compareNode );
  6887. textureNode.referenceNode = this.getSelf();
  6888. return nodeObject( textureNode );
  6889. }
  6890. /**
  6891. * Samples the texture using an explicit gradient.
  6892. *
  6893. * @param {Node<vec2>} gradNodeX - The gradX node.
  6894. * @param {Node<vec2>} gradNodeY - The gradY node.
  6895. * @return {TextureNode} A texture node representing the texture sample.
  6896. */
  6897. grad( gradNodeX, gradNodeY ) {
  6898. const textureNode = this.clone();
  6899. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6900. textureNode.referenceNode = this.getSelf();
  6901. return nodeObject( textureNode );
  6902. }
  6903. /**
  6904. * Samples the texture by defining a depth node.
  6905. *
  6906. * @param {Node<int>} depthNode - The depth node.
  6907. * @return {TextureNode} A texture node representing the texture sample.
  6908. */
  6909. depth( depthNode ) {
  6910. const textureNode = this.clone();
  6911. textureNode.depthNode = nodeObject( depthNode );
  6912. textureNode.referenceNode = this.getSelf();
  6913. return nodeObject( textureNode );
  6914. }
  6915. // --
  6916. serialize( data ) {
  6917. super.serialize( data );
  6918. data.value = this.value.toJSON( data.meta ).uuid;
  6919. data.sampler = this.sampler;
  6920. data.updateMatrix = this.updateMatrix;
  6921. data.updateType = this.updateType;
  6922. }
  6923. deserialize( data ) {
  6924. super.deserialize( data );
  6925. this.value = data.meta.textures[ data.value ];
  6926. this.sampler = data.sampler;
  6927. this.updateMatrix = data.updateMatrix;
  6928. this.updateType = data.updateType;
  6929. }
  6930. /**
  6931. * The update is used to implement the update of the uv transformation matrix.
  6932. */
  6933. update() {
  6934. const texture = this.value;
  6935. const matrixUniform = this._matrixUniform;
  6936. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6937. if ( texture.matrixAutoUpdate === true ) {
  6938. texture.updateMatrix();
  6939. }
  6940. }
  6941. /**
  6942. * Clones the texture node.
  6943. *
  6944. * @return {TextureNode} The cloned texture node.
  6945. */
  6946. clone() {
  6947. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6948. newNode.sampler = this.sampler;
  6949. return newNode;
  6950. }
  6951. }
  6952. /**
  6953. * TSL function for creating a texture node.
  6954. *
  6955. * @function
  6956. * @param {Texture} value - The texture.
  6957. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6958. * @param {Node<int>?} [levelNode=null] - The level node.
  6959. * @param {Node<float>?} [biasNode=null] - The bias node.
  6960. * @returns {TextureNode}
  6961. */
  6962. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6963. /**
  6964. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6965. *
  6966. * @function
  6967. * @param {Texture} value - The texture.
  6968. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6969. * @param {Node<int>?} [levelNode=null] - The level node.
  6970. * @param {Node<float>?} [biasNode=null] - The bias node.
  6971. * @returns {TextureNode}
  6972. */
  6973. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6974. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6975. /**
  6976. * Converts a texture or texture node to a sampler.
  6977. *
  6978. * @function
  6979. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6980. * @returns {Node}
  6981. */
  6982. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6983. /** @module BufferNode **/
  6984. /**
  6985. * A special type of uniform node which represents array-like data
  6986. * as uniform buffers. The access usually happens via `element()`
  6987. * which returns an instance of {@link ArrayElementNode}. For example:
  6988. *
  6989. * ```js
  6990. * const bufferNode = buffer( array, 'mat4', count );
  6991. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  6992. * ```
  6993. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  6994. * since it handles more input types and automatically cares about buffer paddings.
  6995. *
  6996. * @augments module:UniformNode~UniformNode
  6997. */
  6998. class BufferNode extends UniformNode {
  6999. static get type() {
  7000. return 'BufferNode';
  7001. }
  7002. /**
  7003. * Constructs a new buffer node.
  7004. *
  7005. * @param {Array<Number>} value - Array-like buffer data.
  7006. * @param {String} bufferType - The data type of the buffer.
  7007. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7008. */
  7009. constructor( value, bufferType, bufferCount = 0 ) {
  7010. super( value, bufferType );
  7011. /**
  7012. * This flag can be used for type testing.
  7013. *
  7014. * @type {Boolean}
  7015. * @readonly
  7016. * @default true
  7017. */
  7018. this.isBufferNode = true;
  7019. /**
  7020. * The data type of the buffer.
  7021. *
  7022. * @type {String}
  7023. */
  7024. this.bufferType = bufferType;
  7025. /**
  7026. * The uniform node that holds the value of the reference node.
  7027. *
  7028. * @type {Number}
  7029. * @default 0
  7030. */
  7031. this.bufferCount = bufferCount;
  7032. }
  7033. /**
  7034. * The data type of the buffer elements.
  7035. *
  7036. * @param {NodeBuilder} builder - The current node builder.
  7037. * @return {String} The element type.
  7038. */
  7039. getElementType( builder ) {
  7040. return this.getNodeType( builder );
  7041. }
  7042. /**
  7043. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7044. *
  7045. * @param {NodeBuilder} builder - The current node builder.
  7046. * @return {String} The input type.
  7047. */
  7048. getInputType( /*builder*/ ) {
  7049. return 'buffer';
  7050. }
  7051. }
  7052. /**
  7053. * TSL function for creating a buffer node.
  7054. *
  7055. * @function
  7056. * @param {Array} value - Array-like buffer data.
  7057. * @param {String} type - The data type of a buffer element.
  7058. * @param {Number} count - The count of buffer elements.
  7059. * @returns {BufferNode}
  7060. */
  7061. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7062. /** @module UniformArrayNode **/
  7063. /**
  7064. * Represents the element access on uniform array nodes.
  7065. *
  7066. * @augments ArrayElementNode
  7067. */
  7068. class UniformArrayElementNode extends ArrayElementNode {
  7069. static get type() {
  7070. return 'UniformArrayElementNode';
  7071. }
  7072. /**
  7073. * Constructs a new buffer node.
  7074. *
  7075. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7076. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7077. */
  7078. constructor( uniformArrayNode, indexNode ) {
  7079. super( uniformArrayNode, indexNode );
  7080. /**
  7081. * This flag can be used for type testing.
  7082. *
  7083. * @type {Boolean}
  7084. * @readonly
  7085. * @default true
  7086. */
  7087. this.isArrayBufferElementNode = true;
  7088. }
  7089. generate( builder ) {
  7090. const snippet = super.generate( builder );
  7091. const type = this.getNodeType();
  7092. const paddedType = this.node.getPaddedType();
  7093. return builder.format( snippet, paddedType, type );
  7094. }
  7095. }
  7096. /**
  7097. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7098. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7099. * data types in the array (e.g `three.js` primitives) and automatically
  7100. * manage buffer padding. It should be the first choice when working with
  7101. * uniforms buffers.
  7102. * ```js
  7103. * const tintColors = uniformArray( [
  7104. * new Color( 1, 0, 0 ),
  7105. * new Color( 0, 1, 0 ),
  7106. * new Color( 0, 0, 1 )
  7107. * ], 'color' );
  7108. *
  7109. * const redColor = tintColors.element( 0 );
  7110. *
  7111. * @augments module:BufferNode~BufferNode
  7112. */
  7113. class UniformArrayNode extends BufferNode {
  7114. static get type() {
  7115. return 'UniformArrayNode';
  7116. }
  7117. /**
  7118. * Constructs a new uniform array node.
  7119. *
  7120. * @param {Array<Any>} value - Array holding the buffer data.
  7121. * @param {String?} [elementType=null] - The data type of a buffer element.
  7122. */
  7123. constructor( value, elementType = null ) {
  7124. super( null );
  7125. /**
  7126. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7127. * hold number primitives as well as three.js objects like vectors, matrices
  7128. * or colors.
  7129. *
  7130. * @type {Array<Any>}
  7131. */
  7132. this.array = value;
  7133. /**
  7134. * The data type of an array element.
  7135. *
  7136. * @type {String}
  7137. */
  7138. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7139. /**
  7140. * The padded type. Uniform buffers must conform to a certain buffer layout
  7141. * so a separate type is computed to ensure correct buffer size.
  7142. *
  7143. * @type {String}
  7144. */
  7145. this.paddedType = this.getPaddedType();
  7146. /**
  7147. * Overwritten since uniform array nodes are updated per render.
  7148. *
  7149. * @type {String}
  7150. * @default 'render'
  7151. */
  7152. this.updateType = NodeUpdateType.RENDER;
  7153. /**
  7154. * This flag can be used for type testing.
  7155. *
  7156. * @type {Boolean}
  7157. * @readonly
  7158. * @default true
  7159. */
  7160. this.isArrayBufferNode = true;
  7161. }
  7162. /**
  7163. * This method is overwritten since the node type is inferred from the
  7164. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7165. *
  7166. * @param {NodeBuilder} builder - The current node builder.
  7167. * @return {String} The node type.
  7168. */
  7169. getNodeType( /*builder*/ ) {
  7170. return this.paddedType;
  7171. }
  7172. /**
  7173. * The data type of the array elements.
  7174. *
  7175. * @param {NodeBuilder} builder - The current node builder.
  7176. * @return {String} The element type.
  7177. */
  7178. getElementType() {
  7179. return this.elementType;
  7180. }
  7181. /**
  7182. * Returns the padded type based on the element type.
  7183. *
  7184. * @return {String} The padded type.
  7185. */
  7186. getPaddedType() {
  7187. const elementType = this.elementType;
  7188. let paddedType = 'vec4';
  7189. if ( elementType === 'mat2' ) {
  7190. paddedType = 'mat2';
  7191. } else if ( /mat/.test( elementType ) === true ) {
  7192. paddedType = 'mat4';
  7193. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7194. paddedType = 'ivec4';
  7195. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7196. paddedType = 'uvec4';
  7197. }
  7198. return paddedType;
  7199. }
  7200. /**
  7201. * The update makes sure to correctly transfer the data from the (complex) objects
  7202. * in the array to the internal, correctly padded value buffer.
  7203. *
  7204. * @param {NodeFrame} frame - A reference to the current node frame.
  7205. */
  7206. update( /*frame*/ ) {
  7207. const { array, value } = this;
  7208. const elementType = this.elementType;
  7209. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7210. for ( let i = 0; i < array.length; i ++ ) {
  7211. const index = i * 4;
  7212. value[ index ] = array[ i ];
  7213. }
  7214. } else if ( elementType === 'color' ) {
  7215. for ( let i = 0; i < array.length; i ++ ) {
  7216. const index = i * 4;
  7217. const vector = array[ i ];
  7218. value[ index ] = vector.r;
  7219. value[ index + 1 ] = vector.g;
  7220. value[ index + 2 ] = vector.b || 0;
  7221. //value[ index + 3 ] = vector.a || 0;
  7222. }
  7223. } else if ( elementType === 'mat2' ) {
  7224. for ( let i = 0; i < array.length; i ++ ) {
  7225. const index = i * 4;
  7226. const matrix = array[ i ];
  7227. value[ index ] = matrix.elements[ 0 ];
  7228. value[ index + 1 ] = matrix.elements[ 1 ];
  7229. value[ index + 2 ] = matrix.elements[ 2 ];
  7230. value[ index + 3 ] = matrix.elements[ 3 ];
  7231. }
  7232. } else if ( elementType === 'mat3' ) {
  7233. for ( let i = 0; i < array.length; i ++ ) {
  7234. const index = i * 16;
  7235. const matrix = array[ i ];
  7236. value[ index ] = matrix.elements[ 0 ];
  7237. value[ index + 1 ] = matrix.elements[ 1 ];
  7238. value[ index + 2 ] = matrix.elements[ 2 ];
  7239. value[ index + 4 ] = matrix.elements[ 3 ];
  7240. value[ index + 5 ] = matrix.elements[ 4 ];
  7241. value[ index + 6 ] = matrix.elements[ 5 ];
  7242. value[ index + 8 ] = matrix.elements[ 6 ];
  7243. value[ index + 9 ] = matrix.elements[ 7 ];
  7244. value[ index + 10 ] = matrix.elements[ 8 ];
  7245. value[ index + 15 ] = 1;
  7246. }
  7247. } else if ( elementType === 'mat4' ) {
  7248. for ( let i = 0; i < array.length; i ++ ) {
  7249. const index = i * 16;
  7250. const matrix = array[ i ];
  7251. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7252. value[ index + i ] = matrix.elements[ i ];
  7253. }
  7254. }
  7255. } else {
  7256. for ( let i = 0; i < array.length; i ++ ) {
  7257. const index = i * 4;
  7258. const vector = array[ i ];
  7259. value[ index ] = vector.x;
  7260. value[ index + 1 ] = vector.y;
  7261. value[ index + 2 ] = vector.z || 0;
  7262. value[ index + 3 ] = vector.w || 0;
  7263. }
  7264. }
  7265. }
  7266. /**
  7267. * Implement the value buffer creation based on the array data.
  7268. *
  7269. * @param {NodeBuilder} builder - A reference to the current node builder.
  7270. * @return {null}
  7271. */
  7272. setup( builder ) {
  7273. const length = this.array.length;
  7274. const elementType = this.elementType;
  7275. let arrayType = Float32Array;
  7276. const paddedType = this.paddedType;
  7277. const paddedElementLength = builder.getTypeLength( paddedType );
  7278. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7279. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7280. this.value = new arrayType( length * paddedElementLength );
  7281. this.bufferCount = length;
  7282. this.bufferType = paddedType;
  7283. return super.setup( builder );
  7284. }
  7285. /**
  7286. * Overwrites the default `element()` method to provide element access
  7287. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7288. *
  7289. * @param {IndexNode} indexNode - The index node.
  7290. * @return {UniformArrayElementNode}
  7291. */
  7292. element( indexNode ) {
  7293. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7294. }
  7295. }
  7296. /**
  7297. * TSL function for creating an uniform array node.
  7298. *
  7299. * @function
  7300. * @param {Array<Any>} values - Array-like data.
  7301. * @param {String?} nodeType - The data type of the array elements.
  7302. * @returns {UniformArrayNode}
  7303. */
  7304. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7305. /**
  7306. * @function
  7307. * @deprecated since r168. Use {@link uniformArray} instead.
  7308. *
  7309. * @param {Array<Any>} values - Array-like data.
  7310. * @param {String} nodeType - The data type of the array elements.
  7311. * @returns {UniformArrayNode}
  7312. */
  7313. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7314. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7315. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7316. };
  7317. /** @module Camera **/
  7318. /**
  7319. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7320. *
  7321. * @type {UniformNode<uint>}
  7322. */
  7323. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7324. /**
  7325. * TSL object that represents the `near` value of the camera used for the current render.
  7326. *
  7327. * @type {UniformNode<float>}
  7328. */
  7329. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7330. /**
  7331. * TSL object that represents the `far` value of the camera used for the current render.
  7332. *
  7333. * @type {UniformNode<float>}
  7334. */
  7335. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7336. /**
  7337. * TSL object that represents the projection matrix of the camera used for the current render.
  7338. *
  7339. * @type {UniformNode<mat4>}
  7340. */
  7341. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7342. let cameraProjectionMatrix;
  7343. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7344. const matrices = [];
  7345. for ( const subCamera of camera.cameras ) {
  7346. matrices.push( subCamera.projectionMatrix );
  7347. }
  7348. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7349. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7350. } else {
  7351. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7352. }
  7353. return cameraProjectionMatrix;
  7354. } ).once() )();
  7355. /**
  7356. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7357. *
  7358. * @type {UniformNode<mat4>}
  7359. */
  7360. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7361. /**
  7362. * TSL object that represents the view matrix of the camera used for the current render.
  7363. *
  7364. * @type {UniformNode<mat4>}
  7365. */
  7366. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7367. let cameraViewMatrix;
  7368. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7369. const matrices = [];
  7370. for ( const subCamera of camera.cameras ) {
  7371. matrices.push( subCamera.matrixWorldInverse );
  7372. }
  7373. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7374. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7375. } else {
  7376. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7377. }
  7378. return cameraViewMatrix;
  7379. } ).once() )();
  7380. /**
  7381. * TSL object that represents the world matrix of the camera used for the current render.
  7382. *
  7383. * @type {UniformNode<mat4>}
  7384. */
  7385. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7386. /**
  7387. * TSL object that represents the normal matrix of the camera used for the current render.
  7388. *
  7389. * @type {UniformNode<mat3>}
  7390. */
  7391. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7392. /**
  7393. * TSL object that represents the position in world space of the camera used for the current render.
  7394. *
  7395. * @type {UniformNode<vec3>}
  7396. */
  7397. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7398. /** @module Object3DNode **/
  7399. /**
  7400. * This node can be used to access transformation related metrics of 3D objects.
  7401. * Depending on the selected scope, a different metric is represented as a uniform
  7402. * in the shader. The following scopes are supported:
  7403. *
  7404. * - `POSITION`: The object's position in world space.
  7405. * - `VIEW_POSITION`: The object's position in view/camera space.
  7406. * - `DIRECTION`: The object's direction in world space.
  7407. * - `SCALE`: The object's scale in world space.
  7408. * - `WORLD_MATRIX`: The object's matrix in world space.
  7409. *
  7410. * @augments Node
  7411. */
  7412. class Object3DNode extends Node {
  7413. static get type() {
  7414. return 'Object3DNode';
  7415. }
  7416. /**
  7417. * Constructs a new object 3D node.
  7418. *
  7419. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7420. * @param {Object3D?} [object3d=null] - The 3D object.
  7421. */
  7422. constructor( scope, object3d = null ) {
  7423. super();
  7424. /**
  7425. * The node reports a different type of transformation depending on the scope.
  7426. *
  7427. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7428. */
  7429. this.scope = scope;
  7430. /**
  7431. * The 3D object.
  7432. *
  7433. * @type {Object3D?}
  7434. * @default null
  7435. */
  7436. this.object3d = object3d;
  7437. /**
  7438. * Overwritten since this type of node is updated per object.
  7439. *
  7440. * @type {String}
  7441. * @default 'object'
  7442. */
  7443. this.updateType = NodeUpdateType.OBJECT;
  7444. /**
  7445. * Holds the value of the node as a uniform.
  7446. *
  7447. * @private
  7448. * @type {UniformNode}
  7449. */
  7450. this._uniformNode = new UniformNode( null );
  7451. }
  7452. /**
  7453. * Overwritten since the node type is inferred from the scope.
  7454. *
  7455. * @return {String} The node type.
  7456. */
  7457. getNodeType() {
  7458. const scope = this.scope;
  7459. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7460. return 'mat4';
  7461. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7462. return 'vec3';
  7463. }
  7464. }
  7465. /**
  7466. * Updates the uniform value depending on the scope.
  7467. *
  7468. * @param {NodeFrame} frame - The current node frame.
  7469. */
  7470. update( frame ) {
  7471. const object = this.object3d;
  7472. const uniformNode = this._uniformNode;
  7473. const scope = this.scope;
  7474. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7475. uniformNode.value = object.matrixWorld;
  7476. } else if ( scope === Object3DNode.POSITION ) {
  7477. uniformNode.value = uniformNode.value || new Vector3();
  7478. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7479. } else if ( scope === Object3DNode.SCALE ) {
  7480. uniformNode.value = uniformNode.value || new Vector3();
  7481. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7482. } else if ( scope === Object3DNode.DIRECTION ) {
  7483. uniformNode.value = uniformNode.value || new Vector3();
  7484. object.getWorldDirection( uniformNode.value );
  7485. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7486. const camera = frame.camera;
  7487. uniformNode.value = uniformNode.value || new Vector3();
  7488. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7489. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7490. }
  7491. }
  7492. /**
  7493. * Generates the code snippet of the uniform node. The node type of the uniform
  7494. * node also depends on the selected scope.
  7495. *
  7496. * @param {NodeBuilder} builder - The current node builder.
  7497. * @return {String} The generated code snippet.
  7498. */
  7499. generate( builder ) {
  7500. const scope = this.scope;
  7501. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7502. this._uniformNode.nodeType = 'mat4';
  7503. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7504. this._uniformNode.nodeType = 'vec3';
  7505. }
  7506. return this._uniformNode.build( builder );
  7507. }
  7508. serialize( data ) {
  7509. super.serialize( data );
  7510. data.scope = this.scope;
  7511. }
  7512. deserialize( data ) {
  7513. super.deserialize( data );
  7514. this.scope = data.scope;
  7515. }
  7516. }
  7517. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7518. Object3DNode.POSITION = 'position';
  7519. Object3DNode.SCALE = 'scale';
  7520. Object3DNode.VIEW_POSITION = 'viewPosition';
  7521. Object3DNode.DIRECTION = 'direction';
  7522. /**
  7523. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7524. *
  7525. * @function
  7526. * @param {Object3D?} [object3d=null] - The 3D object.
  7527. * @returns {Object3DNode<vec3>}
  7528. */
  7529. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7530. /**
  7531. * TSL function for creating an object 3D node that represents the object's world matrix.
  7532. *
  7533. * @function
  7534. * @param {Object3D?} [object3d=null] - The 3D object.
  7535. * @returns {Object3DNode<mat4>}
  7536. */
  7537. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7538. /**
  7539. * TSL function for creating an object 3D node that represents the object's position in world space.
  7540. *
  7541. * @function
  7542. * @param {Object3D?} [object3d=null] - The 3D object.
  7543. * @returns {Object3DNode<vec3>}
  7544. */
  7545. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7546. /**
  7547. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7548. *
  7549. * @function
  7550. * @param {Object3D?} [object3d=null] - The 3D object.
  7551. * @returns {Object3DNode<vec3>}
  7552. */
  7553. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7554. /**
  7555. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7556. *
  7557. * @function
  7558. * @param {Object3D?} [object3d=null] - The 3D object.
  7559. * @returns {Object3DNode<vec3>}
  7560. */
  7561. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7562. /** @module ModelNode **/
  7563. /**
  7564. * This type of node is a specialized version of `Object3DNode`
  7565. * with larger set of model related metrics. Unlike `Object3DNode`,
  7566. * `ModelNode` extracts the reference to the 3D object from the
  7567. * current node frame state.
  7568. *
  7569. * @augments module:Object3DNode~Object3DNode
  7570. */
  7571. class ModelNode extends Object3DNode {
  7572. static get type() {
  7573. return 'ModelNode';
  7574. }
  7575. /**
  7576. * Constructs a new object model node.
  7577. *
  7578. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7579. */
  7580. constructor( scope ) {
  7581. super( scope );
  7582. }
  7583. /**
  7584. * Extracts the model reference from the frame state and then
  7585. * updates the uniform value depending on the scope.
  7586. *
  7587. * @param {NodeFrame} frame - The current node frame.
  7588. */
  7589. update( frame ) {
  7590. this.object3d = frame.object;
  7591. super.update( frame );
  7592. }
  7593. }
  7594. /**
  7595. * TSL object that represents the object's direction in world space.
  7596. *
  7597. * @type {ModelNode<vec3>}
  7598. */
  7599. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7600. /**
  7601. * TSL object that represents the object's world matrix.
  7602. *
  7603. * @type {ModelNode<mat4>}
  7604. */
  7605. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7606. /**
  7607. * TSL object that represents the object's position in world space.
  7608. *
  7609. * @type {ModelNode<vec3>}
  7610. */
  7611. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7612. /**
  7613. * TSL object that represents the object's scale in world space.
  7614. *
  7615. * @type {ModelNode<vec3>}
  7616. */
  7617. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7618. /**
  7619. * TSL object that represents the object's position in view/camera space.
  7620. *
  7621. * @type {ModelNode<vec3>}
  7622. */
  7623. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7624. /**
  7625. * TSL object that represents the object's normal matrix.
  7626. *
  7627. * @type {UniformNode<mat3>}
  7628. */
  7629. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7630. /**
  7631. * TSL object that represents the object's inverse world matrix.
  7632. *
  7633. * @type {UniformNode<mat4>}
  7634. */
  7635. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7636. /**
  7637. * TSL object that represents the object's model view matrix.
  7638. *
  7639. * @type {Node<mat4>}
  7640. */
  7641. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7642. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7643. } ).once() )().toVar( 'modelViewMatrix' );
  7644. // GPU Precision
  7645. /**
  7646. * TSL object that represents the object's model view in `mediump` precision.
  7647. *
  7648. * @type {Node<mat4>}
  7649. */
  7650. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7651. // CPU Precision
  7652. /**
  7653. * TSL object that represents the object's model view in `highp` precision
  7654. * which is achieved by computing the matrix in JS and not in the shader.
  7655. *
  7656. * @type {Node<mat4>}
  7657. */
  7658. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7659. builder.context.isHighPrecisionModelViewMatrix = true;
  7660. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7661. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7662. } );
  7663. } ).once() )().toVar( 'highpModelViewMatrix' );
  7664. /**
  7665. * TSL object that represents the object's model normal view in `highp` precision
  7666. * which is achieved by computing the matrix in JS and not in the shader.
  7667. *
  7668. * @type {Node<mat3>}
  7669. */
  7670. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7671. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7672. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7673. if ( isHighPrecisionModelViewMatrix !== true ) {
  7674. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7675. }
  7676. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7677. } );
  7678. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7679. /** @module Position **/
  7680. /**
  7681. * TSL object that represents the position attribute of the current rendered object.
  7682. *
  7683. * @type {AttributeNode<vec3>}
  7684. */
  7685. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7686. /**
  7687. * TSL object that represents the vertex position in local space of the current rendered object.
  7688. *
  7689. * @type {AttributeNode<vec3>}
  7690. */
  7691. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7692. /**
  7693. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7694. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7695. *
  7696. * @type {AttributeNode<vec3>}
  7697. */
  7698. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7699. /**
  7700. * TSL object that represents the vertex position in world space of the current rendered object.
  7701. *
  7702. * @type {VaryingNode<vec3>}
  7703. */
  7704. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7705. /**
  7706. * TSL object that represents the position world direction of the current rendered object.
  7707. *
  7708. * @type {Node<vec3>}
  7709. */
  7710. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7711. /**
  7712. * TSL object that represents the vertex position in view space of the current rendered object.
  7713. *
  7714. * @type {VaryingNode<vec3>}
  7715. */
  7716. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7717. return builder.context.setupPositionView();
  7718. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7719. /**
  7720. * TSL object that represents the position view direction of the current rendered object.
  7721. *
  7722. * @type {VaryingNode<vec3>}
  7723. */
  7724. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7725. /** @module FrontFacingNode **/
  7726. /**
  7727. * This node can be used to evaluate whether a primitive is front or back facing.
  7728. *
  7729. * @augments Node
  7730. */
  7731. class FrontFacingNode extends Node {
  7732. static get type() {
  7733. return 'FrontFacingNode';
  7734. }
  7735. /**
  7736. * Constructs a new front facing node.
  7737. */
  7738. constructor() {
  7739. super( 'bool' );
  7740. /**
  7741. * This flag can be used for type testing.
  7742. *
  7743. * @type {Boolean}
  7744. * @readonly
  7745. * @default true
  7746. */
  7747. this.isFrontFacingNode = true;
  7748. }
  7749. generate( builder ) {
  7750. const { renderer, material } = builder;
  7751. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7752. if ( material.side === BackSide ) {
  7753. return 'false';
  7754. }
  7755. }
  7756. return builder.getFrontFacing();
  7757. }
  7758. }
  7759. /**
  7760. * TSL object that represents whether a primitive is front or back facing
  7761. *
  7762. * @type {FrontFacingNode<bool>}
  7763. */
  7764. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7765. /**
  7766. * TSL object that represents the front facing status as a number instead of a bool.
  7767. * `1` means front facing, `-1` means back facing.
  7768. *
  7769. * @type {Node<float>}
  7770. */
  7771. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7772. /** @module Normal **/
  7773. /**
  7774. * TSL object that represents the normal attribute of the current rendered object.
  7775. *
  7776. * @type {Node<vec3>}
  7777. */
  7778. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7779. /**
  7780. * TSL object that represents the vertex normal in local space of the current rendered object.
  7781. *
  7782. * @type {Node<vec3>}
  7783. */
  7784. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7785. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7786. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7787. return vec3( 0, 1, 0 );
  7788. }
  7789. return normalGeometry;
  7790. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7791. /**
  7792. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7793. *
  7794. * @type {Node<vec3>}
  7795. */
  7796. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7797. /**
  7798. * TSL object that represents the vertex normal in view space of the current rendered object.
  7799. *
  7800. * @type {Node<vec3>}
  7801. */
  7802. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7803. let node;
  7804. if ( builder.material.flatShading === true ) {
  7805. node = normalFlat;
  7806. } else {
  7807. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7808. }
  7809. return node;
  7810. }, 'vec3' ).once() )().toVar( 'normalView' );
  7811. /**
  7812. * TSL object that represents the vertex normal in world space of the current rendered object.
  7813. *
  7814. * @type {Node<vec3>}
  7815. */
  7816. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7817. /**
  7818. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7819. *
  7820. * @type {Node<vec3>}
  7821. */
  7822. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7823. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7824. return builder.context.setupNormal().context( { getUV: null } );
  7825. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7826. /**
  7827. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7828. *
  7829. * @type {Node<vec3>}
  7830. */
  7831. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7832. /**
  7833. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7834. *
  7835. * @type {Node<vec3>}
  7836. */
  7837. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7838. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7839. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7840. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7841. /**
  7842. * Transforms the normal with the given matrix.
  7843. *
  7844. * @function
  7845. * @param {Node<vec3>} normal - The normal.
  7846. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7847. * @return {Node<vec3>} The transformed normal.
  7848. */
  7849. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7850. const m = mat3( matrix );
  7851. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7852. return m.mul( transformedNormal ).xyz;
  7853. } );
  7854. /**
  7855. * Transforms the given normal from local to view space.
  7856. *
  7857. * @function
  7858. * @param {Node<vec3>} normal - The normal.
  7859. * @param {NodeBuilder} builder - The current node builder.
  7860. * @return {Node<vec3>} The transformed normal.
  7861. */
  7862. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7863. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7864. if ( modelNormalViewMatrix !== null ) {
  7865. return modelNormalViewMatrix.transformDirection( normal );
  7866. }
  7867. //
  7868. const transformedNormal = modelNormalMatrix.mul( normal );
  7869. return cameraViewMatrix.transformDirection( transformedNormal );
  7870. } );
  7871. /** @module MaterialProperties **/
  7872. /**
  7873. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7874. *
  7875. * @type {UniformNode<float>}
  7876. */
  7877. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7878. /** @module ReflectVector **/
  7879. /**
  7880. * The reflect vector in view space.
  7881. *
  7882. * @type {Node<vec3>}
  7883. */
  7884. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7885. /**
  7886. * The refract vector in view space.
  7887. *
  7888. * @type {Node<vec3>}
  7889. */
  7890. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7891. /**
  7892. * Used for sampling cube maps when using cube reflection mapping.
  7893. *
  7894. * @type {Node<vec3>}
  7895. */
  7896. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7897. /**
  7898. * Used for sampling cube maps when using cube refraction mapping.
  7899. *
  7900. * @type {Node<vec3>}
  7901. */
  7902. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7903. /** @module CubeTextureNode **/
  7904. /**
  7905. * This type of uniform node represents a cube texture.
  7906. *
  7907. * @augments module:TextureNode~TextureNode
  7908. */
  7909. class CubeTextureNode extends TextureNode {
  7910. static get type() {
  7911. return 'CubeTextureNode';
  7912. }
  7913. /**
  7914. * Constructs a new cube texture node.
  7915. *
  7916. * @param {CubeTexture} value - The cube texture.
  7917. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7918. * @param {Node<int>?} [levelNode=null] - The level node.
  7919. * @param {Node<float>?} [biasNode=null] - The bias node.
  7920. */
  7921. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7922. super( value, uvNode, levelNode, biasNode );
  7923. /**
  7924. * This flag can be used for type testing.
  7925. *
  7926. * @type {Boolean}
  7927. * @readonly
  7928. * @default true
  7929. */
  7930. this.isCubeTextureNode = true;
  7931. }
  7932. /**
  7933. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7934. *
  7935. * @param {NodeBuilder} builder - The current node builder.
  7936. * @return {String} The input type.
  7937. */
  7938. getInputType( /*builder*/ ) {
  7939. return 'cubeTexture';
  7940. }
  7941. /**
  7942. * Returns a default uvs based on the mapping type of the cube texture.
  7943. *
  7944. * @return {Node<vec3>} The default uv attribute.
  7945. */
  7946. getDefaultUV() {
  7947. const texture = this.value;
  7948. if ( texture.mapping === CubeReflectionMapping ) {
  7949. return reflectVector;
  7950. } else if ( texture.mapping === CubeRefractionMapping ) {
  7951. return refractVector;
  7952. } else {
  7953. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7954. return vec3( 0, 0, 0 );
  7955. }
  7956. }
  7957. /**
  7958. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7959. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7960. *
  7961. * @param {Boolean} value - The update toggle.
  7962. */
  7963. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7964. /**
  7965. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7966. * to modify the uv node for correct sampling.
  7967. *
  7968. * @param {NodeBuilder} builder - The current node builder.
  7969. * @param {Node} uvNode - The uv node to setup.
  7970. * @return {Node} The updated uv node.
  7971. */
  7972. setupUV( builder, uvNode ) {
  7973. const texture = this.value;
  7974. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7975. return vec3( uvNode.x.negate(), uvNode.yz );
  7976. } else {
  7977. return uvNode;
  7978. }
  7979. }
  7980. /**
  7981. * Generates the uv code snippet.
  7982. *
  7983. * @param {NodeBuilder} builder - The current node builder.
  7984. * @param {Node} cubeUV - The uv node to generate code for.
  7985. * @return {String} The generated code snippet.
  7986. */
  7987. generateUV( builder, cubeUV ) {
  7988. return cubeUV.build( builder, 'vec3' );
  7989. }
  7990. }
  7991. /**
  7992. * TSL function for creating a cube texture node.
  7993. *
  7994. * @function
  7995. * @param {CubeTexture} value - The cube texture.
  7996. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7997. * @param {Node<int>?} [levelNode=null] - The level node.
  7998. * @param {Node<float>?} [biasNode=null] - The bias node.
  7999. * @returns {CubeTextureNode}
  8000. */
  8001. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  8002. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8003. /** @module ReferenceNode **/
  8004. /**
  8005. * This class is only relevant if the referenced property is array-like.
  8006. * In this case, `ReferenceElementNode` allows to refer to a specific
  8007. * element inside the data structure via an index.
  8008. *
  8009. * @augments ArrayElementNode
  8010. */
  8011. class ReferenceElementNode extends ArrayElementNode {
  8012. static get type() {
  8013. return 'ReferenceElementNode';
  8014. }
  8015. /**
  8016. * Constructs a new reference element node.
  8017. *
  8018. * @param {ReferenceNode?} referenceNode - The reference node.
  8019. * @param {Node} indexNode - The index node that defines the element access.
  8020. */
  8021. constructor( referenceNode, indexNode ) {
  8022. super( referenceNode, indexNode );
  8023. /**
  8024. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  8025. * property references to the current node.
  8026. *
  8027. * @type {ReferenceNode?}
  8028. * @default null
  8029. */
  8030. this.referenceNode = referenceNode;
  8031. /**
  8032. * This flag can be used for type testing.
  8033. *
  8034. * @type {Boolean}
  8035. * @readonly
  8036. * @default true
  8037. */
  8038. this.isReferenceElementNode = true;
  8039. }
  8040. /**
  8041. * This method is overwritten since the node type is inferred from
  8042. * the uniform type of the reference node.
  8043. *
  8044. * @return {String} The node type.
  8045. */
  8046. getNodeType() {
  8047. return this.referenceNode.uniformType;
  8048. }
  8049. generate( builder ) {
  8050. const snippet = super.generate( builder );
  8051. const arrayType = this.referenceNode.getNodeType();
  8052. const elementType = this.getNodeType();
  8053. return builder.format( snippet, arrayType, elementType );
  8054. }
  8055. }
  8056. /**
  8057. * This type of node establishes a reference to a property of another object.
  8058. * In this way, the value of the node is automatically linked to the value of
  8059. * referenced object. Reference nodes internally represent the linked value
  8060. * as a uniform.
  8061. *
  8062. * @augments Node
  8063. */
  8064. class ReferenceNode extends Node {
  8065. static get type() {
  8066. return 'ReferenceNode';
  8067. }
  8068. /**
  8069. * Constructs a new reference node.
  8070. *
  8071. * @param {String} property - The name of the property the node refers to.
  8072. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  8073. * @param {Object?} [object=null] - The object the property belongs to.
  8074. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8075. */
  8076. constructor( property, uniformType, object = null, count = null ) {
  8077. super();
  8078. /**
  8079. * The name of the property the node refers to.
  8080. *
  8081. * @type {String}
  8082. */
  8083. this.property = property;
  8084. /**
  8085. * The uniform type that should be used to represent the property value.
  8086. *
  8087. * @type {String}
  8088. */
  8089. this.uniformType = uniformType;
  8090. /**
  8091. * The object the property belongs to.
  8092. *
  8093. * @type {Object?}
  8094. * @default null
  8095. */
  8096. this.object = object;
  8097. /**
  8098. * When the linked property is an array, this parameter defines its length.
  8099. *
  8100. * @type {Number?}
  8101. * @default null
  8102. */
  8103. this.count = count;
  8104. /**
  8105. * The property name might have dots so nested properties can be referred.
  8106. * The hierarchy of the names is stored inside this array.
  8107. *
  8108. * @type {Array<String>}
  8109. */
  8110. this.properties = property.split( '.' );
  8111. /**
  8112. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  8113. * since the final reference might be updated from calling code.
  8114. *
  8115. * @type {Object?}
  8116. * @default null
  8117. */
  8118. this.reference = object;
  8119. /**
  8120. * The uniform node that holds the value of the reference node.
  8121. *
  8122. * @type {UniformNode}
  8123. * @default null
  8124. */
  8125. this.node = null;
  8126. /**
  8127. * The uniform group of the internal uniform.
  8128. *
  8129. * @type {UniformGroupNode}
  8130. * @default null
  8131. */
  8132. this.group = null;
  8133. /**
  8134. * An optional label of the internal uniform node.
  8135. *
  8136. * @type {String?}
  8137. * @default null
  8138. */
  8139. this.name = null;
  8140. /**
  8141. * Overwritten since reference nodes are updated per object.
  8142. *
  8143. * @type {String}
  8144. * @default 'object'
  8145. */
  8146. this.updateType = NodeUpdateType.OBJECT;
  8147. }
  8148. /**
  8149. * When the referred property is array-like, this method can be used
  8150. * to access elements via an index node.
  8151. *
  8152. * @param {IndexNode} indexNode - indexNode.
  8153. * @return {ReferenceElementNode} A reference to an element.
  8154. */
  8155. element( indexNode ) {
  8156. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8157. }
  8158. /**
  8159. * Sets the uniform group for this reference node.
  8160. *
  8161. * @param {UniformGroupNode} group - The uniform group to set.
  8162. * @return {ReferenceNode} A reference to this node.
  8163. */
  8164. setGroup( group ) {
  8165. this.group = group;
  8166. return this;
  8167. }
  8168. /**
  8169. * Sets the label for the internal uniform.
  8170. *
  8171. * @param {String} name - The label to set.
  8172. * @return {ReferenceNode} A reference to this node.
  8173. */
  8174. label( name ) {
  8175. this.name = name;
  8176. return this;
  8177. }
  8178. /**
  8179. * Sets the node type which automatically defines the internal
  8180. * uniform type.
  8181. *
  8182. * @param {String} uniformType - The type to set.
  8183. */
  8184. setNodeType( uniformType ) {
  8185. let node = null;
  8186. if ( this.count !== null ) {
  8187. node = buffer( null, uniformType, this.count );
  8188. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8189. node = uniformArray( null, uniformType );
  8190. } else if ( uniformType === 'texture' ) {
  8191. node = texture( null );
  8192. } else if ( uniformType === 'cubeTexture' ) {
  8193. node = cubeTexture( null );
  8194. } else {
  8195. node = uniform( null, uniformType );
  8196. }
  8197. if ( this.group !== null ) {
  8198. node.setGroup( this.group );
  8199. }
  8200. if ( this.name !== null ) node.label( this.name );
  8201. this.node = node.getSelf();
  8202. }
  8203. /**
  8204. * This method is overwritten since the node type is inferred from
  8205. * the type of the reference node.
  8206. *
  8207. * @param {NodeBuilder} builder - The current node builder.
  8208. * @return {String} The node type.
  8209. */
  8210. getNodeType( builder ) {
  8211. if ( this.node === null ) {
  8212. this.updateReference( builder );
  8213. this.updateValue();
  8214. }
  8215. return this.node.getNodeType( builder );
  8216. }
  8217. /**
  8218. * Returns the property value from the given referred object.
  8219. *
  8220. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8221. * @return {Any} The value.
  8222. */
  8223. getValueFromReference( object = this.reference ) {
  8224. const { properties } = this;
  8225. let value = object[ properties[ 0 ] ];
  8226. for ( let i = 1; i < properties.length; i ++ ) {
  8227. value = value[ properties[ i ] ];
  8228. }
  8229. return value;
  8230. }
  8231. /**
  8232. * Allows to update the reference based on the given state. The state is only
  8233. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  8234. *
  8235. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8236. * @return {Object} The updated reference.
  8237. */
  8238. updateReference( state ) {
  8239. this.reference = this.object !== null ? this.object : state.object;
  8240. return this.reference;
  8241. }
  8242. /**
  8243. * The output of the reference node is the internal uniform node.
  8244. *
  8245. * @param {NodeBuilder} builder - The current node builder.
  8246. * @return {UniformNode} The output node.
  8247. */
  8248. setup( /* builder */ ) {
  8249. this.updateValue();
  8250. return this.node;
  8251. }
  8252. /**
  8253. * Overwritten to to update the internal uniform value.
  8254. *
  8255. * @param {NodeFrame} frame - A reference to the current node frame.
  8256. */
  8257. update( /*frame*/ ) {
  8258. this.updateValue();
  8259. }
  8260. /**
  8261. * Retrieves the value from the referred object property and uses it
  8262. * to updated the internal uniform.
  8263. */
  8264. updateValue() {
  8265. if ( this.node === null ) this.setNodeType( this.uniformType );
  8266. const value = this.getValueFromReference();
  8267. if ( Array.isArray( value ) ) {
  8268. this.node.array = value;
  8269. } else {
  8270. this.node.value = value;
  8271. }
  8272. }
  8273. }
  8274. /**
  8275. * TSL function for creating a reference node.
  8276. *
  8277. * @function
  8278. * @param {String} name - The name of the property the node refers to.
  8279. * @param {String} type - The uniform type that should be used to represent the property value.
  8280. * @param {Object} object - The object the property belongs to.
  8281. * @returns {ReferenceNode}
  8282. */
  8283. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8284. /**
  8285. * TSL function for creating a reference node. Use this function if you want need a reference
  8286. * to an array-like property that should be represented as a uniform buffer.
  8287. *
  8288. * @function
  8289. * @param {String} name - The name of the property the node refers to.
  8290. * @param {String} type - The uniform type that should be used to represent the property value.
  8291. * @param {Number} count - The number of value inside the array-like object.
  8292. * @param {Object} object - An array-like object the property belongs to.
  8293. * @returns {ReferenceNode}
  8294. */
  8295. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8296. /** @module MaterialReferenceNode **/
  8297. /**
  8298. * This node is a special type of reference node which is intended
  8299. * for linking material properties with node values.
  8300. * ```js
  8301. * const opacityNode = materialReference( 'opacity', 'float', material );
  8302. * ```
  8303. * When changing `material.opacity`, the node value of `opacityNode` will
  8304. * automatically be updated.
  8305. *
  8306. * @augments module:ReferenceNode~ReferenceNode
  8307. */
  8308. class MaterialReferenceNode extends ReferenceNode {
  8309. static get type() {
  8310. return 'MaterialReferenceNode';
  8311. }
  8312. /**
  8313. * Constructs a new material reference node.
  8314. *
  8315. * @param {String} property - The name of the property the node refers to.
  8316. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8317. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8318. * the node refers to the material of the current rendered object.
  8319. */
  8320. constructor( property, inputType, material = null ) {
  8321. super( property, inputType, material );
  8322. /**
  8323. * The material the property belongs to. When no material is set,
  8324. * the node refers to the material of the current rendered object.
  8325. *
  8326. * @type {Material?}
  8327. * @default null
  8328. */
  8329. this.material = material;
  8330. /**
  8331. * This flag can be used for type testing.
  8332. *
  8333. * @type {Boolean}
  8334. * @readonly
  8335. * @default true
  8336. */
  8337. this.isMaterialReferenceNode = true;
  8338. }
  8339. /**
  8340. * Updates the reference based on the given state. The state is only evaluated
  8341. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8342. *
  8343. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8344. * @return {Object} The updated reference.
  8345. */
  8346. updateReference( state ) {
  8347. this.reference = this.material !== null ? this.material : state.material;
  8348. return this.reference;
  8349. }
  8350. }
  8351. /**
  8352. * TSL function for creating a material reference node.
  8353. *
  8354. * @function
  8355. * @param {String} name - The name of the property the node refers to.
  8356. * @param {String} type - The uniform type that should be used to represent the property value.
  8357. * @param {Material?} [material=null] - The material the property belongs to.
  8358. * When no material is set, the node refers to the material of the current rendered object.
  8359. * @returns {MaterialReferenceNode}
  8360. */
  8361. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8362. /** @module Tangent **/
  8363. /**
  8364. * TSL object that represents the tangent attribute of the current rendered object.
  8365. *
  8366. * @type {Node<vec4>}
  8367. */
  8368. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8369. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8370. builder.geometry.computeTangents();
  8371. }
  8372. return attribute( 'tangent', 'vec4' );
  8373. } )();
  8374. /**
  8375. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8376. *
  8377. * @type {Node<vec3>}
  8378. */
  8379. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8380. /**
  8381. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8382. *
  8383. * @type {Node<vec3>}
  8384. */
  8385. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8386. /**
  8387. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8388. *
  8389. * @type {Node<vec3>}
  8390. */
  8391. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8392. /**
  8393. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8394. *
  8395. * @type {Node<vec3>}
  8396. */
  8397. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8398. /**
  8399. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8400. *
  8401. * @type {Node<vec3>}
  8402. */
  8403. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8404. /** @module Bitangent **/
  8405. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8406. /**
  8407. * TSL object that represents the bitangent attribute of the current rendered object.
  8408. *
  8409. * @type {Node<vec3>}
  8410. */
  8411. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8412. /**
  8413. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8414. *
  8415. * @type {Node<vec3>}
  8416. */
  8417. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8418. /**
  8419. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8420. *
  8421. * @type {Node<vec4>}
  8422. */
  8423. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8424. /**
  8425. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8426. *
  8427. * @type {Node<vec4>}
  8428. */
  8429. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8430. /**
  8431. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8432. *
  8433. * @type {Node<vec4>}
  8434. */
  8435. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8436. /**
  8437. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8438. *
  8439. * @type {Node<vec4>}
  8440. */
  8441. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8442. /** @module AccessorsUtils **/
  8443. /**
  8444. * TSL object that represents the TBN matrix in view space.
  8445. *
  8446. * @type {Node<mat3>}
  8447. */
  8448. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8449. /**
  8450. * TSL object that represents the parallax direction.
  8451. *
  8452. * @type {Node<mat3>}
  8453. */
  8454. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8455. /**
  8456. * TSL function for computing parallax uv coordinates.
  8457. *
  8458. * @function
  8459. * @param {Node<vec2>} uv - A uv node.
  8460. * @param {Node<vec2>} scale - A scale node.
  8461. * @returns {Node<vec2>} Parallax uv coordinates.
  8462. */
  8463. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8464. /**
  8465. * TSL function for computing bent normals.
  8466. *
  8467. * @function
  8468. * @returns {Node<vec3>} Bent normals.
  8469. */
  8470. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8471. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8472. let bentNormal = anisotropyB.cross( positionViewDirection );
  8473. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8474. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8475. return bentNormal;
  8476. } )();
  8477. /** @module NormalMapNode **/
  8478. // Normal Mapping Without Precomputed Tangents
  8479. // http://www.thetenthplanet.de/archives/1180
  8480. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8481. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8482. const q0 = eye_pos.dFdx();
  8483. const q1 = eye_pos.dFdy();
  8484. const st0 = uv.dFdx();
  8485. const st1 = uv.dFdy();
  8486. const N = surf_norm; // normalized
  8487. const q1perp = q1.cross( N );
  8488. const q0perp = N.cross( q0 );
  8489. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8490. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8491. const det = T.dot( T ).max( B.dot( B ) );
  8492. const scale = faceDirection.mul( det.inverseSqrt() );
  8493. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8494. } );
  8495. /**
  8496. * This class can be used for applying normals maps to materials.
  8497. *
  8498. * ```js
  8499. * material.normalNode = normalMap( texture( normalTex ) );
  8500. * ```
  8501. *
  8502. * @augments TempNode
  8503. */
  8504. class NormalMapNode extends TempNode {
  8505. static get type() {
  8506. return 'NormalMapNode';
  8507. }
  8508. /**
  8509. * Constructs a new normal map node.
  8510. *
  8511. * @param {Node<vec3>} node - Represents the normal map data.
  8512. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8513. */
  8514. constructor( node, scaleNode = null ) {
  8515. super( 'vec3' );
  8516. /**
  8517. * Represents the normal map data.
  8518. *
  8519. * @type {Node<vec3>}
  8520. */
  8521. this.node = node;
  8522. /**
  8523. * Controls the intensity of the effect.
  8524. *
  8525. * @type {Node<vec2>?}
  8526. * @default null
  8527. */
  8528. this.scaleNode = scaleNode;
  8529. /**
  8530. * The normal map type.
  8531. *
  8532. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8533. * @default TangentSpaceNormalMap
  8534. */
  8535. this.normalMapType = TangentSpaceNormalMap;
  8536. }
  8537. setup( builder ) {
  8538. const { normalMapType, scaleNode } = this;
  8539. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8540. if ( scaleNode !== null ) {
  8541. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8542. }
  8543. let outputNode = null;
  8544. if ( normalMapType === ObjectSpaceNormalMap ) {
  8545. outputNode = transformNormalToView( normalMap );
  8546. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8547. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8548. if ( tangent === true ) {
  8549. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8550. } else {
  8551. outputNode = perturbNormal2Arb( {
  8552. eye_pos: positionView,
  8553. surf_norm: normalView,
  8554. mapN: normalMap,
  8555. uv: uv()
  8556. } );
  8557. }
  8558. }
  8559. return outputNode;
  8560. }
  8561. }
  8562. /**
  8563. * TSL function for creating a normal map node.
  8564. *
  8565. * @function
  8566. * @param {Node<vec3>} node - Represents the normal map data.
  8567. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8568. * @returns {NormalMapNode}
  8569. */
  8570. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8571. /** @module BumpMapNode **/
  8572. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8573. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8574. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8575. // It's used to preserve the same TextureNode instance
  8576. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8577. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8578. return vec2(
  8579. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8580. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8581. ).mul( bumpScale );
  8582. } );
  8583. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8584. const perturbNormalArb = Fn( ( inputs ) => {
  8585. const { surf_pos, surf_norm, dHdxy } = inputs;
  8586. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8587. const vSigmaX = surf_pos.dFdx().normalize();
  8588. const vSigmaY = surf_pos.dFdy().normalize();
  8589. const vN = surf_norm; // normalized
  8590. const R1 = vSigmaY.cross( vN );
  8591. const R2 = vN.cross( vSigmaX );
  8592. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8593. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8594. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8595. } );
  8596. /**
  8597. * This class can be used for applying bump maps to materials.
  8598. *
  8599. * ```js
  8600. * material.normalNode = bumpMap( texture( bumpTex ) );
  8601. * ```
  8602. *
  8603. * @augments TempNode
  8604. */
  8605. class BumpMapNode extends TempNode {
  8606. static get type() {
  8607. return 'BumpMapNode';
  8608. }
  8609. /**
  8610. * Constructs a new bump map node.
  8611. *
  8612. * @param {Node<float>} textureNode - Represents the bump map data.
  8613. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8614. */
  8615. constructor( textureNode, scaleNode = null ) {
  8616. super( 'vec3' );
  8617. /**
  8618. * Represents the bump map data.
  8619. *
  8620. * @type {Node<float>}
  8621. */
  8622. this.textureNode = textureNode;
  8623. /**
  8624. * Controls the intensity of the bump effect.
  8625. *
  8626. * @type {Node<float>?}
  8627. * @default null
  8628. */
  8629. this.scaleNode = scaleNode;
  8630. }
  8631. setup() {
  8632. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8633. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8634. return perturbNormalArb( {
  8635. surf_pos: positionView,
  8636. surf_norm: normalView,
  8637. dHdxy
  8638. } );
  8639. }
  8640. }
  8641. /**
  8642. * TSL function for creating a bump map node.
  8643. *
  8644. * @function
  8645. * @param {Node<float>} textureNode - Represents the bump map data.
  8646. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8647. * @returns {BumpMapNode}
  8648. */
  8649. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8650. /** @module MaterialNode **/
  8651. const _propertyCache = new Map();
  8652. /**
  8653. * This class should simplify the node access to material properties.
  8654. * It internal uses reference nodes to make sure changes to material
  8655. * properties are automatically reflected to predefined TSL objects
  8656. * like e.g. `materialColor`.
  8657. *
  8658. * @augments Node
  8659. */
  8660. class MaterialNode extends Node {
  8661. static get type() {
  8662. return 'MaterialNode';
  8663. }
  8664. /**
  8665. * Constructs a new material node.
  8666. *
  8667. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8668. */
  8669. constructor( scope ) {
  8670. super();
  8671. /**
  8672. * The scope defines what material property is referred by the node.
  8673. *
  8674. * @type {String}
  8675. */
  8676. this.scope = scope;
  8677. }
  8678. /**
  8679. * Returns a cached reference node for the given property and type.
  8680. *
  8681. * @param {String} property - The name of the material property.
  8682. * @param {String} type - The uniform type of the property.
  8683. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8684. */
  8685. getCache( property, type ) {
  8686. let node = _propertyCache.get( property );
  8687. if ( node === undefined ) {
  8688. node = materialReference( property, type );
  8689. _propertyCache.set( property, node );
  8690. }
  8691. return node;
  8692. }
  8693. /**
  8694. * Returns a float-typed material reference node for the given property name.
  8695. *
  8696. * @param {String} property - The name of the material property.
  8697. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8698. */
  8699. getFloat( property ) {
  8700. return this.getCache( property, 'float' );
  8701. }
  8702. /**
  8703. * Returns a color-typed material reference node for the given property name.
  8704. *
  8705. * @param {String} property - The name of the material property.
  8706. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8707. */
  8708. getColor( property ) {
  8709. return this.getCache( property, 'color' );
  8710. }
  8711. /**
  8712. * Returns a texture-typed material reference node for the given property name.
  8713. *
  8714. * @param {String} property - The name of the material property.
  8715. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8716. */
  8717. getTexture( property ) {
  8718. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8719. }
  8720. /**
  8721. * The node setup is done depending on the selected scope. Multiple material properties
  8722. * might be grouped into a single node composition if they logically belong together.
  8723. *
  8724. * @param {NodeBuilder} builder - The current node builder.
  8725. * @return {Node} The node representing the selected scope.
  8726. */
  8727. setup( builder ) {
  8728. const material = builder.context.material;
  8729. const scope = this.scope;
  8730. let node = null;
  8731. if ( scope === MaterialNode.COLOR ) {
  8732. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8733. if ( material.map && material.map.isTexture === true ) {
  8734. node = colorNode.mul( this.getTexture( 'map' ) );
  8735. } else {
  8736. node = colorNode;
  8737. }
  8738. } else if ( scope === MaterialNode.OPACITY ) {
  8739. const opacityNode = this.getFloat( scope );
  8740. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8741. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8742. } else {
  8743. node = opacityNode;
  8744. }
  8745. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8746. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8747. node = this.getTexture( 'specular' ).r;
  8748. } else {
  8749. node = float( 1 );
  8750. }
  8751. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8752. const specularIntensityNode = this.getFloat( scope );
  8753. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8754. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8755. } else {
  8756. node = specularIntensityNode;
  8757. }
  8758. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8759. const specularColorNode = this.getColor( scope );
  8760. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8761. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8762. } else {
  8763. node = specularColorNode;
  8764. }
  8765. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8766. const roughnessNode = this.getFloat( scope );
  8767. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8768. node = roughnessNode.mul( this.getTexture( scope ).g );
  8769. } else {
  8770. node = roughnessNode;
  8771. }
  8772. } else if ( scope === MaterialNode.METALNESS ) {
  8773. const metalnessNode = this.getFloat( scope );
  8774. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8775. node = metalnessNode.mul( this.getTexture( scope ).b );
  8776. } else {
  8777. node = metalnessNode;
  8778. }
  8779. } else if ( scope === MaterialNode.EMISSIVE ) {
  8780. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8781. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8782. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8783. node = emissiveNode.mul( this.getTexture( scope ) );
  8784. } else {
  8785. node = emissiveNode;
  8786. }
  8787. } else if ( scope === MaterialNode.NORMAL ) {
  8788. if ( material.normalMap ) {
  8789. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8790. node.normalMapType = material.normalMapType;
  8791. } else if ( material.bumpMap ) {
  8792. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8793. } else {
  8794. node = normalView;
  8795. }
  8796. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8797. const clearcoatNode = this.getFloat( scope );
  8798. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8799. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8800. } else {
  8801. node = clearcoatNode;
  8802. }
  8803. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8804. const clearcoatRoughnessNode = this.getFloat( scope );
  8805. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8806. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8807. } else {
  8808. node = clearcoatRoughnessNode;
  8809. }
  8810. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8811. if ( material.clearcoatNormalMap ) {
  8812. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8813. } else {
  8814. node = normalView;
  8815. }
  8816. } else if ( scope === MaterialNode.SHEEN ) {
  8817. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8818. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8819. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8820. } else {
  8821. node = sheenNode;
  8822. }
  8823. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8824. const sheenRoughnessNode = this.getFloat( scope );
  8825. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8826. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8827. } else {
  8828. node = sheenRoughnessNode;
  8829. }
  8830. node = node.clamp( 0.07, 1.0 );
  8831. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8832. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8833. const anisotropyPolar = this.getTexture( scope );
  8834. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8835. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8836. } else {
  8837. node = materialAnisotropyVector;
  8838. }
  8839. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8840. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8841. if ( material.iridescenceThicknessMap ) {
  8842. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8843. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8844. } else {
  8845. node = iridescenceThicknessMaximum;
  8846. }
  8847. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8848. const transmissionNode = this.getFloat( scope );
  8849. if ( material.transmissionMap ) {
  8850. node = transmissionNode.mul( this.getTexture( scope ).r );
  8851. } else {
  8852. node = transmissionNode;
  8853. }
  8854. } else if ( scope === MaterialNode.THICKNESS ) {
  8855. const thicknessNode = this.getFloat( scope );
  8856. if ( material.thicknessMap ) {
  8857. node = thicknessNode.mul( this.getTexture( scope ).g );
  8858. } else {
  8859. node = thicknessNode;
  8860. }
  8861. } else if ( scope === MaterialNode.IOR ) {
  8862. node = this.getFloat( scope );
  8863. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8864. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8865. } else if ( scope === MaterialNode.AO ) {
  8866. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8867. } else {
  8868. const outputType = this.getNodeType( builder );
  8869. node = this.getCache( scope, outputType );
  8870. }
  8871. return node;
  8872. }
  8873. }
  8874. MaterialNode.ALPHA_TEST = 'alphaTest';
  8875. MaterialNode.COLOR = 'color';
  8876. MaterialNode.OPACITY = 'opacity';
  8877. MaterialNode.SHININESS = 'shininess';
  8878. MaterialNode.SPECULAR = 'specular';
  8879. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8880. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8881. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8882. MaterialNode.REFLECTIVITY = 'reflectivity';
  8883. MaterialNode.ROUGHNESS = 'roughness';
  8884. MaterialNode.METALNESS = 'metalness';
  8885. MaterialNode.NORMAL = 'normal';
  8886. MaterialNode.CLEARCOAT = 'clearcoat';
  8887. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8888. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8889. MaterialNode.EMISSIVE = 'emissive';
  8890. MaterialNode.ROTATION = 'rotation';
  8891. MaterialNode.SHEEN = 'sheen';
  8892. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8893. MaterialNode.ANISOTROPY = 'anisotropy';
  8894. MaterialNode.IRIDESCENCE = 'iridescence';
  8895. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8896. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8897. MaterialNode.IOR = 'ior';
  8898. MaterialNode.TRANSMISSION = 'transmission';
  8899. MaterialNode.THICKNESS = 'thickness';
  8900. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8901. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8902. MaterialNode.LINE_SCALE = 'scale';
  8903. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8904. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8905. MaterialNode.LINE_WIDTH = 'linewidth';
  8906. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8907. MaterialNode.POINT_SIZE = 'size';
  8908. MaterialNode.DISPERSION = 'dispersion';
  8909. MaterialNode.LIGHT_MAP = 'light';
  8910. MaterialNode.AO = 'ao';
  8911. /**
  8912. * TSL object that represents alpha test of the current material.
  8913. *
  8914. * @type {Node<float>}
  8915. */
  8916. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8917. /**
  8918. * TSL object that represents the diffuse color of the current material.
  8919. * The value is composed via `color` * `map`.
  8920. *
  8921. * @type {Node<vec3>}
  8922. */
  8923. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8924. /**
  8925. * TSL object that represents the shininess of the current material.
  8926. *
  8927. * @type {Node<float>}
  8928. */
  8929. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8930. /**
  8931. * TSL object that represents the emissive color of the current material.
  8932. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8933. *
  8934. * @type {Node<vec3>}
  8935. */
  8936. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8937. /**
  8938. * TSL object that represents the opacity of the current material.
  8939. * The value is composed via `opacity` * `alphaMap`.
  8940. *
  8941. * @type {Node<float>}
  8942. */
  8943. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8944. /**
  8945. * TSL object that represents the specular of the current material.
  8946. *
  8947. * @type {Node<vec3>}
  8948. */
  8949. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8950. /**
  8951. * TSL object that represents the specular intensity of the current material.
  8952. * The value is composed via `specularIntensity` * `specularMap.a`.
  8953. *
  8954. * @type {Node<float>}
  8955. */
  8956. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8957. /**
  8958. * TSL object that represents the specular color of the current material.
  8959. * The value is composed via `specularColor` * `specularMap.rgb`.
  8960. *
  8961. * @type {Node<vec3>}
  8962. */
  8963. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8964. /**
  8965. * TSL object that represents the specular strength of the current material.
  8966. * The value is composed via `specularMap.r`.
  8967. *
  8968. * @type {Node<float>}
  8969. */
  8970. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8971. /**
  8972. * TSL object that represents the reflectivity of the current material.
  8973. *
  8974. * @type {Node<float>}
  8975. */
  8976. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8977. /**
  8978. * TSL object that represents the roughness of the current material.
  8979. * The value is composed via `roughness` * `roughnessMap.g`.
  8980. *
  8981. * @type {Node<float>}
  8982. */
  8983. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8984. /**
  8985. * TSL object that represents the metalness of the current material.
  8986. * The value is composed via `metalness` * `metalnessMap.b`.
  8987. *
  8988. * @type {Node<float>}
  8989. */
  8990. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8991. /**
  8992. * TSL object that represents the normal of the current material.
  8993. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8994. *
  8995. * @type {Node<vec3>}
  8996. */
  8997. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  8998. /**
  8999. * TSL object that represents the clearcoat of the current material.
  9000. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9001. *
  9002. * @type {Node<float>}
  9003. */
  9004. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9005. /**
  9006. * TSL object that represents the clearcoat roughness of the current material.
  9007. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9008. *
  9009. * @type {Node<float>}
  9010. */
  9011. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9012. /**
  9013. * TSL object that represents the clearcoat normal of the current material.
  9014. * The value will be either `clearcoatNormalMap` or `normalView`.
  9015. *
  9016. * @type {Node<vec3>}
  9017. */
  9018. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9019. /**
  9020. * TSL object that represents the rotation of the current sprite material.
  9021. *
  9022. * @type {Node<float>}
  9023. */
  9024. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9025. /**
  9026. * TSL object that represents the sheen color of the current material.
  9027. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9028. *
  9029. * @type {Node<vec3>}
  9030. */
  9031. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9032. /**
  9033. * TSL object that represents the sheen roughness of the current material.
  9034. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9035. *
  9036. * @type {Node<float>}
  9037. */
  9038. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9039. /**
  9040. * TSL object that represents the anisotropy of the current material.
  9041. *
  9042. * @type {Node<vec2>}
  9043. */
  9044. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9045. /**
  9046. * TSL object that represents the iridescence of the current material.
  9047. *
  9048. * @type {Node<float>}
  9049. */
  9050. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9051. /**
  9052. * TSL object that represents the iridescence IOR of the current material.
  9053. *
  9054. * @type {Node<float>}
  9055. */
  9056. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9057. /**
  9058. * TSL object that represents the iridescence thickness of the current material.
  9059. *
  9060. * @type {Node<float>}
  9061. */
  9062. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9063. /**
  9064. * TSL object that represents the transmission of the current material.
  9065. * The value is composed via `transmission` * `transmissionMap.r`.
  9066. *
  9067. * @type {Node<float>}
  9068. */
  9069. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9070. /**
  9071. * TSL object that represents the thickness of the current material.
  9072. * The value is composed via `thickness` * `thicknessMap.g`.
  9073. *
  9074. * @type {Node<float>}
  9075. */
  9076. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9077. /**
  9078. * TSL object that represents the IOR of the current material.
  9079. *
  9080. * @type {Node<float>}
  9081. */
  9082. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9083. /**
  9084. * TSL object that represents the attenuation distance of the current material.
  9085. *
  9086. * @type {Node<float>}
  9087. */
  9088. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9089. /**
  9090. * TSL object that represents the attenuation color of the current material.
  9091. *
  9092. * @type {Node<vec3>}
  9093. */
  9094. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9095. /**
  9096. * TSL object that represents the scale of the current dashed line material.
  9097. *
  9098. * @type {Node<float>}
  9099. */
  9100. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9101. /**
  9102. * TSL object that represents the dash size of the current dashed line material.
  9103. *
  9104. * @type {Node<float>}
  9105. */
  9106. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9107. /**
  9108. * TSL object that represents the gap size of the current dashed line material.
  9109. *
  9110. * @type {Node<float>}
  9111. */
  9112. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9113. /**
  9114. * TSL object that represents the line width of the current line material.
  9115. *
  9116. * @type {Node<float>}
  9117. */
  9118. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9119. /**
  9120. * TSL object that represents the dash offset of the current line material.
  9121. *
  9122. * @type {Node<float>}
  9123. */
  9124. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9125. /**
  9126. * TSL object that represents the point size of the current points material.
  9127. *
  9128. * @type {Node<float>}
  9129. */
  9130. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9131. /**
  9132. * TSL object that represents the dispersion of the current material.
  9133. *
  9134. * @type {Node<float>}
  9135. */
  9136. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9137. /**
  9138. * TSL object that represents the light map of the current material.
  9139. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9140. *
  9141. * @type {Node<vec3>}
  9142. */
  9143. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9144. /**
  9145. * TSL object that represents the ambient occlusion map of the current material.
  9146. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9147. *
  9148. * @type {Node<float>}
  9149. */
  9150. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9151. /**
  9152. * TSL object that represents the anisotropy vector of the current material.
  9153. *
  9154. * @type {Node<vec2>}
  9155. */
  9156. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9157. return frame.material;
  9158. } ).onRenderUpdate( function ( { material } ) {
  9159. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9160. } );
  9161. /** @module ModelViewProjectionNode **/
  9162. /**
  9163. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9164. *
  9165. * @type {VaryingNode<vec4>}
  9166. */
  9167. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9168. return builder.context.setupModelViewProjection();
  9169. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9170. /** @module IndexNode **/
  9171. /**
  9172. * This class represents shader indices of different types. The following predefined node
  9173. * objects cover frequent use cases:
  9174. *
  9175. * - `vertexIndex`: The index of a vertex within a mesh.
  9176. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9177. * - `drawIndex`: The index of a draw call.
  9178. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9179. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9180. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9181. *
  9182. * @augments Node
  9183. */
  9184. class IndexNode extends Node {
  9185. static get type() {
  9186. return 'IndexNode';
  9187. }
  9188. /**
  9189. * Constructs a new index node.
  9190. *
  9191. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9192. */
  9193. constructor( scope ) {
  9194. super( 'uint' );
  9195. /**
  9196. * The scope of the index node.
  9197. *
  9198. * @type {String}
  9199. */
  9200. this.scope = scope;
  9201. /**
  9202. * This flag can be used for type testing.
  9203. *
  9204. * @type {Boolean}
  9205. * @readonly
  9206. * @default true
  9207. */
  9208. this.isIndexNode = true;
  9209. }
  9210. generate( builder ) {
  9211. const nodeType = this.getNodeType( builder );
  9212. const scope = this.scope;
  9213. let propertyName;
  9214. if ( scope === IndexNode.VERTEX ) {
  9215. propertyName = builder.getVertexIndex();
  9216. } else if ( scope === IndexNode.INSTANCE ) {
  9217. propertyName = builder.getInstanceIndex();
  9218. } else if ( scope === IndexNode.DRAW ) {
  9219. propertyName = builder.getDrawIndex();
  9220. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9221. propertyName = builder.getInvocationLocalIndex();
  9222. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9223. propertyName = builder.getInvocationSubgroupIndex();
  9224. } else if ( scope === IndexNode.SUBGROUP ) {
  9225. propertyName = builder.getSubgroupIndex();
  9226. } else {
  9227. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9228. }
  9229. let output;
  9230. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9231. output = propertyName;
  9232. } else {
  9233. const nodeVarying = varying( this );
  9234. output = nodeVarying.build( builder, nodeType );
  9235. }
  9236. return output;
  9237. }
  9238. }
  9239. IndexNode.VERTEX = 'vertex';
  9240. IndexNode.INSTANCE = 'instance';
  9241. IndexNode.SUBGROUP = 'subgroup';
  9242. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9243. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9244. IndexNode.DRAW = 'draw';
  9245. /**
  9246. * TSL object that represents the index of a vertex within a mesh.
  9247. *
  9248. * @type {IndexNode}
  9249. */
  9250. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9251. /**
  9252. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9253. *
  9254. * @type {IndexNode}
  9255. */
  9256. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9257. /**
  9258. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9259. *
  9260. * @type {IndexNode}
  9261. */
  9262. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9263. /**
  9264. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9265. *
  9266. * @type {IndexNode}
  9267. */
  9268. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9269. /**
  9270. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9271. *
  9272. * @type {IndexNode}
  9273. */
  9274. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9275. /**
  9276. * TSL object that represents the index of a draw call.
  9277. *
  9278. * @type {IndexNode}
  9279. */
  9280. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9281. /** @module InstanceNode **/
  9282. /**
  9283. * This node implements the vertex shader logic which is required
  9284. * when rendering 3D objects via instancing. The code makes sure
  9285. * vertex positions, normals and colors can be modified via instanced
  9286. * data.
  9287. *
  9288. * @augments Node
  9289. */
  9290. class InstanceNode extends Node {
  9291. static get type() {
  9292. return 'InstanceNode';
  9293. }
  9294. /**
  9295. * Constructs a new instance node.
  9296. *
  9297. * @param {Number} count - The number of instances.
  9298. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9299. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9300. */
  9301. constructor( count, instanceMatrix, instanceColor ) {
  9302. super( 'void' );
  9303. /**
  9304. * The number of instances.
  9305. *
  9306. * @type {Number}
  9307. */
  9308. this.count = count;
  9309. /**
  9310. * Instanced buffer attribute representing the transformation of instances.
  9311. *
  9312. * @type {InstancedBufferAttribute}
  9313. */
  9314. this.instanceMatrix = instanceMatrix;
  9315. /**
  9316. * Instanced buffer attribute representing the color of instances.
  9317. *
  9318. * @type {InstancedBufferAttribute}
  9319. */
  9320. this.instanceColor = instanceColor;
  9321. /**
  9322. * The node that represents the instance matrix data.
  9323. *
  9324. * @type {Node}
  9325. */
  9326. this.instanceMatrixNode = null;
  9327. /**
  9328. * The node that represents the instance color data.
  9329. *
  9330. * @type {Node}
  9331. */
  9332. this.instanceColorNode = null;
  9333. /**
  9334. * The update type is set to `frame` since an update
  9335. * of instanced buffer data must be checked per frame.
  9336. *
  9337. * @type {String}
  9338. * @default 'frame'
  9339. */
  9340. this.updateType = NodeUpdateType.FRAME;
  9341. /**
  9342. * A reference to a buffer that is used by `instanceMatrixNode`.
  9343. *
  9344. * @type {InstancedInterleavedBuffer}
  9345. */
  9346. this.buffer = null;
  9347. /**
  9348. * A reference to a buffer that is used by `instanceColorNode`.
  9349. *
  9350. * @type {InstancedBufferAttribute}
  9351. */
  9352. this.bufferColor = null;
  9353. }
  9354. /**
  9355. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9356. * to predefined node variables for accumulation. That follows the same patterns
  9357. * like with morph and skinning nodes.
  9358. *
  9359. * @param {NodeBuilder} builder - The current node builder.
  9360. */
  9361. setup( builder ) {
  9362. const { count, instanceMatrix, instanceColor } = this;
  9363. let { instanceMatrixNode, instanceColorNode } = this;
  9364. if ( instanceMatrixNode === null ) {
  9365. // 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.
  9366. if ( count <= 1000 ) {
  9367. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9368. } else {
  9369. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9370. this.buffer = buffer;
  9371. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9372. const instanceBuffers = [
  9373. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9374. bufferFn( buffer, 'vec4', 16, 0 ),
  9375. bufferFn( buffer, 'vec4', 16, 4 ),
  9376. bufferFn( buffer, 'vec4', 16, 8 ),
  9377. bufferFn( buffer, 'vec4', 16, 12 )
  9378. ];
  9379. instanceMatrixNode = mat4( ...instanceBuffers );
  9380. }
  9381. this.instanceMatrixNode = instanceMatrixNode;
  9382. }
  9383. if ( instanceColor && instanceColorNode === null ) {
  9384. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9385. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9386. this.bufferColor = buffer;
  9387. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9388. this.instanceColorNode = instanceColorNode;
  9389. }
  9390. // POSITION
  9391. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9392. positionLocal.assign( instancePosition );
  9393. // NORMAL
  9394. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9395. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9396. // ASSIGNS
  9397. normalLocal.assign( instanceNormal );
  9398. }
  9399. // COLOR
  9400. if ( this.instanceColorNode !== null ) {
  9401. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9402. }
  9403. }
  9404. /**
  9405. * Checks if the internal buffers required an update.
  9406. *
  9407. * @param {NodeFrame} frame - The current node frame.
  9408. */
  9409. update( /*frame*/ ) {
  9410. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9411. this.buffer.version = this.instanceMatrix.version;
  9412. }
  9413. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9414. this.bufferColor.version = this.instanceColor.version;
  9415. }
  9416. }
  9417. }
  9418. /**
  9419. * TSL function for creating an instance node.
  9420. *
  9421. * @function
  9422. * @param {Number} count - The number of instances.
  9423. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9424. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9425. * @returns {InstanceNode}
  9426. */
  9427. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9428. /** @module InstancedMeshNode **/
  9429. /**
  9430. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9431. * It allows an easier setup of the instance node.
  9432. *
  9433. * @augments module:InstanceNode~InstanceNode
  9434. */
  9435. class InstancedMeshNode extends InstanceNode {
  9436. static get type() {
  9437. return 'InstancedMeshNode';
  9438. }
  9439. /**
  9440. * Constructs a new instanced mesh node.
  9441. *
  9442. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9443. */
  9444. constructor( instancedMesh ) {
  9445. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9446. super( count, instanceMatrix, instanceColor );
  9447. /**
  9448. * A reference to the instanced mesh.
  9449. *
  9450. * @type {InstancedMesh}
  9451. */
  9452. this.instancedMesh = instancedMesh;
  9453. }
  9454. }
  9455. /**
  9456. * TSL function for creating an instanced mesh node.
  9457. *
  9458. * @function
  9459. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9460. * @returns {InstancedMeshNode}
  9461. */
  9462. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9463. /** @module BatchNode **/
  9464. /**
  9465. * This node implements the vertex shader logic which is required
  9466. * when rendering 3D objects via batching. `BatchNode` must be used
  9467. * with instances of {@link BatchedMesh}.
  9468. *
  9469. * @augments Node
  9470. */
  9471. class BatchNode extends Node {
  9472. static get type() {
  9473. return 'BatchNode';
  9474. }
  9475. /**
  9476. * Constructs a new batch node.
  9477. *
  9478. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9479. */
  9480. constructor( batchMesh ) {
  9481. super( 'void' );
  9482. /**
  9483. * A reference to batched mesh.
  9484. *
  9485. * @type {BatchedMesh}
  9486. */
  9487. this.batchMesh = batchMesh;
  9488. /**
  9489. * The batching index node.
  9490. *
  9491. * @type {IndexNode?}
  9492. * @default null
  9493. */
  9494. this.batchingIdNode = null;
  9495. }
  9496. /**
  9497. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9498. * to predefined node variables for accumulation. That follows the same patterns
  9499. * like with morph and skinning nodes.
  9500. *
  9501. * @param {NodeBuilder} builder - The current node builder.
  9502. */
  9503. setup( builder ) {
  9504. if ( this.batchingIdNode === null ) {
  9505. if ( builder.getDrawIndex() === null ) {
  9506. this.batchingIdNode = instanceIndex;
  9507. } else {
  9508. this.batchingIdNode = drawIndex;
  9509. }
  9510. }
  9511. const getIndirectIndex = Fn( ( [ id ] ) => {
  9512. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9513. const x = int( id ).modInt( int( size ) );
  9514. const y = int( id ).div( int( size ) );
  9515. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9516. } ).setLayout( {
  9517. name: 'getIndirectIndex',
  9518. type: 'uint',
  9519. inputs: [
  9520. { name: 'id', type: 'int' }
  9521. ]
  9522. } );
  9523. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9524. const matricesTexture = this.batchMesh._matricesTexture;
  9525. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9526. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9527. const x = j.modInt( size );
  9528. const y = j.div( int( size ) );
  9529. const batchingMatrix = mat4(
  9530. textureLoad( matricesTexture, ivec2( x, y ) ),
  9531. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9532. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9533. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9534. );
  9535. const colorsTexture = this.batchMesh._colorsTexture;
  9536. if ( colorsTexture !== null ) {
  9537. const getBatchingColor = Fn( ( [ id ] ) => {
  9538. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9539. const j = id;
  9540. const x = j.modInt( size );
  9541. const y = j.div( size );
  9542. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9543. } ).setLayout( {
  9544. name: 'getBatchingColor',
  9545. type: 'vec3',
  9546. inputs: [
  9547. { name: 'id', type: 'int' }
  9548. ]
  9549. } );
  9550. const color = getBatchingColor( indirectId );
  9551. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9552. }
  9553. const bm = mat3( batchingMatrix );
  9554. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9555. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9556. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9557. normalLocal.assign( batchingNormal );
  9558. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9559. tangentLocal.mulAssign( bm );
  9560. }
  9561. }
  9562. }
  9563. /**
  9564. * TSL function for creating a batch node.
  9565. *
  9566. * @function
  9567. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9568. * @returns {BatchNode}
  9569. */
  9570. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9571. /** @module SkinningNode **/
  9572. const _frameId = new WeakMap();
  9573. /**
  9574. * This node implements the vertex transformation shader logic which is required
  9575. * for skinning/skeletal animation.
  9576. *
  9577. * @augments Node
  9578. */
  9579. class SkinningNode extends Node {
  9580. static get type() {
  9581. return 'SkinningNode';
  9582. }
  9583. /**
  9584. * Constructs a new skinning node.
  9585. *
  9586. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9587. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9588. */
  9589. constructor( skinnedMesh, useReference = false ) {
  9590. super( 'void' );
  9591. /**
  9592. * The skinned mesh.
  9593. *
  9594. * @type {SkinnedMesh}
  9595. */
  9596. this.skinnedMesh = skinnedMesh;
  9597. /**
  9598. * Whether to use reference nodes for internal skinned mesh related data or not.
  9599. * TODO: Explain the purpose of the property.
  9600. *
  9601. * @type {Boolean}
  9602. */
  9603. this.useReference = useReference;
  9604. /**
  9605. * The update type overwritten since skinning nodes are updated per object.
  9606. *
  9607. * @type {String}
  9608. */
  9609. this.updateType = NodeUpdateType.OBJECT;
  9610. //
  9611. /**
  9612. * The skin index attribute.
  9613. *
  9614. * @type {AttributeNode}
  9615. */
  9616. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9617. /**
  9618. * The skin weight attribute.
  9619. *
  9620. * @type {AttributeNode}
  9621. */
  9622. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9623. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9624. if ( useReference ) {
  9625. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9626. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9627. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9628. } else {
  9629. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9630. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9631. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9632. }
  9633. /**
  9634. * The bind matrix node.
  9635. *
  9636. * @type {Node<mat4>}
  9637. */
  9638. this.bindMatrixNode = bindMatrixNode;
  9639. /**
  9640. * The bind matrix inverse node.
  9641. *
  9642. * @type {Node<mat4>}
  9643. */
  9644. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9645. /**
  9646. * The bind matrices as a uniform buffer node.
  9647. *
  9648. * @type {Node}
  9649. */
  9650. this.boneMatricesNode = boneMatricesNode;
  9651. /**
  9652. * The previous bind matrices as a uniform buffer node.
  9653. * Required for computing motion vectors.
  9654. *
  9655. * @type {Node?}
  9656. * @default null
  9657. */
  9658. this.previousBoneMatricesNode = null;
  9659. }
  9660. /**
  9661. * Transforms the given vertex position via skinning.
  9662. *
  9663. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9664. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9665. * @return {Node<vec3>} The transformed vertex position.
  9666. */
  9667. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9668. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9669. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9670. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9671. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9672. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9673. // POSITION
  9674. const skinVertex = bindMatrixNode.mul( position );
  9675. const skinned = add(
  9676. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9677. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9678. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9679. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9680. );
  9681. return bindMatrixInverseNode.mul( skinned ).xyz;
  9682. }
  9683. /**
  9684. * Transforms the given vertex normal via skinning.
  9685. *
  9686. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9687. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9688. * @return {Node<vec3>} The transformed vertex normal.
  9689. */
  9690. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9691. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9692. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9693. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9694. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9695. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9696. // NORMAL
  9697. let skinMatrix = add(
  9698. skinWeightNode.x.mul( boneMatX ),
  9699. skinWeightNode.y.mul( boneMatY ),
  9700. skinWeightNode.z.mul( boneMatZ ),
  9701. skinWeightNode.w.mul( boneMatW )
  9702. );
  9703. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9704. return skinMatrix.transformDirection( normal ).xyz;
  9705. }
  9706. /**
  9707. * Transforms the given vertex normal via skinning.
  9708. *
  9709. * @param {NodeBuilder} builder - The current node builder.
  9710. * @return {Node<vec3>} The skinned position from the previous frame.
  9711. */
  9712. getPreviousSkinnedPosition( builder ) {
  9713. const skinnedMesh = builder.object;
  9714. if ( this.previousBoneMatricesNode === null ) {
  9715. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9716. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9717. }
  9718. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9719. }
  9720. /**
  9721. * Returns `true` if bone matrices from the previous frame are required.
  9722. *
  9723. * @param {NodeBuilder} builder - The current node builder.
  9724. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9725. */
  9726. needsPreviousBoneMatrices( builder ) {
  9727. const mrt = builder.renderer.getMRT();
  9728. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9729. }
  9730. /**
  9731. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9732. *
  9733. * @param {NodeBuilder} builder - The current node builder.
  9734. */
  9735. setup( builder ) {
  9736. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9737. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9738. }
  9739. const skinPosition = this.getSkinnedPosition();
  9740. positionLocal.assign( skinPosition );
  9741. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9742. const skinNormal = this.getSkinnedNormal();
  9743. normalLocal.assign( skinNormal );
  9744. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9745. tangentLocal.assign( skinNormal );
  9746. }
  9747. }
  9748. }
  9749. /**
  9750. * Generates the code snippet of the skinning node.
  9751. *
  9752. * @param {NodeBuilder} builder - The current node builder.
  9753. * @param {String} output - The current output.
  9754. * @return {String} The generated code snippet.
  9755. */
  9756. generate( builder, output ) {
  9757. if ( output !== 'void' ) {
  9758. return positionLocal.build( builder, output );
  9759. }
  9760. }
  9761. /**
  9762. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9763. *
  9764. * @param {NodeFrame} frame - The current node frame.
  9765. */
  9766. update( frame ) {
  9767. const object = this.useReference ? frame.object : this.skinnedMesh;
  9768. const skeleton = object.skeleton;
  9769. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9770. _frameId.set( skeleton, frame.frameId );
  9771. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9772. skeleton.update();
  9773. }
  9774. }
  9775. /**
  9776. * TSL function for creating a skinning node.
  9777. *
  9778. * @function
  9779. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9780. * @returns {SkinningNode}
  9781. */
  9782. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9783. /**
  9784. * TSL function for creating a skinning node with reference usage.
  9785. *
  9786. * @function
  9787. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9788. * @returns {SkinningNode}
  9789. */
  9790. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9791. /** @module LoopNode **/
  9792. /**
  9793. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9794. * ```js
  9795. * Loop( count, ( { i } ) => {
  9796. *
  9797. * } );
  9798. * ```
  9799. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9800. * ```js
  9801. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9802. *
  9803. * } );
  9804. *```
  9805. * Nested loops can be defined in a compacted form:
  9806. * ```js
  9807. * Loop( 10, 5, ( { i, j } ) => {
  9808. *
  9809. * } );
  9810. * ```
  9811. * Loops that should run backwards can be defined like so:
  9812. * ```js
  9813. * Loop( { start: 10 }, () => {} );
  9814. * ```
  9815. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9816. * @augments Node
  9817. */
  9818. class LoopNode extends Node {
  9819. static get type() {
  9820. return 'LoopNode';
  9821. }
  9822. /**
  9823. * Constructs a new loop node.
  9824. *
  9825. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9826. */
  9827. constructor( params = [] ) {
  9828. super();
  9829. this.params = params;
  9830. }
  9831. /**
  9832. * Returns a loop variable name based on an index. The pattern is
  9833. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9834. *
  9835. * @param {Number} index - The index.
  9836. * @return {String} The loop variable name.
  9837. */
  9838. getVarName( index ) {
  9839. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9840. }
  9841. /**
  9842. * Returns properties about this node.
  9843. *
  9844. * @param {NodeBuilder} builder - The current node builder.
  9845. * @return {Object} The node properties.
  9846. */
  9847. getProperties( builder ) {
  9848. const properties = builder.getNodeProperties( this );
  9849. if ( properties.stackNode !== undefined ) return properties;
  9850. //
  9851. const inputs = {};
  9852. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9853. const param = this.params[ i ];
  9854. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9855. const type = ( param.isNode !== true && param.type ) || 'int';
  9856. inputs[ name ] = expression( name, type );
  9857. }
  9858. const stack = builder.addStack(); // TODO: cache() it
  9859. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9860. properties.stackNode = stack;
  9861. builder.removeStack();
  9862. return properties;
  9863. }
  9864. /**
  9865. * This method is overwritten since the node type is inferred based on the loop configuration.
  9866. *
  9867. * @param {NodeBuilder} builder - The current node builder.
  9868. * @return {String} The node type.
  9869. */
  9870. getNodeType( builder ) {
  9871. const { returnsNode } = this.getProperties( builder );
  9872. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9873. }
  9874. setup( builder ) {
  9875. // setup properties
  9876. this.getProperties( builder );
  9877. }
  9878. generate( builder ) {
  9879. const properties = this.getProperties( builder );
  9880. const params = this.params;
  9881. const stackNode = properties.stackNode;
  9882. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9883. const param = params[ i ];
  9884. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9885. if ( param.isNode ) {
  9886. type = 'int';
  9887. name = this.getVarName( i );
  9888. start = '0';
  9889. end = param.build( builder, type );
  9890. condition = '<';
  9891. } else {
  9892. type = param.type || 'int';
  9893. name = param.name || this.getVarName( i );
  9894. start = param.start;
  9895. end = param.end;
  9896. condition = param.condition;
  9897. update = param.update;
  9898. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9899. else if ( start && start.isNode ) start = start.build( builder, type );
  9900. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9901. else if ( end && end.isNode ) end = end.build( builder, type );
  9902. if ( start !== undefined && end === undefined ) {
  9903. start = start + ' - 1';
  9904. end = '0';
  9905. condition = '>=';
  9906. } else if ( end !== undefined && start === undefined ) {
  9907. start = '0';
  9908. condition = '<';
  9909. }
  9910. if ( condition === undefined ) {
  9911. if ( Number( start ) > Number( end ) ) {
  9912. condition = '>=';
  9913. } else {
  9914. condition = '<';
  9915. }
  9916. }
  9917. }
  9918. const internalParam = { start, end, condition };
  9919. //
  9920. const startSnippet = internalParam.start;
  9921. const endSnippet = internalParam.end;
  9922. let declarationSnippet = '';
  9923. let conditionalSnippet = '';
  9924. let updateSnippet = '';
  9925. if ( ! update ) {
  9926. if ( type === 'int' || type === 'uint' ) {
  9927. if ( condition.includes( '<' ) ) update = '++';
  9928. else update = '--';
  9929. } else {
  9930. if ( condition.includes( '<' ) ) update = '+= 1.';
  9931. else update = '-= 1.';
  9932. }
  9933. }
  9934. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9935. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9936. updateSnippet += name + ' ' + update;
  9937. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9938. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9939. }
  9940. const stackSnippet = stackNode.build( builder, 'void' );
  9941. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9942. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9943. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9944. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9945. }
  9946. builder.addFlowTab();
  9947. return returnsSnippet;
  9948. }
  9949. }
  9950. /**
  9951. * TSL function for creating a loop node.
  9952. *
  9953. * @function
  9954. * @param {...Any} params - A list of parameters.
  9955. * @returns {LoopNode}
  9956. */
  9957. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9958. /**
  9959. * TSL function for creating a `Continue()` expression.
  9960. *
  9961. * @function
  9962. * @returns {ExpressionNode}
  9963. */
  9964. const Continue = () => expression( 'continue' ).append();
  9965. /**
  9966. * TSL function for creating a `Break()` expression.
  9967. *
  9968. * @function
  9969. * @returns {ExpressionNode}
  9970. */
  9971. const Break = () => expression( 'break' ).append();
  9972. // Deprecated
  9973. /**
  9974. * @function
  9975. * @deprecated since r168. Use {@link Loop} instead.
  9976. *
  9977. * @param {...any} params
  9978. * @returns {LoopNode}
  9979. */
  9980. const loop = ( ...params ) => { // @deprecated, r168
  9981. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9982. return Loop( ...params );
  9983. };
  9984. /** @module MorphNode **/
  9985. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9986. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9987. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9988. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9989. const y = texelIndex.div( width );
  9990. const x = texelIndex.sub( y.mul( width ) );
  9991. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9992. return bufferAttrib.mul( influence );
  9993. } );
  9994. function getEntry( geometry ) {
  9995. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9996. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9997. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9998. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9999. // into an array of data textures. Each layer represents a single morph target.
  10000. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10001. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10002. let entry = _morphTextures.get( geometry );
  10003. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10004. if ( entry !== undefined ) entry.texture.dispose();
  10005. const morphTargets = geometry.morphAttributes.position || [];
  10006. const morphNormals = geometry.morphAttributes.normal || [];
  10007. const morphColors = geometry.morphAttributes.color || [];
  10008. let vertexDataCount = 0;
  10009. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10010. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10011. if ( hasMorphColors === true ) vertexDataCount = 3;
  10012. let width = geometry.attributes.position.count * vertexDataCount;
  10013. let height = 1;
  10014. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  10015. if ( width > maxTextureSize ) {
  10016. height = Math.ceil( width / maxTextureSize );
  10017. width = maxTextureSize;
  10018. }
  10019. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10020. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10021. bufferTexture.type = FloatType;
  10022. bufferTexture.needsUpdate = true;
  10023. // fill buffer
  10024. const vertexDataStride = vertexDataCount * 4;
  10025. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10026. const morphTarget = morphTargets[ i ];
  10027. const morphNormal = morphNormals[ i ];
  10028. const morphColor = morphColors[ i ];
  10029. const offset = width * height * 4 * i;
  10030. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10031. const stride = j * vertexDataStride;
  10032. if ( hasMorphPosition === true ) {
  10033. _morphVec4.fromBufferAttribute( morphTarget, j );
  10034. buffer[ offset + stride + 0 ] = _morphVec4.x;
  10035. buffer[ offset + stride + 1 ] = _morphVec4.y;
  10036. buffer[ offset + stride + 2 ] = _morphVec4.z;
  10037. buffer[ offset + stride + 3 ] = 0;
  10038. }
  10039. if ( hasMorphNormals === true ) {
  10040. _morphVec4.fromBufferAttribute( morphNormal, j );
  10041. buffer[ offset + stride + 4 ] = _morphVec4.x;
  10042. buffer[ offset + stride + 5 ] = _morphVec4.y;
  10043. buffer[ offset + stride + 6 ] = _morphVec4.z;
  10044. buffer[ offset + stride + 7 ] = 0;
  10045. }
  10046. if ( hasMorphColors === true ) {
  10047. _morphVec4.fromBufferAttribute( morphColor, j );
  10048. buffer[ offset + stride + 8 ] = _morphVec4.x;
  10049. buffer[ offset + stride + 9 ] = _morphVec4.y;
  10050. buffer[ offset + stride + 10 ] = _morphVec4.z;
  10051. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  10052. }
  10053. }
  10054. }
  10055. entry = {
  10056. count: morphTargetsCount,
  10057. texture: bufferTexture,
  10058. stride: vertexDataCount,
  10059. size: new Vector2( width, height )
  10060. };
  10061. _morphTextures.set( geometry, entry );
  10062. function disposeTexture() {
  10063. bufferTexture.dispose();
  10064. _morphTextures.delete( geometry );
  10065. geometry.removeEventListener( 'dispose', disposeTexture );
  10066. }
  10067. geometry.addEventListener( 'dispose', disposeTexture );
  10068. }
  10069. return entry;
  10070. }
  10071. /**
  10072. * This node implements the vertex transformation shader logic which is required
  10073. * for morph target animation.
  10074. *
  10075. * @augments Node
  10076. */
  10077. class MorphNode extends Node {
  10078. static get type() {
  10079. return 'MorphNode';
  10080. }
  10081. /**
  10082. * Constructs a new morph node.
  10083. *
  10084. * @param {Mesh} mesh - The mesh holding the morph targets.
  10085. */
  10086. constructor( mesh ) {
  10087. super( 'void' );
  10088. /**
  10089. * The mesh holding the morph targets.
  10090. *
  10091. * @type {Mesh}
  10092. */
  10093. this.mesh = mesh;
  10094. /**
  10095. * A uniform node which represents the morph base influence value.
  10096. *
  10097. * @type {UniformNode<float>}
  10098. */
  10099. this.morphBaseInfluence = uniform( 1 );
  10100. /**
  10101. * The update type overwritten since morph nodes are updated per object.
  10102. *
  10103. * @type {String}
  10104. */
  10105. this.updateType = NodeUpdateType.OBJECT;
  10106. }
  10107. /**
  10108. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  10109. *
  10110. * @param {NodeBuilder} builder - The current node builder.
  10111. */
  10112. setup( builder ) {
  10113. const { geometry } = builder;
  10114. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10115. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  10116. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10117. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10118. // nodes
  10119. const { texture: bufferMap, stride, size } = getEntry( geometry );
  10120. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  10121. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  10122. const width = int( size.width );
  10123. Loop( morphTargetsCount, ( { i } ) => {
  10124. const influence = float( 0 ).toVar();
  10125. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10126. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10127. } else {
  10128. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10129. }
  10130. if ( hasMorphPosition === true ) {
  10131. positionLocal.addAssign( getMorph( {
  10132. bufferMap,
  10133. influence,
  10134. stride,
  10135. width,
  10136. depth: i,
  10137. offset: int( 0 )
  10138. } ) );
  10139. }
  10140. if ( hasMorphNormals === true ) {
  10141. normalLocal.addAssign( getMorph( {
  10142. bufferMap,
  10143. influence,
  10144. stride,
  10145. width,
  10146. depth: i,
  10147. offset: int( 1 )
  10148. } ) );
  10149. }
  10150. } );
  10151. }
  10152. /**
  10153. * Updates the state of the morphed mesh by updating the base influence.
  10154. *
  10155. * @param {NodeFrame} frame - The current node frame.
  10156. */
  10157. update( /*frame*/ ) {
  10158. const morphBaseInfluence = this.morphBaseInfluence;
  10159. if ( this.mesh.geometry.morphTargetsRelative ) {
  10160. morphBaseInfluence.value = 1;
  10161. } else {
  10162. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10163. }
  10164. }
  10165. }
  10166. /**
  10167. * TSL function for creating a morph node.
  10168. *
  10169. * @function
  10170. * @param {Mesh} mesh - The mesh holding the morph targets.
  10171. * @returns {MorphNode}
  10172. */
  10173. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10174. /**
  10175. * Base class for lighting nodes.
  10176. *
  10177. * @augments Node
  10178. */
  10179. class LightingNode extends Node {
  10180. static get type() {
  10181. return 'LightingNode';
  10182. }
  10183. /**
  10184. * Constructs a new lighting node.
  10185. */
  10186. constructor() {
  10187. super( 'vec3' );
  10188. /**
  10189. * This flag can be used for type testing.
  10190. *
  10191. * @type {Boolean}
  10192. * @readonly
  10193. * @default true
  10194. */
  10195. this.isLightingNode = true;
  10196. }
  10197. }
  10198. /**
  10199. * A generic class that can be used by nodes which contribute
  10200. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10201. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10202. *
  10203. * @augments LightingNode
  10204. */
  10205. class AONode extends LightingNode {
  10206. static get type() {
  10207. return 'AONode';
  10208. }
  10209. /**
  10210. * Constructs a new AO node.
  10211. *
  10212. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  10213. */
  10214. constructor( aoNode = null ) {
  10215. super();
  10216. /**
  10217. * The ambient occlusion node.
  10218. *
  10219. * @type {Node<float>?}
  10220. * @default null
  10221. */
  10222. this.aoNode = aoNode;
  10223. }
  10224. setup( builder ) {
  10225. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10226. }
  10227. }
  10228. /**
  10229. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  10230. * by adding lighting specific context data. It represents the runtime context of
  10231. * {@link LightsNode}.
  10232. *
  10233. * @augments ContextNode
  10234. */
  10235. class LightingContextNode extends ContextNode {
  10236. static get type() {
  10237. return 'LightingContextNode';
  10238. }
  10239. /**
  10240. * Constructs a new lighting context node.
  10241. *
  10242. * @param {LightsNode} node - The lights node.
  10243. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  10244. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  10245. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  10246. */
  10247. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10248. super( node );
  10249. /**
  10250. * The current lighting model.
  10251. *
  10252. * @type {LightingModel?}
  10253. * @default null
  10254. */
  10255. this.lightingModel = lightingModel;
  10256. /**
  10257. * A backdrop node.
  10258. *
  10259. * @type {Node<vec3>?}
  10260. * @default null
  10261. */
  10262. this.backdropNode = backdropNode;
  10263. /**
  10264. * A backdrop alpha node.
  10265. *
  10266. * @type {Node<float>?}
  10267. * @default null
  10268. */
  10269. this.backdropAlphaNode = backdropAlphaNode;
  10270. this._value = null;
  10271. }
  10272. /**
  10273. * Returns a lighting context object.
  10274. *
  10275. * @return {{
  10276. * radiance: Node<vec3>,
  10277. * irradiance: Node<vec3>,
  10278. * iblIrradiance: Node<vec3>,
  10279. * ambientOcclusion: Node<float>,
  10280. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10281. * backdrop: Node<vec3>,
  10282. * backdropAlpha: Node<float>
  10283. * }} The lighting context object.
  10284. */
  10285. getContext() {
  10286. const { backdropNode, backdropAlphaNode } = this;
  10287. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10288. directSpecular = vec3().toVar( 'directSpecular' ),
  10289. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10290. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10291. const reflectedLight = {
  10292. directDiffuse,
  10293. directSpecular,
  10294. indirectDiffuse,
  10295. indirectSpecular
  10296. };
  10297. const context = {
  10298. radiance: vec3().toVar( 'radiance' ),
  10299. irradiance: vec3().toVar( 'irradiance' ),
  10300. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10301. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10302. reflectedLight,
  10303. backdrop: backdropNode,
  10304. backdropAlpha: backdropAlphaNode
  10305. };
  10306. return context;
  10307. }
  10308. setup( builder ) {
  10309. this.value = this._value || ( this._value = this.getContext() );
  10310. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10311. return super.setup( builder );
  10312. }
  10313. }
  10314. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10315. /**
  10316. * A generic class that can be used by nodes which contribute
  10317. * irradiance to the scene. E.g. a light map node can be used
  10318. * as input for this module. Used in {@link NodeMaterial}.
  10319. *
  10320. * @augments LightingNode
  10321. */
  10322. class IrradianceNode extends LightingNode {
  10323. static get type() {
  10324. return 'IrradianceNode';
  10325. }
  10326. /**
  10327. * Constructs a new irradiance node.
  10328. *
  10329. * @param {Node<vec3>} node - A node contributing irradiance.
  10330. */
  10331. constructor( node ) {
  10332. super();
  10333. /**
  10334. * A node contributing irradiance.
  10335. *
  10336. * @type {Node<vec3>}
  10337. */
  10338. this.node = node;
  10339. }
  10340. setup( builder ) {
  10341. builder.context.irradiance.addAssign( this.node );
  10342. }
  10343. }
  10344. /** @module ScreenNode **/
  10345. let screenSizeVec, viewportVec;
  10346. /**
  10347. * This node provides a collection of screen related metrics.
  10348. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10349. * resolution or viewport data as well as fragment or uv coordinates.
  10350. *
  10351. * @augments Node
  10352. */
  10353. class ScreenNode extends Node {
  10354. static get type() {
  10355. return 'ScreenNode';
  10356. }
  10357. /**
  10358. * Constructs a new screen node.
  10359. *
  10360. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10361. */
  10362. constructor( scope ) {
  10363. super();
  10364. /**
  10365. * The node represents different metric depending on which scope is selected.
  10366. *
  10367. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10368. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10369. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10370. * - `ScreenNode.UV`: Normalized coordinates.
  10371. *
  10372. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10373. */
  10374. this.scope = scope;
  10375. /**
  10376. * This flag can be used for type testing.
  10377. *
  10378. * @type {Boolean}
  10379. * @readonly
  10380. * @default true
  10381. */
  10382. this.isViewportNode = true;
  10383. }
  10384. /**
  10385. * This method is overwritten since the node type depends on the selected scope.
  10386. *
  10387. * @return {('vec2'|'vec4')} The node type.
  10388. */
  10389. getNodeType() {
  10390. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10391. else return 'vec2';
  10392. }
  10393. /**
  10394. * This method is overwritten since the node's update type depends on the selected scope.
  10395. *
  10396. * @return {NodeUpdateType} The update type.
  10397. */
  10398. getUpdateType() {
  10399. let updateType = NodeUpdateType.NONE;
  10400. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10401. updateType = NodeUpdateType.RENDER;
  10402. }
  10403. this.updateType = updateType;
  10404. return updateType;
  10405. }
  10406. /**
  10407. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10408. * from the current renderer.
  10409. *
  10410. * @param {NodeFrame} frame - A reference to the current node frame.
  10411. */
  10412. update( { renderer } ) {
  10413. const renderTarget = renderer.getRenderTarget();
  10414. if ( this.scope === ScreenNode.VIEWPORT ) {
  10415. if ( renderTarget !== null ) {
  10416. viewportVec.copy( renderTarget.viewport );
  10417. } else {
  10418. renderer.getViewport( viewportVec );
  10419. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10420. }
  10421. } else {
  10422. if ( renderTarget !== null ) {
  10423. screenSizeVec.width = renderTarget.width;
  10424. screenSizeVec.height = renderTarget.height;
  10425. } else {
  10426. renderer.getDrawingBufferSize( screenSizeVec );
  10427. }
  10428. }
  10429. }
  10430. setup( /*builder*/ ) {
  10431. const scope = this.scope;
  10432. let output = null;
  10433. if ( scope === ScreenNode.SIZE ) {
  10434. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10435. } else if ( scope === ScreenNode.VIEWPORT ) {
  10436. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10437. } else {
  10438. output = vec2( screenCoordinate.div( screenSize ) );
  10439. }
  10440. return output;
  10441. }
  10442. generate( builder ) {
  10443. if ( this.scope === ScreenNode.COORDINATE ) {
  10444. let coord = builder.getFragCoord();
  10445. if ( builder.isFlipY() ) {
  10446. // follow webgpu standards
  10447. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10448. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10449. }
  10450. return coord;
  10451. }
  10452. return super.generate( builder );
  10453. }
  10454. }
  10455. ScreenNode.COORDINATE = 'coordinate';
  10456. ScreenNode.VIEWPORT = 'viewport';
  10457. ScreenNode.SIZE = 'size';
  10458. ScreenNode.UV = 'uv';
  10459. // Screen
  10460. /**
  10461. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10462. *
  10463. * @type {ScreenNode<vec2>}
  10464. */
  10465. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10466. /**
  10467. * TSL object that represents the screen resolution in physical pixel units.
  10468. *
  10469. * @type {ScreenNode<vec2>}
  10470. */
  10471. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10472. /**
  10473. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10474. *
  10475. * @type {ScreenNode<vec2>}
  10476. */
  10477. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10478. // Viewport
  10479. /**
  10480. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10481. *
  10482. * @type {ScreenNode<vec4>}
  10483. */
  10484. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10485. /**
  10486. * TSL object that represents the viewport resolution in physical pixel units.
  10487. *
  10488. * @type {ScreenNode<vec2>}
  10489. */
  10490. const viewportSize = viewport.zw;
  10491. /**
  10492. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10493. *
  10494. * @type {ScreenNode<vec2>}
  10495. */
  10496. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10497. /**
  10498. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10499. *
  10500. * @type {ScreenNode<vec2>}
  10501. */
  10502. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10503. // Deprecated
  10504. /**
  10505. * @deprecated since r169. Use {@link screenSize} instead.
  10506. */
  10507. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10508. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10509. return screenSize;
  10510. }, 'vec2' ).once() )();
  10511. /**
  10512. * @deprecated since r168. Use {@link screenUV} instead.
  10513. */
  10514. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10515. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10516. return screenUV;
  10517. }, 'vec2' ).once() )();
  10518. /**
  10519. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10520. */
  10521. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10522. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10523. return screenUV.flipY();
  10524. }, 'vec2' ).once() )();
  10525. /** @module ViewportTextureNode **/
  10526. const _size$4 = /*@__PURE__*/ new Vector2();
  10527. /**
  10528. * A special type of texture node which represents the data of the current viewport
  10529. * as a texture. The module extracts data from the current bound framebuffer with
  10530. * a copy operation so no extra render pass is required to produce the texture data
  10531. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10532. * variety of effects like refractive or transmissive materials.
  10533. *
  10534. * @augments module:TextureNode~TextureNode
  10535. */
  10536. class ViewportTextureNode extends TextureNode {
  10537. static get type() {
  10538. return 'ViewportTextureNode';
  10539. }
  10540. /**
  10541. * Constructs a new viewport texture node.
  10542. *
  10543. * @param {Node} [uvNode=screenUV] - The uv node.
  10544. * @param {Node?} [levelNode=null] - The level node.
  10545. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10546. */
  10547. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10548. if ( framebufferTexture === null ) {
  10549. framebufferTexture = new FramebufferTexture();
  10550. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10551. }
  10552. super( framebufferTexture, uvNode, levelNode );
  10553. /**
  10554. * Whether to generate mipmaps or not.
  10555. *
  10556. * @type {Boolean}
  10557. * @default false
  10558. */
  10559. this.generateMipmaps = false;
  10560. /**
  10561. * This flag can be used for type testing.
  10562. *
  10563. * @type {Boolean}
  10564. * @readonly
  10565. * @default true
  10566. */
  10567. this.isOutputTextureNode = true;
  10568. /**
  10569. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10570. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10571. *
  10572. * @type {String}
  10573. * @default 'frame'
  10574. */
  10575. this.updateBeforeType = NodeUpdateType.FRAME;
  10576. }
  10577. updateBefore( frame ) {
  10578. const renderer = frame.renderer;
  10579. renderer.getDrawingBufferSize( _size$4 );
  10580. //
  10581. const framebufferTexture = this.value;
  10582. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10583. framebufferTexture.image.width = _size$4.width;
  10584. framebufferTexture.image.height = _size$4.height;
  10585. framebufferTexture.needsUpdate = true;
  10586. }
  10587. //
  10588. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10589. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10590. renderer.copyFramebufferToTexture( framebufferTexture );
  10591. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10592. }
  10593. clone() {
  10594. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10595. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10596. return viewportTextureNode;
  10597. }
  10598. }
  10599. /**
  10600. * TSL function for creating a viewport texture node.
  10601. *
  10602. * @function
  10603. * @param {Node} [uvNode=screenUV] - The uv node.
  10604. * @param {Node?} [levelNode=null] - The level node.
  10605. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10606. * @returns {ViewportTextureNode}
  10607. */
  10608. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10609. /**
  10610. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10611. *
  10612. * @function
  10613. * @param {Node} [uvNode=screenUV] - The uv node.
  10614. * @param {Node?} [levelNode=null] - The level node.
  10615. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10616. * @returns {ViewportTextureNode}
  10617. */
  10618. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10619. /** @module ViewportDepthTextureNode **/
  10620. let sharedDepthbuffer = null;
  10621. /**
  10622. * Represents the depth of the current viewport as a texture. This module
  10623. * can be used in combination with viewport texture to achieve effects
  10624. * that require depth evaluation.
  10625. *
  10626. * @augments module:ViewportTextureNode~ViewportTextureNode
  10627. */
  10628. class ViewportDepthTextureNode extends ViewportTextureNode {
  10629. static get type() {
  10630. return 'ViewportDepthTextureNode';
  10631. }
  10632. /**
  10633. * Constructs a new viewport depth texture node.
  10634. *
  10635. * @param {Node} [uvNode=screenUV] - The uv node.
  10636. * @param {Node?} [levelNode=null] - The level node.
  10637. */
  10638. constructor( uvNode = screenUV, levelNode = null ) {
  10639. if ( sharedDepthbuffer === null ) {
  10640. sharedDepthbuffer = new DepthTexture();
  10641. }
  10642. super( uvNode, levelNode, sharedDepthbuffer );
  10643. }
  10644. }
  10645. /**
  10646. * TSL function for a viewport depth texture node.
  10647. *
  10648. * @function
  10649. * @param {Node} [uvNode=screenUV] - The uv node.
  10650. * @param {Node?} [levelNode=null] - The level node.
  10651. * @returns {ViewportDepthTextureNode}
  10652. */
  10653. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10654. /** @module ViewportDepthNode **/
  10655. /**
  10656. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10657. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10658. * fragment or for depth evaluation purposes.
  10659. *
  10660. * @augments Node
  10661. */
  10662. class ViewportDepthNode extends Node {
  10663. static get type() {
  10664. return 'ViewportDepthNode';
  10665. }
  10666. /**
  10667. * Constructs a new viewport depth node.
  10668. *
  10669. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10670. * @param {Node?} [valueNode=null] - The value node.
  10671. */
  10672. constructor( scope, valueNode = null ) {
  10673. super( 'float' );
  10674. /**
  10675. * The node behaves differently depending on which scope is selected.
  10676. *
  10677. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10678. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10679. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10680. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10681. *
  10682. * @type {('depth'|'depthBase'|'linearDepth')}
  10683. */
  10684. this.scope = scope;
  10685. /**
  10686. * Can be used to define a custom depth value.
  10687. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10688. *
  10689. * @type {Node?}
  10690. * @default null
  10691. */
  10692. this.valueNode = valueNode;
  10693. /**
  10694. * This flag can be used for type testing.
  10695. *
  10696. * @type {Boolean}
  10697. * @readonly
  10698. * @default true
  10699. */
  10700. this.isViewportDepthNode = true;
  10701. }
  10702. generate( builder ) {
  10703. const { scope } = this;
  10704. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10705. return builder.getFragDepth();
  10706. }
  10707. return super.generate( builder );
  10708. }
  10709. setup( { camera } ) {
  10710. const { scope } = this;
  10711. const value = this.valueNode;
  10712. let node = null;
  10713. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10714. if ( value !== null ) {
  10715. node = depthBase().assign( value );
  10716. }
  10717. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10718. if ( camera.isPerspectiveCamera ) {
  10719. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10720. } else {
  10721. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10722. }
  10723. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10724. if ( value !== null ) {
  10725. if ( camera.isPerspectiveCamera ) {
  10726. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10727. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10728. } else {
  10729. node = value;
  10730. }
  10731. } else {
  10732. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10733. }
  10734. }
  10735. return node;
  10736. }
  10737. }
  10738. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10739. ViewportDepthNode.DEPTH = 'depth';
  10740. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10741. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10742. /**
  10743. * TSL function for converting a viewZ value to an orthographic depth value.
  10744. *
  10745. * @function
  10746. * @param {Node<float>} viewZ - The viewZ node.
  10747. * @param {Node<float>} near - The camera's near value.
  10748. * @param {Node<float>} far - The camera's far value.
  10749. * @returns {Node<float>}
  10750. */
  10751. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10752. /**
  10753. * TSL function for converting an orthographic depth value to a viewZ value.
  10754. *
  10755. * @function
  10756. * @param {Node<float>} depth - The orthographic depth.
  10757. * @param {Node<float>} near - The camera's near value.
  10758. * @param {Node<float>} far - The camera's far value.
  10759. * @returns {Node<float>}
  10760. */
  10761. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10762. /**
  10763. * TSL function for converting a viewZ value to a perspective depth value.
  10764. *
  10765. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10766. *
  10767. * @function
  10768. * @param {Node<float>} viewZ - The viewZ node.
  10769. * @param {Node<float>} near - The camera's near value.
  10770. * @param {Node<float>} far - The camera's far value.
  10771. * @returns {Node<float>}
  10772. */
  10773. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10774. /**
  10775. * TSL function for converting a perspective depth value to a viewZ value.
  10776. *
  10777. * @function
  10778. * @param {Node<float>} depth - The perspective depth.
  10779. * @param {Node<float>} near - The camera's near value.
  10780. * @param {Node<float>} far - The camera's far value.
  10781. * @returns {Node<float>}
  10782. */
  10783. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10784. /**
  10785. * TSL function for converting a viewZ value to a logarithmic depth value.
  10786. *
  10787. * @function
  10788. * @param {Node<float>} viewZ - The viewZ node.
  10789. * @param {Node<float>} near - The camera's near value.
  10790. * @param {Node<float>} far - The camera's far value.
  10791. * @returns {Node<float>}
  10792. */
  10793. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10794. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10795. // The final logarithmic depth formula used here is adapted from one described in an
  10796. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10797. // which was an improvement upon an earlier formula one described in an
  10798. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10799. // Ulrich's formula is the following:
  10800. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10801. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10802. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10803. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10804. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10805. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10806. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10807. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10808. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10809. // Outerra eventually made another improvement to their original "C-constant" variant,
  10810. // but it still does not incorporate the camera near plane (for this version,
  10811. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10812. // Here we make 4 changes to Ulrich's formula:
  10813. // 1. Clamp the camera near plane so we don't divide by 0.
  10814. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10815. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10816. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10817. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10818. // so we do the same here, hence the 'viewZ.negate()' call.
  10819. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10820. near = near.max( 1e-6 ).toVar();
  10821. const numerator = log2( viewZ.negate().div( near ) );
  10822. const denominator = log2( far.div( near ) );
  10823. return numerator.div( denominator );
  10824. };
  10825. /**
  10826. * TSL function for converting a logarithmic depth value to a viewZ value.
  10827. *
  10828. * @function
  10829. * @param {Node<float>} depth - The logarithmic depth.
  10830. * @param {Node<float>} near - The camera's near value.
  10831. * @param {Node<float>} far - The camera's far value.
  10832. * @returns {Node<float>}
  10833. */
  10834. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10835. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10836. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10837. // a negative viewZ).
  10838. const exponent = depth.mul( log( far.div( near ) ) );
  10839. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10840. };
  10841. /**
  10842. * TSL function for defining a value for the current fragment's depth.
  10843. *
  10844. * @function
  10845. * @param {Node<float>} value - The depth value to set.
  10846. * @returns {ViewportDepthNode<float>}
  10847. */
  10848. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10849. /**
  10850. * TSL object that represents the depth value for the current fragment.
  10851. *
  10852. * @type {ViewportDepthNode}
  10853. */
  10854. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10855. /**
  10856. * TSL function for converting a perspective depth value to linear depth.
  10857. *
  10858. * @function
  10859. * @param {Node<float>} value - The perspective depth.
  10860. * @returns {ViewportDepthNode<float>}
  10861. */
  10862. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10863. /**
  10864. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10865. *
  10866. * @type {ViewportDepthNode}
  10867. */
  10868. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10869. depth.assign = ( value ) => depthBase( value );
  10870. /** @module BuiltinNode **/
  10871. /**
  10872. * The node allows to set values for built-in shader variables. That is
  10873. * required for features like hardware-accelerated vertex clipping.
  10874. *
  10875. * @augments Node
  10876. */
  10877. class BuiltinNode extends Node {
  10878. /**
  10879. * Constructs a new builtin node.
  10880. *
  10881. * @param {String} name - The name of the built-in shader variable.
  10882. */
  10883. constructor( name ) {
  10884. super( 'float' );
  10885. /**
  10886. * The name of the built-in shader variable.
  10887. *
  10888. * @type {String}
  10889. */
  10890. this.name = name;
  10891. /**
  10892. * This flag can be used for type testing.
  10893. *
  10894. * @type {Boolean}
  10895. * @readonly
  10896. * @default true
  10897. */
  10898. this.isBuiltinNode = true;
  10899. }
  10900. /**
  10901. * Generates the code snippet of the builtin node.
  10902. *
  10903. * @param {NodeBuilder} builder - The current node builder.
  10904. * @return {String} The generated code snippet.
  10905. */
  10906. generate( /* builder */ ) {
  10907. return this.name;
  10908. }
  10909. }
  10910. /**
  10911. * TSL function for creating a builtin node.
  10912. *
  10913. * @function
  10914. * @param {String} name - The name of the built-in shader variable.
  10915. * @returns {BuiltinNode}
  10916. */
  10917. const builtin = nodeProxy( BuiltinNode );
  10918. /** @module ClippingNode **/
  10919. /**
  10920. * ```
  10921. * This node is used in {@link NodeMaterial} to setup the clipping
  10922. * which can happen hardware-accelerated (if supported) and optionally
  10923. * use alpha-to-coverage for anti-aliasing clipped edges.
  10924. * ```
  10925. * @augments Node
  10926. */
  10927. class ClippingNode extends Node {
  10928. static get type() {
  10929. return 'ClippingNode';
  10930. }
  10931. /**
  10932. * Constructs a new clipping node.
  10933. *
  10934. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10935. * the selected scope influences the behavior of the node and what type of code is generated.
  10936. */
  10937. constructor( scope = ClippingNode.DEFAULT ) {
  10938. super();
  10939. /**
  10940. * The node's scope. Similar to other nodes, the selected scope influences
  10941. * the behavior of the node and what type of code is generated.
  10942. *
  10943. * @type {('default'|'hardware'|'alphaToCoverage')}
  10944. */
  10945. this.scope = scope;
  10946. }
  10947. /**
  10948. * Setups the node depending on the selected scope.
  10949. *
  10950. * @param {NodeBuilder} builder - The current node builder.
  10951. * @return {Node} The result node.
  10952. */
  10953. setup( builder ) {
  10954. super.setup( builder );
  10955. const clippingContext = builder.clippingContext;
  10956. const { intersectionPlanes, unionPlanes } = clippingContext;
  10957. this.hardwareClipping = builder.material.hardwareClipping;
  10958. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10959. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10960. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10961. return this.setupHardwareClipping( unionPlanes, builder );
  10962. } else {
  10963. return this.setupDefault( intersectionPlanes, unionPlanes );
  10964. }
  10965. }
  10966. /**
  10967. * Setups alpha to coverage.
  10968. *
  10969. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10970. * @param {Array<Vector4>} unionPlanes - The union planes.
  10971. * @return {Node} The result node.
  10972. */
  10973. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10974. return Fn( () => {
  10975. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10976. const distanceGradient = float().toVar( 'distanceToGradient' );
  10977. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10978. const numUnionPlanes = unionPlanes.length;
  10979. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10980. const clippingPlanes = uniformArray( unionPlanes );
  10981. Loop( numUnionPlanes, ( { i } ) => {
  10982. const plane = clippingPlanes.element( i );
  10983. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10984. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10985. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10986. } );
  10987. }
  10988. const numIntersectionPlanes = intersectionPlanes.length;
  10989. if ( numIntersectionPlanes > 0 ) {
  10990. const clippingPlanes = uniformArray( intersectionPlanes );
  10991. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10992. Loop( numIntersectionPlanes, ( { i } ) => {
  10993. const plane = clippingPlanes.element( i );
  10994. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10995. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10996. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10997. } );
  10998. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10999. }
  11000. diffuseColor.a.mulAssign( clipOpacity );
  11001. diffuseColor.a.equal( 0.0 ).discard();
  11002. } )();
  11003. }
  11004. /**
  11005. * Setups the default clipping.
  11006. *
  11007. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11008. * @param {Array<Vector4>} unionPlanes - The union planes.
  11009. * @return {Node} The result node.
  11010. */
  11011. setupDefault( intersectionPlanes, unionPlanes ) {
  11012. return Fn( () => {
  11013. const numUnionPlanes = unionPlanes.length;
  11014. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11015. const clippingPlanes = uniformArray( unionPlanes );
  11016. Loop( numUnionPlanes, ( { i } ) => {
  11017. const plane = clippingPlanes.element( i );
  11018. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  11019. } );
  11020. }
  11021. const numIntersectionPlanes = intersectionPlanes.length;
  11022. if ( numIntersectionPlanes > 0 ) {
  11023. const clippingPlanes = uniformArray( intersectionPlanes );
  11024. const clipped = bool( true ).toVar( 'clipped' );
  11025. Loop( numIntersectionPlanes, ( { i } ) => {
  11026. const plane = clippingPlanes.element( i );
  11027. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  11028. } );
  11029. clipped.discard();
  11030. }
  11031. } )();
  11032. }
  11033. /**
  11034. * Setups hardware clipping.
  11035. *
  11036. * @param {Array<Vector4>} unionPlanes - The union planes.
  11037. * @param {NodeBuilder} builder - The current node builder.
  11038. * @return {Node} The result node.
  11039. */
  11040. setupHardwareClipping( unionPlanes, builder ) {
  11041. const numUnionPlanes = unionPlanes.length;
  11042. builder.enableHardwareClipping( numUnionPlanes );
  11043. return Fn( () => {
  11044. const clippingPlanes = uniformArray( unionPlanes );
  11045. const hw_clip_distances = builtin( builder.getClipDistance() );
  11046. Loop( numUnionPlanes, ( { i } ) => {
  11047. const plane = clippingPlanes.element( i );
  11048. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  11049. hw_clip_distances.element( i ).assign( distance );
  11050. } );
  11051. } )();
  11052. }
  11053. }
  11054. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  11055. ClippingNode.DEFAULT = 'default';
  11056. ClippingNode.HARDWARE = 'hardware';
  11057. /**
  11058. * TSL function for setting up the default clipping logic.
  11059. *
  11060. * @function
  11061. * @returns {ClippingNode}
  11062. */
  11063. const clipping = () => nodeObject( new ClippingNode() );
  11064. /**
  11065. * TSL function for setting up alpha to coverage.
  11066. *
  11067. * @function
  11068. * @returns {ClippingNode}
  11069. */
  11070. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  11071. /**
  11072. * TSL function for setting up hardware-based clipping.
  11073. *
  11074. * @function
  11075. * @returns {ClippingNode}
  11076. */
  11077. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  11078. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  11079. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  11080. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11081. 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 ) ) ) ) ) );
  11082. } );
  11083. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11084. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  11085. } );
  11086. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  11087. // Find the discretized derivatives of our coordinates
  11088. const maxDeriv = max$1(
  11089. length( dFdx( position.xyz ) ),
  11090. length( dFdy( position.xyz ) )
  11091. );
  11092. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  11093. // Find two nearest log-discretized noise scales
  11094. const pixScales = vec2(
  11095. exp2( floor( log2( pixScale ) ) ),
  11096. exp2( ceil( log2( pixScale ) ) )
  11097. );
  11098. // Compute alpha thresholds at our two noise scales
  11099. const alpha = vec2(
  11100. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  11101. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  11102. );
  11103. // Factor to interpolate lerp with
  11104. const lerpFactor = fract( log2( pixScale ) );
  11105. // Interpolate alpha threshold from noise at two scales
  11106. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  11107. // Pass into CDF to compute uniformly distrib threshold
  11108. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  11109. const cases = vec3(
  11110. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  11111. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  11112. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  11113. // Find our final, uniformly distributed alpha threshold (ατ)
  11114. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  11115. // Avoids ατ == 0. Could also do ατ =1-ατ
  11116. return clamp( threshold, 1.0e-6, 1.0 );
  11117. } ).setLayout( {
  11118. name: 'getAlphaHashThreshold',
  11119. type: 'float',
  11120. inputs: [
  11121. { name: 'position', type: 'vec3' }
  11122. ]
  11123. } );
  11124. /**
  11125. * Base class for all node materials.
  11126. *
  11127. * @augments Material
  11128. */
  11129. class NodeMaterial extends Material {
  11130. static get type() {
  11131. return 'NodeMaterial';
  11132. }
  11133. /**
  11134. * Represents the type of the node material.
  11135. *
  11136. * @type {String}
  11137. */
  11138. get type() {
  11139. return this.constructor.type;
  11140. }
  11141. set type( _value ) { /* */ }
  11142. /**
  11143. * Constructs a new node material.
  11144. */
  11145. constructor() {
  11146. super();
  11147. /**
  11148. * This flag can be used for type testing.
  11149. *
  11150. * @type {Boolean}
  11151. * @readonly
  11152. * @default true
  11153. */
  11154. this.isNodeMaterial = true;
  11155. /**
  11156. * Whether this material is affected by fog or not.
  11157. *
  11158. * @type {Boolean}
  11159. * @default true
  11160. */
  11161. this.fog = true;
  11162. /**
  11163. * Whether this material is affected by lights or not.
  11164. *
  11165. * @type {Boolean}
  11166. * @default false
  11167. */
  11168. this.lights = false;
  11169. /**
  11170. * Whether this material uses hardware clipping or not.
  11171. * This property is managed by the engine and should not be
  11172. * modified by apps.
  11173. *
  11174. * @type {Boolean}
  11175. * @default false
  11176. */
  11177. this.hardwareClipping = false;
  11178. /**
  11179. * Node materials which set their `lights` property to `true`
  11180. * are affected by all lights of the scene. Sometimes selective
  11181. * lighting is wanted which means only _some_ lights in the scene
  11182. * affect a material. This can be achieved by creating an instance
  11183. * of {@link module:LightsNode~LightsNode} with a list of selective
  11184. * lights and assign the node to this property.
  11185. *
  11186. * ```js
  11187. * const customLightsNode = lights( [ light1, light2 ] );
  11188. * material.lightsNode = customLightsNode;
  11189. * ```
  11190. *
  11191. * @type {LightsNode?}
  11192. * @default null
  11193. */
  11194. this.lightsNode = null;
  11195. /**
  11196. * The environment of node materials can be defined by an environment
  11197. * map assigned to the `envMap` property or by `Scene.environment`
  11198. * if the node material is a PBR material. This node property allows to overwrite
  11199. * the default behavior and define the environment with a custom node.
  11200. *
  11201. * ```js
  11202. * material.envNode = pmremTexture( renderTarget.texture );
  11203. * ```
  11204. *
  11205. * @type {Node<vec3>?}
  11206. * @default null
  11207. */
  11208. this.envNode = null;
  11209. /**
  11210. * The lighting of node materials might be influenced by ambient occlusion.
  11211. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11212. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11213. * the default and define the ambient occlusion with a custom node instead.
  11214. *
  11215. * If you don't want to overwrite the diffuse color but modify the existing
  11216. * values instead, use {@link module:MaterialNode.materialAO}.
  11217. *
  11218. * @type {Node<float>?}
  11219. * @default null
  11220. */
  11221. this.aoNode = null;
  11222. /**
  11223. * The diffuse color of node materials is by default inferred from the
  11224. * `color` and `map` properties. This node property allows to overwrite the default
  11225. * and define the diffuse color with a node instead.
  11226. *
  11227. * ```js
  11228. * material.colorNode = color( 0xff0000 ); // define red color
  11229. * ```
  11230. *
  11231. * If you don't want to overwrite the diffuse color but modify the existing
  11232. * values instead, use {@link module:MaterialNode.materialColor}.
  11233. *
  11234. * ```js
  11235. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11236. * ```
  11237. *
  11238. * @type {Node<vec3>?}
  11239. * @default null
  11240. */
  11241. this.colorNode = null;
  11242. /**
  11243. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11244. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11245. * and define the normals with a node instead.
  11246. *
  11247. * If you don't want to overwrite the normals but modify the existing values instead,
  11248. * use {@link module:MaterialNode.materialNormal}.
  11249. *
  11250. * @type {Node<vec3>?}
  11251. * @default null
  11252. */
  11253. this.normalNode = null;
  11254. /**
  11255. * The opacity of node materials is by default inferred from the `opacity`
  11256. * and `alphaMap` properties. This node property allows to overwrite the default
  11257. * and define the opacity with a node instead.
  11258. *
  11259. * If you don't want to overwrite the normals but modify the existing
  11260. * value instead, use {@link module:MaterialNode.materialOpacity}.
  11261. *
  11262. * @type {Node<float>?}
  11263. * @default null
  11264. */
  11265. this.opacityNode = null;
  11266. /**
  11267. * This node can be used to to implement a variety of filter-like effects. The idea is
  11268. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11269. * to create an arbitrary effect and then assign the node composition to this property.
  11270. * Everything behind the object using this material will now be affected by a filter.
  11271. *
  11272. * ```js
  11273. * const material = new NodeMaterial()
  11274. * material.transparent = true;
  11275. *
  11276. * // everything behind the object will be monochromatic
  11277. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  11278. * ```
  11279. *
  11280. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11281. *
  11282. * @type {Node<vec3>?}
  11283. * @default null
  11284. */
  11285. this.backdropNode = null;
  11286. /**
  11287. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11288. *
  11289. * @type {Node<float>?}
  11290. * @default null
  11291. */
  11292. this.backdropAlphaNode = null;
  11293. /**
  11294. * The alpha test of node materials is by default inferred from the `alphaTest`
  11295. * property. This node property allows to overwrite the default and define the
  11296. * alpha test with a node instead.
  11297. *
  11298. * If you don't want to overwrite the alpha test but modify the existing
  11299. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11300. *
  11301. * @type {Node<float>?}
  11302. * @default null
  11303. */
  11304. this.alphaTestNode = null;
  11305. /**
  11306. * The local vertex positions are computed based on multiple factors like the
  11307. * attribute data, morphing or skinning. This node property allows to overwrite
  11308. * the default and define local vertex positions with nodes instead.
  11309. *
  11310. * If you don't want to overwrite the vertex positions but modify the existing
  11311. * values instead, use {@link module:Position.positionLocal}.
  11312. *
  11313. *```js
  11314. * material.positionNode = positionLocal.add( displace );
  11315. * ```
  11316. *
  11317. * @type {Node<vec3>?}
  11318. * @default null
  11319. */
  11320. this.positionNode = null;
  11321. /**
  11322. * This node property is intended for logic which modifies geometry data once or per animation step.
  11323. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11324. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11325. * can be implemented.
  11326. *
  11327. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11328. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11329. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11330. * eventually assigned to `geometryNode`.
  11331. *
  11332. * @type {Function}
  11333. * @default null
  11334. */
  11335. this.geometryNode = null;
  11336. /**
  11337. * Allows to overwrite depth values in the fragment shader.
  11338. *
  11339. * @type {Node<float>?}
  11340. * @default null
  11341. */
  11342. this.depthNode = null;
  11343. /**
  11344. * Allows to overwrite the position used for shadow map rendering which
  11345. * is by default {@link module:Position.positionWorld}, the vertex position
  11346. * in world space.
  11347. *
  11348. * @type {Node<float>?}
  11349. * @default null
  11350. */
  11351. this.shadowPositionNode = null;
  11352. /**
  11353. * This node can be used to influence how an object using this node material
  11354. * receive shadows.
  11355. *
  11356. * ```js
  11357. * const totalShadows = float( 1 ).toVar();
  11358. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11359. * totalShadows.mulAssign( shadow );
  11360. * //return float( 1 ); // bypass received shadows
  11361. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11362. * } );
  11363. *
  11364. * @type {Node<vec4>?}
  11365. * @default null
  11366. */
  11367. this.receivedShadowNode = null;
  11368. /**
  11369. * This node can be used to influence how an object using this node material
  11370. * casts shadows. To apply a color to shadows, you can simply do:
  11371. *
  11372. * ```js
  11373. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11374. * ```
  11375. *
  11376. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11377. * is also common to use the property with `Fn` function so checks are performed
  11378. * per fragment.
  11379. *
  11380. * ```js
  11381. * materialCustomShadow.castShadowNode = Fn( () => {
  11382. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11383. * return materialColor;
  11384. * } )();
  11385. * ```
  11386. *
  11387. * @type {Node<vec4>?}
  11388. * @default null
  11389. */
  11390. this.castShadowNode = null;
  11391. /**
  11392. * This node can be used to define the final output of the material.
  11393. *
  11394. * TODO: Explain the differences to `fragmentNode`.
  11395. *
  11396. * @type {Node<vec4>?}
  11397. * @default null
  11398. */
  11399. this.outputNode = null;
  11400. /**
  11401. * MRT configuration is done on renderer or pass level. This node allows to
  11402. * overwrite what values are written into MRT targets on material level. This
  11403. * can be useful for implementing selective FX features that should only affect
  11404. * specific objects.
  11405. *
  11406. * @type {MRTNode?}
  11407. * @default null
  11408. */
  11409. this.mrtNode = null;
  11410. /**
  11411. * This node property can be used if you need complete freedom in implementing
  11412. * the fragment shader. Assigning a node will replace the built-in material
  11413. * logic used in the fragment stage.
  11414. *
  11415. * @type {Node<vec4>?}
  11416. * @default null
  11417. */
  11418. this.fragmentNode = null;
  11419. /**
  11420. * This node property can be used if you need complete freedom in implementing
  11421. * the vertex shader. Assigning a node will replace the built-in material logic
  11422. * used in the vertex stage.
  11423. *
  11424. * @type {Node<vec4>?}
  11425. * @default null
  11426. */
  11427. this.vertexNode = null;
  11428. }
  11429. /**
  11430. * Allows to define a custom cache key that influence the material key computation
  11431. * for render objects.
  11432. *
  11433. * @return {String} The custom cache key.
  11434. */
  11435. customProgramCacheKey() {
  11436. return this.type + getCacheKey$1( this );
  11437. }
  11438. /**
  11439. * Builds this material with the given node builder.
  11440. *
  11441. * @param {NodeBuilder} builder - The current node builder.
  11442. */
  11443. build( builder ) {
  11444. this.setup( builder );
  11445. }
  11446. /**
  11447. * Setups a node material observer with the given builder.
  11448. *
  11449. * @param {NodeBuilder} builder - The current node builder.
  11450. * @return {NodeMaterialObserver} The node material observer.
  11451. */
  11452. setupObserver( builder ) {
  11453. return new NodeMaterialObserver( builder );
  11454. }
  11455. /**
  11456. * Setups the vertex and fragment stage of this node material.
  11457. *
  11458. * @param {NodeBuilder} builder - The current node builder.
  11459. */
  11460. setup( builder ) {
  11461. builder.context.setupNormal = () => this.setupNormal( builder );
  11462. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11463. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11464. const renderer = builder.renderer;
  11465. const renderTarget = renderer.getRenderTarget();
  11466. // < VERTEX STAGE >
  11467. builder.addStack();
  11468. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11469. builder.stack.outputNode = vertexNode;
  11470. this.setupHardwareClipping( builder );
  11471. if ( this.geometryNode !== null ) {
  11472. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11473. }
  11474. builder.addFlow( 'vertex', builder.removeStack() );
  11475. // < FRAGMENT STAGE >
  11476. builder.addStack();
  11477. let resultNode;
  11478. const clippingNode = this.setupClipping( builder );
  11479. if ( this.depthWrite === true || this.depthTest === true ) {
  11480. // only write depth if depth buffer is configured
  11481. if ( renderTarget !== null ) {
  11482. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11483. } else {
  11484. if ( renderer.depth === true ) this.setupDepth( builder );
  11485. }
  11486. }
  11487. if ( this.fragmentNode === null ) {
  11488. this.setupDiffuseColor( builder );
  11489. this.setupVariants( builder );
  11490. const outgoingLightNode = this.setupLighting( builder );
  11491. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11492. // force unsigned floats - useful for RenderTargets
  11493. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11494. resultNode = this.setupOutput( builder, basicOutput );
  11495. // OUTPUT NODE
  11496. output.assign( resultNode );
  11497. //
  11498. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11499. // MRT
  11500. if ( renderTarget !== null ) {
  11501. const mrt = renderer.getMRT();
  11502. const materialMRT = this.mrtNode;
  11503. if ( mrt !== null ) {
  11504. resultNode = mrt;
  11505. if ( materialMRT !== null ) {
  11506. resultNode = mrt.merge( materialMRT );
  11507. }
  11508. } else if ( materialMRT !== null ) {
  11509. resultNode = materialMRT;
  11510. }
  11511. }
  11512. } else {
  11513. let fragmentNode = this.fragmentNode;
  11514. if ( fragmentNode.isOutputStructNode !== true ) {
  11515. fragmentNode = vec4( fragmentNode );
  11516. }
  11517. resultNode = this.setupOutput( builder, fragmentNode );
  11518. }
  11519. builder.stack.outputNode = resultNode;
  11520. builder.addFlow( 'fragment', builder.removeStack() );
  11521. // < OBSERVER >
  11522. builder.observer = this.setupObserver( builder );
  11523. }
  11524. /**
  11525. * Setups the clipping node.
  11526. *
  11527. * @param {NodeBuilder} builder - The current node builder.
  11528. * @return {ClippingNode} The clipping node.
  11529. */
  11530. setupClipping( builder ) {
  11531. if ( builder.clippingContext === null ) return null;
  11532. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11533. let result = null;
  11534. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11535. const samples = builder.renderer.samples;
  11536. if ( this.alphaToCoverage && samples > 1 ) {
  11537. // to be added to flow when the color/alpha value has been determined
  11538. result = clippingAlpha();
  11539. } else {
  11540. builder.stack.add( clipping() );
  11541. }
  11542. }
  11543. return result;
  11544. }
  11545. /**
  11546. * Setups the hardware clipping if available on the current device.
  11547. *
  11548. * @param {NodeBuilder} builder - The current node builder.
  11549. */
  11550. setupHardwareClipping( builder ) {
  11551. this.hardwareClipping = false;
  11552. if ( builder.clippingContext === null ) return;
  11553. const candidateCount = builder.clippingContext.unionPlanes.length;
  11554. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11555. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11556. builder.stack.add( hardwareClipping() );
  11557. this.hardwareClipping = true;
  11558. }
  11559. return;
  11560. }
  11561. /**
  11562. * Setups the depth of this material.
  11563. *
  11564. * @param {NodeBuilder} builder - The current node builder.
  11565. */
  11566. setupDepth( builder ) {
  11567. const { renderer, camera } = builder;
  11568. // Depth
  11569. let depthNode = this.depthNode;
  11570. if ( depthNode === null ) {
  11571. const mrt = renderer.getMRT();
  11572. if ( mrt && mrt.has( 'depth' ) ) {
  11573. depthNode = mrt.get( 'depth' );
  11574. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11575. if ( camera.isPerspectiveCamera ) {
  11576. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11577. } else {
  11578. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11579. }
  11580. }
  11581. }
  11582. if ( depthNode !== null ) {
  11583. depth.assign( depthNode ).append();
  11584. }
  11585. }
  11586. /**
  11587. * Setups the position node in view space. This method exists
  11588. * so derived node materials can modify the implementation e.g. sprite materials.
  11589. *
  11590. * @param {NodeBuilder} builder - The current node builder.
  11591. * @return {Node<vec3>} The position in view space.
  11592. */
  11593. setupPositionView( /*builder*/ ) {
  11594. return modelViewMatrix.mul( positionLocal ).xyz;
  11595. }
  11596. /**
  11597. * Setups the position in clip space.
  11598. *
  11599. * @param {NodeBuilder} builder - The current node builder.
  11600. * @return {Node<vec4>} The position in view space.
  11601. */
  11602. setupModelViewProjection( /*builder*/ ) {
  11603. return cameraProjectionMatrix.mul( positionView );
  11604. }
  11605. /**
  11606. * Setups the logic for the vertex stage.
  11607. *
  11608. * @param {NodeBuilder} builder - The current node builder.
  11609. * @return {Node<vec4>} The position in clip space.
  11610. */
  11611. setupVertex( builder ) {
  11612. builder.addStack();
  11613. this.setupPosition( builder );
  11614. builder.context.vertex = builder.removeStack();
  11615. return modelViewProjection;
  11616. }
  11617. /**
  11618. * Setups the computation of the position in local space.
  11619. *
  11620. * @param {NodeBuilder} builder - The current node builder.
  11621. * @return {Node<vec3>} The position in local space.
  11622. */
  11623. setupPosition( builder ) {
  11624. const { object, geometry } = builder;
  11625. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11626. morphReference( object ).append();
  11627. }
  11628. if ( object.isSkinnedMesh === true ) {
  11629. skinningReference( object ).append();
  11630. }
  11631. if ( this.displacementMap ) {
  11632. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11633. const displacementScale = materialReference( 'displacementScale', 'float' );
  11634. const displacementBias = materialReference( 'displacementBias', 'float' );
  11635. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11636. }
  11637. if ( object.isBatchedMesh ) {
  11638. batch( object ).append();
  11639. }
  11640. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11641. instancedMesh( object ).append();
  11642. }
  11643. if ( this.positionNode !== null ) {
  11644. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11645. }
  11646. return positionLocal;
  11647. }
  11648. /**
  11649. * Setups the computation of the material's diffuse color.
  11650. *
  11651. * @param {NodeBuilder} builder - The current node builder.
  11652. * @param {BufferGeometry} geometry - The geometry.
  11653. */
  11654. setupDiffuseColor( { object, geometry } ) {
  11655. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11656. // VERTEX COLORS
  11657. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11658. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11659. }
  11660. // Instanced colors
  11661. if ( object.instanceColor ) {
  11662. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11663. colorNode = instanceColor.mul( colorNode );
  11664. }
  11665. if ( object.isBatchedMesh && object._colorsTexture ) {
  11666. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11667. colorNode = batchColor.mul( colorNode );
  11668. }
  11669. // COLOR
  11670. diffuseColor.assign( colorNode );
  11671. // OPACITY
  11672. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11673. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11674. // ALPHA TEST
  11675. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11676. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11677. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11678. }
  11679. // ALPHA HASH
  11680. if ( this.alphaHash === true ) {
  11681. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11682. }
  11683. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11684. diffuseColor.a.assign( 1.0 );
  11685. }
  11686. }
  11687. /**
  11688. * Abstract interface method that can be implemented by derived materials
  11689. * to setup material-specific node variables.
  11690. *
  11691. * @abstract
  11692. * @param {NodeBuilder} builder - The current node builder.
  11693. */
  11694. setupVariants( /*builder*/ ) {
  11695. // Interface function.
  11696. }
  11697. /**
  11698. * Setups the outgoing light node variable
  11699. *
  11700. * @return {Node<vec3>} The outgoing light node.
  11701. */
  11702. setupOutgoingLight() {
  11703. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11704. }
  11705. /**
  11706. * Setups the normal node from the material.
  11707. *
  11708. * @return {Node<vec3>} The normal node.
  11709. */
  11710. setupNormal() {
  11711. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11712. }
  11713. /**
  11714. * Setups the environment node from the material.
  11715. *
  11716. * @param {NodeBuilder} builder - The current node builder.
  11717. * @return {Node<vec4>} The environment node.
  11718. */
  11719. setupEnvironment( /*builder*/ ) {
  11720. let node = null;
  11721. if ( this.envNode ) {
  11722. node = this.envNode;
  11723. } else if ( this.envMap ) {
  11724. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11725. }
  11726. return node;
  11727. }
  11728. /**
  11729. * Setups the light map node from the material.
  11730. *
  11731. * @param {NodeBuilder} builder - The current node builder.
  11732. * @return {Node<vec3>} The light map node.
  11733. */
  11734. setupLightMap( builder ) {
  11735. let node = null;
  11736. if ( builder.material.lightMap ) {
  11737. node = new IrradianceNode( materialLightMap );
  11738. }
  11739. return node;
  11740. }
  11741. /**
  11742. * Setups the lights node based on the scene, environment and material.
  11743. *
  11744. * @param {NodeBuilder} builder - The current node builder.
  11745. * @return {LightsNode} The lights node.
  11746. */
  11747. setupLights( builder ) {
  11748. const materialLightsNode = [];
  11749. //
  11750. const envNode = this.setupEnvironment( builder );
  11751. if ( envNode && envNode.isLightingNode ) {
  11752. materialLightsNode.push( envNode );
  11753. }
  11754. const lightMapNode = this.setupLightMap( builder );
  11755. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11756. materialLightsNode.push( lightMapNode );
  11757. }
  11758. if ( this.aoNode !== null || builder.material.aoMap ) {
  11759. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11760. materialLightsNode.push( new AONode( aoNode ) );
  11761. }
  11762. let lightsN = this.lightsNode || builder.lightsNode;
  11763. if ( materialLightsNode.length > 0 ) {
  11764. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11765. }
  11766. return lightsN;
  11767. }
  11768. /**
  11769. * This method should be implemented by most derived materials
  11770. * since it defines the material's lighting model.
  11771. *
  11772. * @abstract
  11773. * @param {NodeBuilder} builder - The current node builder.
  11774. * @return {LightingModel} The lighting model.
  11775. */
  11776. setupLightingModel( /*builder*/ ) {
  11777. // Interface function.
  11778. }
  11779. /**
  11780. * Setups the outgoing light node.
  11781. *
  11782. * @param {NodeBuilder} builder - The current node builder.
  11783. * @return {Node<vec3>} The outgoing light node.
  11784. */
  11785. setupLighting( builder ) {
  11786. const { material } = builder;
  11787. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11788. // OUTGOING LIGHT
  11789. const lights = this.lights === true || this.lightsNode !== null;
  11790. const lightsNode = lights ? this.setupLights( builder ) : null;
  11791. let outgoingLightNode = this.setupOutgoingLight( builder );
  11792. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11793. const lightingModel = this.setupLightingModel( builder );
  11794. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11795. } else if ( backdropNode !== null ) {
  11796. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11797. }
  11798. // EMISSIVE
  11799. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11800. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11801. outgoingLightNode = outgoingLightNode.add( emissive );
  11802. }
  11803. return outgoingLightNode;
  11804. }
  11805. /**
  11806. * Setups the output node.
  11807. *
  11808. * @param {NodeBuilder} builder - The current node builder.
  11809. * @param {Node<vec4>} outputNode - The existing output node.
  11810. * @return {Node<vec4>} The output node.
  11811. */
  11812. setupOutput( builder, outputNode ) {
  11813. // FOG
  11814. if ( this.fog === true ) {
  11815. const fogNode = builder.fogNode;
  11816. if ( fogNode ) {
  11817. output.assign( outputNode );
  11818. outputNode = vec4( fogNode );
  11819. }
  11820. }
  11821. return outputNode;
  11822. }
  11823. /**
  11824. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11825. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11826. * defining all material properties of the classic type in the node type.
  11827. *
  11828. * @param {Material} material - The material to copy properties with their values to this node material.
  11829. */
  11830. setDefaultValues( material ) {
  11831. // This approach is to reuse the native refreshUniforms*
  11832. // and turn available the use of features like transmission and environment in core
  11833. for ( const property in material ) {
  11834. const value = material[ property ];
  11835. if ( this[ property ] === undefined ) {
  11836. this[ property ] = value;
  11837. if ( value && value.clone ) this[ property ] = value.clone();
  11838. }
  11839. }
  11840. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11841. for ( const key in descriptors ) {
  11842. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11843. descriptors[ key ].get !== undefined ) {
  11844. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11845. }
  11846. }
  11847. }
  11848. /**
  11849. * Serializes this material to JSON.
  11850. *
  11851. * @param {(Object|String)?} meta - The meta information for serialization.
  11852. * @return {Object} The serialized node.
  11853. */
  11854. toJSON( meta ) {
  11855. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11856. if ( isRoot ) {
  11857. meta = {
  11858. textures: {},
  11859. images: {},
  11860. nodes: {}
  11861. };
  11862. }
  11863. const data = Material.prototype.toJSON.call( this, meta );
  11864. const nodeChildren = getNodeChildren( this );
  11865. data.inputNodes = {};
  11866. for ( const { property, childNode } of nodeChildren ) {
  11867. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11868. }
  11869. // TODO: Copied from Object3D.toJSON
  11870. function extractFromCache( cache ) {
  11871. const values = [];
  11872. for ( const key in cache ) {
  11873. const data = cache[ key ];
  11874. delete data.metadata;
  11875. values.push( data );
  11876. }
  11877. return values;
  11878. }
  11879. if ( isRoot ) {
  11880. const textures = extractFromCache( meta.textures );
  11881. const images = extractFromCache( meta.images );
  11882. const nodes = extractFromCache( meta.nodes );
  11883. if ( textures.length > 0 ) data.textures = textures;
  11884. if ( images.length > 0 ) data.images = images;
  11885. if ( nodes.length > 0 ) data.nodes = nodes;
  11886. }
  11887. return data;
  11888. }
  11889. /**
  11890. * Copies the properties of the given node material to this instance.
  11891. *
  11892. * @param {NodeMaterial} source - The material to copy.
  11893. * @return {NodeMaterial} A reference to this node material.
  11894. */
  11895. copy( source ) {
  11896. this.lightsNode = source.lightsNode;
  11897. this.envNode = source.envNode;
  11898. this.colorNode = source.colorNode;
  11899. this.normalNode = source.normalNode;
  11900. this.opacityNode = source.opacityNode;
  11901. this.backdropNode = source.backdropNode;
  11902. this.backdropAlphaNode = source.backdropAlphaNode;
  11903. this.alphaTestNode = source.alphaTestNode;
  11904. this.positionNode = source.positionNode;
  11905. this.geometryNode = source.geometryNode;
  11906. this.depthNode = source.depthNode;
  11907. this.shadowPositionNode = source.shadowPositionNode;
  11908. this.receivedShadowNode = source.receivedShadowNode;
  11909. this.castShadowNode = source.castShadowNode;
  11910. this.outputNode = source.outputNode;
  11911. this.mrtNode = source.mrtNode;
  11912. this.fragmentNode = source.fragmentNode;
  11913. this.vertexNode = source.vertexNode;
  11914. return super.copy( source );
  11915. }
  11916. }
  11917. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11918. /**
  11919. * Node material version of `LineBasicMaterial`.
  11920. *
  11921. * @augments NodeMaterial
  11922. */
  11923. class LineBasicNodeMaterial extends NodeMaterial {
  11924. static get type() {
  11925. return 'LineBasicNodeMaterial';
  11926. }
  11927. /**
  11928. * Constructs a new line basic node material.
  11929. *
  11930. * @param {Object?} parameters - The configuration parameter.
  11931. */
  11932. constructor( parameters ) {
  11933. super();
  11934. /**
  11935. * This flag can be used for type testing.
  11936. *
  11937. * @type {Boolean}
  11938. * @readonly
  11939. * @default true
  11940. */
  11941. this.isLineBasicNodeMaterial = true;
  11942. this.setDefaultValues( _defaultValues$d );
  11943. this.setValues( parameters );
  11944. }
  11945. }
  11946. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11947. /**
  11948. * Node material version of `LineDashedMaterial`.
  11949. *
  11950. * @augments NodeMaterial
  11951. */
  11952. class LineDashedNodeMaterial extends NodeMaterial {
  11953. static get type() {
  11954. return 'LineDashedNodeMaterial';
  11955. }
  11956. /**
  11957. * Constructs a new line dashed node material.
  11958. *
  11959. * @param {Object?} parameters - The configuration parameter.
  11960. */
  11961. constructor( parameters ) {
  11962. super();
  11963. /**
  11964. * This flag can be used for type testing.
  11965. *
  11966. * @type {Boolean}
  11967. * @readonly
  11968. * @default true
  11969. */
  11970. this.isLineDashedNodeMaterial = true;
  11971. this.setDefaultValues( _defaultValues$c );
  11972. /**
  11973. * The dash offset.
  11974. *
  11975. * @type {Number}
  11976. * @default 0
  11977. */
  11978. this.dashOffset = 0;
  11979. /**
  11980. * The offset of dash materials is by default inferred from the `dashOffset`
  11981. * property. This node property allows to overwrite the default
  11982. * and define the offset with a node instead.
  11983. *
  11984. * If you don't want to overwrite the offset but modify the existing
  11985. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11986. *
  11987. * @type {Node<float>?}
  11988. * @default null
  11989. */
  11990. this.offsetNode = null;
  11991. /**
  11992. * The scale of dash materials is by default inferred from the `scale`
  11993. * property. This node property allows to overwrite the default
  11994. * and define the scale with a node instead.
  11995. *
  11996. * If you don't want to overwrite the scale but modify the existing
  11997. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11998. *
  11999. * @type {Node<float>?}
  12000. * @default null
  12001. */
  12002. this.dashScaleNode = null;
  12003. /**
  12004. * The dash size of dash materials is by default inferred from the `dashSize`
  12005. * property. This node property allows to overwrite the default
  12006. * and define the dash size with a node instead.
  12007. *
  12008. * If you don't want to overwrite the dash size but modify the existing
  12009. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  12010. *
  12011. * @type {Node<float>?}
  12012. * @default null
  12013. */
  12014. this.dashSizeNode = null;
  12015. /**
  12016. * The gap size of dash materials is by default inferred from the `gapSize`
  12017. * property. This node property allows to overwrite the default
  12018. * and define the gap size with a node instead.
  12019. *
  12020. * If you don't want to overwrite the gap size but modify the existing
  12021. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  12022. *
  12023. * @type {Node<float>?}
  12024. * @default null
  12025. */
  12026. this.gapSizeNode = null;
  12027. this.setValues( parameters );
  12028. }
  12029. /**
  12030. * Setups the dash specific node variables.
  12031. *
  12032. * @param {NodeBuilder} builder - The current node builder.
  12033. */
  12034. setupVariants( /* builder */ ) {
  12035. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12036. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12037. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12038. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12039. dashSize.assign( dashSizeNode );
  12040. gapSize.assign( gapSizeNode );
  12041. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  12042. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  12043. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  12044. }
  12045. }
  12046. /** @module ViewportSharedTextureNode **/
  12047. let _sharedFramebuffer = null;
  12048. /**
  12049. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  12050. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  12051. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  12052. *
  12053. * @augments module:ViewportTextureNode~ViewportTextureNode
  12054. */
  12055. class ViewportSharedTextureNode extends ViewportTextureNode {
  12056. static get type() {
  12057. return 'ViewportSharedTextureNode';
  12058. }
  12059. /**
  12060. * Constructs a new viewport shared texture node.
  12061. *
  12062. * @param {Node} [uvNode=screenUV] - The uv node.
  12063. * @param {Node?} [levelNode=null] - The level node.
  12064. */
  12065. constructor( uvNode = screenUV, levelNode = null ) {
  12066. if ( _sharedFramebuffer === null ) {
  12067. _sharedFramebuffer = new FramebufferTexture();
  12068. }
  12069. super( uvNode, levelNode, _sharedFramebuffer );
  12070. }
  12071. updateReference() {
  12072. return this;
  12073. }
  12074. }
  12075. /**
  12076. * TSL function for creating a shared viewport texture node.
  12077. *
  12078. * @function
  12079. * @param {Node} [uvNode=screenUV] - The uv node.
  12080. * @param {Node?} [levelNode=null] - The level node.
  12081. * @returns {ViewportSharedTextureNode}
  12082. */
  12083. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  12084. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  12085. /**
  12086. * This node material can be used to render lines with a size larger than one
  12087. * by representing them as instanced meshes.
  12088. *
  12089. * @augments NodeMaterial
  12090. */
  12091. class Line2NodeMaterial extends NodeMaterial {
  12092. static get type() {
  12093. return 'Line2NodeMaterial';
  12094. }
  12095. /**
  12096. * Constructs a new node material for wide line rendering.
  12097. *
  12098. * @param {Object?} parameters - The configuration parameter.
  12099. */
  12100. constructor( parameters = {} ) {
  12101. super();
  12102. /**
  12103. * This flag can be used for type testing.
  12104. *
  12105. * @type {Boolean}
  12106. * @readonly
  12107. * @default true
  12108. */
  12109. this.isLine2NodeMaterial = true;
  12110. this.setDefaultValues( _defaultValues$b );
  12111. /**
  12112. * Whether vertex colors should be used or not.
  12113. *
  12114. * @type {Boolean}
  12115. * @default false
  12116. */
  12117. this.useColor = parameters.vertexColors;
  12118. /**
  12119. * The dash offset.
  12120. *
  12121. * @type {Number}
  12122. * @default 0
  12123. */
  12124. this.dashOffset = 0;
  12125. /**
  12126. * The line width.
  12127. *
  12128. * @type {Number}
  12129. * @default 0
  12130. */
  12131. this.lineWidth = 1;
  12132. /**
  12133. * Defines the lines color.
  12134. *
  12135. * @type {Node<vec3>?}
  12136. * @default null
  12137. */
  12138. this.lineColorNode = null;
  12139. /**
  12140. * Defines the offset.
  12141. *
  12142. * @type {Node<float>?}
  12143. * @default null
  12144. */
  12145. this.offsetNode = null;
  12146. /**
  12147. * Defines the dash scale.
  12148. *
  12149. * @type {Node<float>?}
  12150. * @default null
  12151. */
  12152. this.dashScaleNode = null;
  12153. /**
  12154. * Defines the dash size.
  12155. *
  12156. * @type {Node<float>?}
  12157. * @default null
  12158. */
  12159. this.dashSizeNode = null;
  12160. /**
  12161. * Defines the gap size.
  12162. *
  12163. * @type {Node<float>?}
  12164. * @default null
  12165. */
  12166. this.gapSizeNode = null;
  12167. /**
  12168. * Blending is set to `NoBlending` since transparency
  12169. * is not supported, yet.
  12170. *
  12171. * @type {Number}
  12172. * @default 0
  12173. */
  12174. this.blending = NoBlending;
  12175. this._useDash = parameters.dashed;
  12176. this._useAlphaToCoverage = true;
  12177. this._useWorldUnits = false;
  12178. this.setValues( parameters );
  12179. }
  12180. /**
  12181. * Setups the vertex and fragment stage of this node material.
  12182. *
  12183. * @param {NodeBuilder} builder - The current node builder.
  12184. */
  12185. setup( builder ) {
  12186. const { renderer } = builder;
  12187. const useAlphaToCoverage = this._useAlphaToCoverage;
  12188. const useColor = this.useColor;
  12189. const useDash = this._useDash;
  12190. const useWorldUnits = this._useWorldUnits;
  12191. const trimSegment = Fn( ( { start, end } ) => {
  12192. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12193. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12194. const nearEstimate = b.mul( -0.5 ).div( a );
  12195. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12196. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12197. } ).setLayout( {
  12198. name: 'trimSegment',
  12199. type: 'vec4',
  12200. inputs: [
  12201. { name: 'start', type: 'vec4' },
  12202. { name: 'end', type: 'vec4' }
  12203. ]
  12204. } );
  12205. this.vertexNode = Fn( () => {
  12206. const instanceStart = attribute( 'instanceStart' );
  12207. const instanceEnd = attribute( 'instanceEnd' );
  12208. // camera space
  12209. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12210. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12211. if ( useDash ) {
  12212. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12213. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12214. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12215. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12216. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12217. lineDistance = lineDistance.add( offsetNode );
  12218. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12219. }
  12220. if ( useWorldUnits ) {
  12221. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12222. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12223. }
  12224. const aspect = viewport.z.div( viewport.w );
  12225. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12226. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12227. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12228. // perhaps there is a more elegant solution -- WestLangley
  12229. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  12230. If( perspective, () => {
  12231. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12232. end.assign( trimSegment( { start: start, end: end } ) );
  12233. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12234. start.assign( trimSegment( { start: end, end: start } ) );
  12235. } );
  12236. } );
  12237. // clip space
  12238. const clipStart = cameraProjectionMatrix.mul( start );
  12239. const clipEnd = cameraProjectionMatrix.mul( end );
  12240. // ndc space
  12241. const ndcStart = clipStart.xyz.div( clipStart.w );
  12242. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12243. // direction
  12244. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12245. // account for clip-space aspect ratio
  12246. dir.x.assign( dir.x.mul( aspect ) );
  12247. dir.assign( dir.normalize() );
  12248. const clip = vec4().toVar();
  12249. if ( useWorldUnits ) {
  12250. // get the offset direction as perpendicular to the view vector
  12251. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12252. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12253. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12254. const worldFwd = worldDir.cross( worldUp );
  12255. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12256. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12257. // height offset
  12258. const hw = materialLineWidth.mul( 0.5 );
  12259. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12260. // don't extend the line if we're rendering dashes because we
  12261. // won't be rendering the endcaps
  12262. if ( ! useDash ) {
  12263. // cap extension
  12264. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12265. // add width to the box
  12266. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12267. // endcaps
  12268. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12269. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12270. } );
  12271. }
  12272. // project the worldpos
  12273. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12274. // shift the depth of the projected points so the line
  12275. // segments overlap neatly
  12276. const clipPose = vec3().toVar();
  12277. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12278. clip.z.assign( clipPose.z.mul( clip.w ) );
  12279. } else {
  12280. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12281. // undo aspect ratio adjustment
  12282. dir.x.assign( dir.x.div( aspect ) );
  12283. offset.x.assign( offset.x.div( aspect ) );
  12284. // sign flip
  12285. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12286. // endcaps
  12287. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12288. offset.assign( offset.sub( dir ) );
  12289. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12290. offset.assign( offset.add( dir ) );
  12291. } );
  12292. // adjust for linewidth
  12293. offset.assign( offset.mul( materialLineWidth ) );
  12294. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12295. offset.assign( offset.div( viewport.w ) );
  12296. // select end
  12297. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12298. // back to clip space
  12299. offset.assign( offset.mul( clip.w ) );
  12300. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12301. }
  12302. return clip;
  12303. } )();
  12304. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12305. const p13 = p1.sub( p3 );
  12306. const p43 = p4.sub( p3 );
  12307. const p21 = p2.sub( p1 );
  12308. const d1343 = p13.dot( p43 );
  12309. const d4321 = p43.dot( p21 );
  12310. const d1321 = p13.dot( p21 );
  12311. const d4343 = p43.dot( p43 );
  12312. const d2121 = p21.dot( p21 );
  12313. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12314. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12315. const mua = numer.div( denom ).clamp();
  12316. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12317. return vec2( mua, mub );
  12318. } );
  12319. this.colorNode = Fn( () => {
  12320. const vUv = uv();
  12321. if ( useDash ) {
  12322. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12323. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12324. dashSize.assign( dashSizeNode );
  12325. gapSize.assign( gapSizeNode );
  12326. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12327. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12328. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12329. }
  12330. const alpha = float( 1 ).toVar( 'alpha' );
  12331. if ( useWorldUnits ) {
  12332. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12333. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12334. // Find the closest points on the view ray and the line segment
  12335. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12336. const lineDir = worldEnd.sub( worldStart );
  12337. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12338. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12339. const p2 = rayEnd.mul( params.y );
  12340. const delta = p1.sub( p2 );
  12341. const len = delta.length();
  12342. const norm = len.div( materialLineWidth );
  12343. if ( ! useDash ) {
  12344. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12345. const dnorm = norm.fwidth();
  12346. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12347. } else {
  12348. norm.greaterThan( 0.5 ).discard();
  12349. }
  12350. }
  12351. } else {
  12352. // round endcaps
  12353. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12354. const a = vUv.x;
  12355. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12356. const len2 = a.mul( a ).add( b.mul( b ) );
  12357. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12358. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12359. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12360. } );
  12361. } else {
  12362. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12363. const a = vUv.x;
  12364. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12365. const len2 = a.mul( a ).add( b.mul( b ) );
  12366. len2.greaterThan( 1.0 ).discard();
  12367. } );
  12368. }
  12369. }
  12370. let lineColorNode;
  12371. if ( this.lineColorNode ) {
  12372. lineColorNode = this.lineColorNode;
  12373. } else {
  12374. if ( useColor ) {
  12375. const instanceColorStart = attribute( 'instanceColorStart' );
  12376. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12377. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12378. lineColorNode = instanceColor.mul( materialColor );
  12379. } else {
  12380. lineColorNode = materialColor;
  12381. }
  12382. }
  12383. return vec4( lineColorNode, alpha );
  12384. } )();
  12385. if ( this.transparent ) {
  12386. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12387. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12388. }
  12389. super.setup( builder );
  12390. }
  12391. /**
  12392. * Whether the lines should sized in world units or not.
  12393. * When set to `false` the unit is pixel.
  12394. *
  12395. * @type {Boolean}
  12396. * @default false
  12397. */
  12398. get worldUnits() {
  12399. return this._useWorldUnits;
  12400. }
  12401. set worldUnits( value ) {
  12402. if ( this._useWorldUnits !== value ) {
  12403. this._useWorldUnits = value;
  12404. this.needsUpdate = true;
  12405. }
  12406. }
  12407. /**
  12408. * Whether the lines should be dashed or not.
  12409. *
  12410. * @type {Boolean}
  12411. * @default false
  12412. */
  12413. get dashed() {
  12414. return this._useDash;
  12415. }
  12416. set dashed( value ) {
  12417. if ( this._useDash !== value ) {
  12418. this._useDash = value;
  12419. this.needsUpdate = true;
  12420. }
  12421. }
  12422. /**
  12423. * Whether alpha to coverage should be used or not.
  12424. *
  12425. * @type {Boolean}
  12426. * @default true
  12427. */
  12428. get alphaToCoverage() {
  12429. return this._useAlphaToCoverage;
  12430. }
  12431. set alphaToCoverage( value ) {
  12432. if ( this._useAlphaToCoverage !== value ) {
  12433. this._useAlphaToCoverage = value;
  12434. this.needsUpdate = true;
  12435. }
  12436. }
  12437. }
  12438. /** @module Packing **/
  12439. /**
  12440. * Packs a direction vector into a color value.
  12441. *
  12442. * @method
  12443. * @param {Node<vec3>} node - The direction to pack.
  12444. * @return {Node<vec3>} The color.
  12445. */
  12446. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12447. /**
  12448. * Unpacks a color value into a direction vector.
  12449. *
  12450. * @method
  12451. * @param {Node<vec3>} node - The color to unpack.
  12452. * @return {Node<vec3>} The direction.
  12453. */
  12454. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12455. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12456. /**
  12457. * Node material version of `MeshNormalMaterial`.
  12458. *
  12459. * @augments NodeMaterial
  12460. */
  12461. class MeshNormalNodeMaterial extends NodeMaterial {
  12462. static get type() {
  12463. return 'MeshNormalNodeMaterial';
  12464. }
  12465. /**
  12466. * Constructs a new mesh normal node material.
  12467. *
  12468. * @param {Object?} parameters - The configuration parameter.
  12469. */
  12470. constructor( parameters ) {
  12471. super();
  12472. /**
  12473. * This flag can be used for type testing.
  12474. *
  12475. * @type {Boolean}
  12476. * @readonly
  12477. * @default true
  12478. */
  12479. this.isMeshNormalNodeMaterial = true;
  12480. this.setDefaultValues( _defaultValues$a );
  12481. this.setValues( parameters );
  12482. }
  12483. /**
  12484. * Overwrites the default implementation by computing the diffuse color
  12485. * based on the normal data.
  12486. */
  12487. setupDiffuseColor() {
  12488. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12489. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12490. }
  12491. }
  12492. /** @module EquirectUVNode **/
  12493. /**
  12494. * Can be used to compute texture coordinates for projecting an
  12495. * equirectangular texture onto a mesh for using it as the scene's
  12496. * background.
  12497. *
  12498. * ```js
  12499. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12500. * ```
  12501. *
  12502. * @augments TempNode
  12503. */
  12504. class EquirectUVNode extends TempNode {
  12505. static get type() {
  12506. return 'EquirectUVNode';
  12507. }
  12508. /**
  12509. * Constructs a new equirect uv node.
  12510. *
  12511. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12512. */
  12513. constructor( dirNode = positionWorldDirection ) {
  12514. super( 'vec2' );
  12515. /**
  12516. * A direction vector for sampling why is by default `positionWorldDirection`.
  12517. *
  12518. * @type {Node<vec3>}
  12519. */
  12520. this.dirNode = dirNode;
  12521. }
  12522. setup() {
  12523. const dir = this.dirNode;
  12524. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12525. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12526. return vec2( u, v );
  12527. }
  12528. }
  12529. /**
  12530. * TSL function for creating an equirect uv node.
  12531. *
  12532. * @function
  12533. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12534. * @returns {EquirectUVNode}
  12535. */
  12536. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12537. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12538. /**
  12539. * This class represents a cube render target. It is a special version
  12540. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12541. *
  12542. * @augments WebGLCubeRenderTarget
  12543. */
  12544. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12545. constructor( size = 1, options = {} ) {
  12546. super( size, options );
  12547. this.isCubeRenderTarget = true;
  12548. }
  12549. /**
  12550. * Converts the given equirectangular texture to a cube map.
  12551. *
  12552. * @param {Renderer} renderer - The renderer.
  12553. * @param {Texture} texture - The equirectangular texture.
  12554. * @return {CubeRenderTarget} A reference to this cube render target.
  12555. */
  12556. fromEquirectangularTexture( renderer, texture$1 ) {
  12557. const currentMinFilter = texture$1.minFilter;
  12558. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12559. texture$1.generateMipmaps = true;
  12560. this.texture.type = texture$1.type;
  12561. this.texture.colorSpace = texture$1.colorSpace;
  12562. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12563. this.texture.minFilter = texture$1.minFilter;
  12564. this.texture.magFilter = texture$1.magFilter;
  12565. const geometry = new BoxGeometry( 5, 5, 5 );
  12566. const uvNode = equirectUV( positionWorldDirection );
  12567. const material = new NodeMaterial();
  12568. material.colorNode = texture( texture$1, uvNode, 0 );
  12569. material.side = BackSide;
  12570. material.blending = NoBlending;
  12571. const mesh = new Mesh( geometry, material );
  12572. const scene = new Scene();
  12573. scene.add( mesh );
  12574. // Avoid blurred poles
  12575. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12576. const camera = new CubeCamera( 1, 10, this );
  12577. const currentMRT = renderer.getMRT();
  12578. renderer.setMRT( null );
  12579. camera.update( renderer, scene );
  12580. renderer.setMRT( currentMRT );
  12581. texture$1.minFilter = currentMinFilter;
  12582. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12583. mesh.geometry.dispose();
  12584. mesh.material.dispose();
  12585. return this;
  12586. }
  12587. }
  12588. /** @module CubeMapNode **/
  12589. const _cache$1 = new WeakMap();
  12590. /**
  12591. * This node can be used to automatically convert environment maps in the
  12592. * equirectangular format into the cube map format.
  12593. *
  12594. * @augments TempNode
  12595. */
  12596. class CubeMapNode extends TempNode {
  12597. static get type() {
  12598. return 'CubeMapNode';
  12599. }
  12600. /**
  12601. * Constructs a new cube map node.
  12602. *
  12603. * @param {Node} envNode - The node representing the environment map.
  12604. */
  12605. constructor( envNode ) {
  12606. super( 'vec3' );
  12607. /**
  12608. * The node representing the environment map.
  12609. *
  12610. * @type {Node}
  12611. */
  12612. this.envNode = envNode;
  12613. /**
  12614. * A reference to the internal cube texture.
  12615. *
  12616. * @private
  12617. * @type {CubeTexture}
  12618. * @default null
  12619. */
  12620. this._cubeTexture = null;
  12621. /**
  12622. * A reference to the internal cube texture node.
  12623. *
  12624. * @private
  12625. * @type {CubeTextureNode}
  12626. */
  12627. this._cubeTextureNode = cubeTexture();
  12628. const defaultTexture = new CubeTexture();
  12629. defaultTexture.isRenderTargetTexture = true;
  12630. /**
  12631. * A default cube texture that acts as a placeholder.
  12632. * It is used when the conversion from equirectangular to cube
  12633. * map has not finished yet for a given texture.
  12634. *
  12635. * @private
  12636. * @type {CubeTexture}
  12637. */
  12638. this._defaultTexture = defaultTexture;
  12639. /**
  12640. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12641. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12642. *
  12643. * @type {String}
  12644. * @default 'render'
  12645. */
  12646. this.updateBeforeType = NodeUpdateType.RENDER;
  12647. }
  12648. updateBefore( frame ) {
  12649. const { renderer, material } = frame;
  12650. const envNode = this.envNode;
  12651. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12652. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12653. if ( texture && texture.isTexture ) {
  12654. const mapping = texture.mapping;
  12655. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12656. // check for converted cubemap map
  12657. if ( _cache$1.has( texture ) ) {
  12658. const cubeMap = _cache$1.get( texture );
  12659. mapTextureMapping( cubeMap, texture.mapping );
  12660. this._cubeTexture = cubeMap;
  12661. } else {
  12662. // create cube map from equirectangular map
  12663. const image = texture.image;
  12664. if ( isEquirectangularMapReady$1( image ) ) {
  12665. const renderTarget = new CubeRenderTarget( image.height );
  12666. renderTarget.fromEquirectangularTexture( renderer, texture );
  12667. mapTextureMapping( renderTarget.texture, texture.mapping );
  12668. this._cubeTexture = renderTarget.texture;
  12669. _cache$1.set( texture, renderTarget.texture );
  12670. texture.addEventListener( 'dispose', onTextureDispose );
  12671. } else {
  12672. // default cube texture as fallback when equirectangular texture is not yet loaded
  12673. this._cubeTexture = this._defaultTexture;
  12674. }
  12675. }
  12676. //
  12677. this._cubeTextureNode.value = this._cubeTexture;
  12678. } else {
  12679. // envNode already refers to a cube map
  12680. this._cubeTextureNode = this.envNode;
  12681. }
  12682. }
  12683. }
  12684. }
  12685. setup( builder ) {
  12686. this.updateBefore( builder );
  12687. return this._cubeTextureNode;
  12688. }
  12689. }
  12690. /**
  12691. * Returns true if the given equirectangular image has been fully loaded
  12692. * and is ready for further processing.
  12693. *
  12694. * @private
  12695. * @param {Image} image - The equirectangular image to check.
  12696. * @return {Boolean} Whether the image is ready or not.
  12697. */
  12698. function isEquirectangularMapReady$1( image ) {
  12699. if ( image === null || image === undefined ) return false;
  12700. return image.height > 0;
  12701. }
  12702. /**
  12703. * This function is executed when `dispose()` is called on the equirectangular
  12704. * texture. In this case, the generated cube map with its render target
  12705. * is deleted as well.
  12706. *
  12707. * @private
  12708. * @param {Object} event - The event object.
  12709. */
  12710. function onTextureDispose( event ) {
  12711. const texture = event.target;
  12712. texture.removeEventListener( 'dispose', onTextureDispose );
  12713. const renderTarget = _cache$1.get( texture );
  12714. if ( renderTarget !== undefined ) {
  12715. _cache$1.delete( texture );
  12716. renderTarget.dispose();
  12717. }
  12718. }
  12719. /**
  12720. * This function makes sure the generated cube map uses the correct
  12721. * texture mapping that corresponds to the equirectangular original.
  12722. *
  12723. * @private
  12724. * @param {Texture} texture - The cube texture.
  12725. * @param {Number} mapping - The original texture mapping.
  12726. */
  12727. function mapTextureMapping( texture, mapping ) {
  12728. if ( mapping === EquirectangularReflectionMapping ) {
  12729. texture.mapping = CubeReflectionMapping;
  12730. } else if ( mapping === EquirectangularRefractionMapping ) {
  12731. texture.mapping = CubeRefractionMapping;
  12732. }
  12733. }
  12734. /**
  12735. * TSL function for creating a cube map node.
  12736. *
  12737. * @function
  12738. * @param {Node} envNode - The node representing the environment map.
  12739. * @returns {CubeMapNode}
  12740. */
  12741. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12742. /**
  12743. * Represents a basic model for Image-based lighting (IBL). The environment
  12744. * is defined via environment maps in the equirectangular or cube map format.
  12745. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12746. * or {@link MeshPhongNodeMaterial}.
  12747. *
  12748. * @augments LightingNode
  12749. */
  12750. class BasicEnvironmentNode extends LightingNode {
  12751. static get type() {
  12752. return 'BasicEnvironmentNode';
  12753. }
  12754. /**
  12755. * Constructs a new basic environment node.
  12756. *
  12757. * @param {Node} [envNode=null] - A node representing the environment.
  12758. */
  12759. constructor( envNode = null ) {
  12760. super();
  12761. /**
  12762. * A node representing the environment.
  12763. *
  12764. * @type {Node}
  12765. * @default null
  12766. */
  12767. this.envNode = envNode;
  12768. }
  12769. setup( builder ) {
  12770. // environment property is used in the finish() method of BasicLightingModel
  12771. builder.context.environment = cubeMapNode( this.envNode );
  12772. }
  12773. }
  12774. /**
  12775. * A specific version of {@link IrradianceNode} that is only relevant
  12776. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12777. * requires a special scaling factor for the light map.
  12778. *
  12779. * @augments LightingNode
  12780. */
  12781. class BasicLightMapNode extends LightingNode {
  12782. static get type() {
  12783. return 'BasicLightMapNode';
  12784. }
  12785. /**
  12786. * Constructs a new basic light map node.
  12787. *
  12788. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12789. */
  12790. constructor( lightMapNode = null ) {
  12791. super();
  12792. /**
  12793. * The light map node.
  12794. *
  12795. * @type {Node<vec3>?}
  12796. */
  12797. this.lightMapNode = lightMapNode;
  12798. }
  12799. setup( builder ) {
  12800. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12801. const RECIPROCAL_PI = float( 1 / Math.PI );
  12802. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12803. }
  12804. }
  12805. /**
  12806. * Abstract class for implementing lighting models. The module defines
  12807. * multiple methods that concrete lighting models can implement. These
  12808. * methods are executed at different points during the light evaluation
  12809. * process.
  12810. */
  12811. class LightingModel {
  12812. /**
  12813. * This method is intended for setting up lighting model and context data
  12814. * which are later used in the evaluation process.
  12815. *
  12816. * @abstract
  12817. * @param {ContextNode} input - The current node context.
  12818. * @param {StackNode} stack - The current stack.
  12819. * @param {NodeBuilder} builder - The current node builder.
  12820. */
  12821. start( /*input, stack, builder*/ ) { }
  12822. /**
  12823. * This method is intended for executing final tasks like final updates
  12824. * to the outgoing light.
  12825. *
  12826. * @abstract
  12827. * @param {ContextNode} input - The current node context.
  12828. * @param {StackNode} stack - The current stack.
  12829. * @param {NodeBuilder} builder - The current node builder.
  12830. */
  12831. finish( /*input, stack, builder*/ ) { }
  12832. /**
  12833. * This method is intended for implementing the direct light term and
  12834. * executed during the build process of directional, point and spot light nodes.
  12835. *
  12836. * @abstract
  12837. * @param {Object} input - The input data.
  12838. * @param {StackNode} stack - The current stack.
  12839. * @param {NodeBuilder} builder - The current node builder.
  12840. */
  12841. direct( /*input, stack, builder*/ ) { }
  12842. /**
  12843. * This method is intended for implementing the direct light term for
  12844. * rect area light nodes.
  12845. *
  12846. * @abstract
  12847. * @param {Object} input - The input data.
  12848. * @param {StackNode} stack - The current stack.
  12849. * @param {NodeBuilder} builder - The current node builder.
  12850. */
  12851. directRectArea( /*input, stack, builder*/ ) {}
  12852. /**
  12853. * This method is intended for implementing the indirect light term.
  12854. *
  12855. * @abstract
  12856. * @param {ContextNode} input - The current node context.
  12857. * @param {StackNode} stack - The current stack.
  12858. * @param {NodeBuilder} builder - The current node builder.
  12859. */
  12860. indirect( /*input, stack, builder*/ ) { }
  12861. /**
  12862. * This method is intended for implementing the ambient occlusion term.
  12863. * Unlike other methods, this method must be called manually by the lighting
  12864. * model in its indirect term.
  12865. *
  12866. * @abstract
  12867. * @param {ContextNode} input - The current node context.
  12868. * @param {StackNode} stack - The current stack.
  12869. * @param {NodeBuilder} builder - The current node builder.
  12870. */
  12871. ambientOcclusion( /*input, stack, builder*/ ) { }
  12872. }
  12873. /**
  12874. * Represents the lighting model for unlit materials. The only light contribution
  12875. * is baked indirect lighting modulated with ambient occlusion and the material's
  12876. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12877. *
  12878. * @augments LightingModel
  12879. */
  12880. class BasicLightingModel extends LightingModel {
  12881. /**
  12882. * Constructs a new basic lighting model.
  12883. */
  12884. constructor() {
  12885. super();
  12886. }
  12887. /**
  12888. * Implements the baked indirect lighting with its modulation.
  12889. *
  12890. * @param {ContextNode} context - The current node context.
  12891. * @param {StackNode} stack - The current stack.
  12892. * @param {NodeBuilder} builder - The current node builder.
  12893. */
  12894. indirect( context, stack, builder ) {
  12895. const ambientOcclusion = context.ambientOcclusion;
  12896. const reflectedLight = context.reflectedLight;
  12897. const irradianceLightMap = builder.context.irradianceLightMap;
  12898. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12899. // accumulation (baked indirect lighting only)
  12900. if ( irradianceLightMap ) {
  12901. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12902. } else {
  12903. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12904. }
  12905. // modulation
  12906. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12907. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12908. }
  12909. /**
  12910. * Implements the environment mapping.
  12911. *
  12912. * @param {ContextNode} context - The current node context.
  12913. * @param {StackNode} stack - The current stack.
  12914. * @param {NodeBuilder} builder - The current node builder.
  12915. */
  12916. finish( context, stack, builder ) {
  12917. const material = builder.material;
  12918. const outgoingLight = context.outgoingLight;
  12919. const envNode = builder.context.environment;
  12920. if ( envNode ) {
  12921. switch ( material.combine ) {
  12922. case MultiplyOperation:
  12923. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12924. break;
  12925. case MixOperation:
  12926. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12927. break;
  12928. case AddOperation:
  12929. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12930. break;
  12931. default:
  12932. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12933. break;
  12934. }
  12935. }
  12936. }
  12937. }
  12938. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12939. /**
  12940. * Node material version of `MeshBasicMaterial`.
  12941. *
  12942. * @augments NodeMaterial
  12943. */
  12944. class MeshBasicNodeMaterial extends NodeMaterial {
  12945. static get type() {
  12946. return 'MeshBasicNodeMaterial';
  12947. }
  12948. /**
  12949. * Constructs a new mesh basic node material.
  12950. *
  12951. * @param {Object?} parameters - The configuration parameter.
  12952. */
  12953. constructor( parameters ) {
  12954. super();
  12955. /**
  12956. * This flag can be used for type testing.
  12957. *
  12958. * @type {Boolean}
  12959. * @readonly
  12960. * @default true
  12961. */
  12962. this.isMeshBasicNodeMaterial = true;
  12963. /**
  12964. * Although the basic material is by definition unlit, we set
  12965. * this property to `true` since we use a lighting model to compute
  12966. * the outgoing light of the fragment shader.
  12967. *
  12968. * @type {Boolean}
  12969. * @default true
  12970. */
  12971. this.lights = true;
  12972. this.setDefaultValues( _defaultValues$9 );
  12973. this.setValues( parameters );
  12974. }
  12975. /**
  12976. * Basic materials are not affected by normal and bump maps so we
  12977. * return by default {@link module:Normal.normalView}.
  12978. *
  12979. * @return {Node<vec3>} The normal node.
  12980. */
  12981. setupNormal() {
  12982. return normalView; // see #28839
  12983. }
  12984. /**
  12985. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12986. * to implement the default environment mapping.
  12987. *
  12988. * @param {NodeBuilder} builder - The current node builder.
  12989. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12990. */
  12991. setupEnvironment( builder ) {
  12992. const envNode = super.setupEnvironment( builder );
  12993. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12994. }
  12995. /**
  12996. * This method must be overwritten since light maps are evaluated
  12997. * with a special scaling factor for basic materials.
  12998. *
  12999. * @param {NodeBuilder} builder - The current node builder.
  13000. * @return {BasicLightMapNode<vec3>?} The light map node.
  13001. */
  13002. setupLightMap( builder ) {
  13003. let node = null;
  13004. if ( builder.material.lightMap ) {
  13005. node = new BasicLightMapNode( materialLightMap );
  13006. }
  13007. return node;
  13008. }
  13009. /**
  13010. * The material overwrites this method because `lights` is set to `true` but
  13011. * we still want to return the diffuse color as the outgoing light.
  13012. *
  13013. * @return {Node<vec3>} The outgoing light node.
  13014. */
  13015. setupOutgoingLight() {
  13016. return diffuseColor.rgb;
  13017. }
  13018. /**
  13019. * Setups the lighting model.
  13020. *
  13021. * @return {BasicLightingModel} The lighting model.
  13022. */
  13023. setupLightingModel() {
  13024. return new BasicLightingModel();
  13025. }
  13026. }
  13027. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  13028. // Original approximation by Christophe Schlick '94
  13029. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  13030. // Optimized variant (presented by Epic at SIGGRAPH '13)
  13031. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  13032. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  13033. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  13034. } ); // validated
  13035. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  13036. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  13037. } ); // validated
  13038. const G_BlinnPhong_Implicit = () => float( 0.25 );
  13039. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  13040. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  13041. } );
  13042. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13043. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13044. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13045. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13046. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  13047. const G = G_BlinnPhong_Implicit();
  13048. const D = D_BlinnPhong( { dotNH } );
  13049. return F.mul( G ).mul( D );
  13050. } );
  13051. /**
  13052. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  13053. *
  13054. * @augments BasicLightingModel
  13055. */
  13056. class PhongLightingModel extends BasicLightingModel {
  13057. /**
  13058. * Constructs a new phong lighting model.
  13059. *
  13060. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  13061. */
  13062. constructor( specular = true ) {
  13063. super();
  13064. /**
  13065. * Whether specular is supported or not. Set this to `false` if you are
  13066. * looking for a Lambert-like material meaning a material for non-shiny
  13067. * surfaces, without specular highlights.
  13068. *
  13069. * @type {Boolean}
  13070. * @default true
  13071. */
  13072. this.specular = specular;
  13073. }
  13074. /**
  13075. * Implements the direct lighting. The specular portion is optional an can be controlled
  13076. * with the {@link PhongLightingModel#specular} flag.
  13077. *
  13078. * @param {Object} input - The input data.
  13079. * @param {StackNode} stack - The current stack.
  13080. * @param {NodeBuilder} builder - The current node builder.
  13081. */
  13082. direct( { lightDirection, lightColor, reflectedLight } ) {
  13083. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13084. const irradiance = dotNL.mul( lightColor );
  13085. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13086. if ( this.specular === true ) {
  13087. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  13088. }
  13089. }
  13090. /**
  13091. * Implements the indirect lighting.
  13092. *
  13093. * @param {ContextNode} input - The current node context.
  13094. * @param {StackNode} stack - The current stack.
  13095. * @param {NodeBuilder} builder - The current node builder.
  13096. */
  13097. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  13098. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13099. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13100. }
  13101. }
  13102. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  13103. /**
  13104. * Node material version of `MeshLambertMaterial`.
  13105. *
  13106. * @augments NodeMaterial
  13107. */
  13108. class MeshLambertNodeMaterial extends NodeMaterial {
  13109. static get type() {
  13110. return 'MeshLambertNodeMaterial';
  13111. }
  13112. /**
  13113. * Constructs a new mesh lambert node material.
  13114. *
  13115. * @param {Object?} parameters - The configuration parameter.
  13116. */
  13117. constructor( parameters ) {
  13118. super();
  13119. /**
  13120. * This flag can be used for type testing.
  13121. *
  13122. * @type {Boolean}
  13123. * @readonly
  13124. * @default true
  13125. */
  13126. this.isMeshLambertNodeMaterial = true;
  13127. /**
  13128. * Set to `true` because lambert materials react on lights.
  13129. *
  13130. * @type {Boolean}
  13131. * @default true
  13132. */
  13133. this.lights = true;
  13134. this.setDefaultValues( _defaultValues$8 );
  13135. this.setValues( parameters );
  13136. }
  13137. /**
  13138. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13139. * to implement the default environment mapping.
  13140. *
  13141. * @param {NodeBuilder} builder - The current node builder.
  13142. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13143. */
  13144. setupEnvironment( builder ) {
  13145. const envNode = super.setupEnvironment( builder );
  13146. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13147. }
  13148. /**
  13149. * Setups the lighting model.
  13150. *
  13151. * @return {PhongLightingModel} The lighting model.
  13152. */
  13153. setupLightingModel( /*builder*/ ) {
  13154. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13155. }
  13156. }
  13157. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13158. /**
  13159. * Node material version of `MeshPhongMaterial`.
  13160. *
  13161. * @augments NodeMaterial
  13162. */
  13163. class MeshPhongNodeMaterial extends NodeMaterial {
  13164. static get type() {
  13165. return 'MeshPhongNodeMaterial';
  13166. }
  13167. /**
  13168. * Constructs a new mesh lambert node material.
  13169. *
  13170. * @param {Object?} parameters - The configuration parameter.
  13171. */
  13172. constructor( parameters ) {
  13173. super();
  13174. /**
  13175. * This flag can be used for type testing.
  13176. *
  13177. * @type {Boolean}
  13178. * @readonly
  13179. * @default true
  13180. */
  13181. this.isMeshPhongNodeMaterial = true;
  13182. /**
  13183. * Set to `true` because phong materials react on lights.
  13184. *
  13185. * @type {Boolean}
  13186. * @default true
  13187. */
  13188. this.lights = true;
  13189. /**
  13190. * The shininess of phong materials is by default inferred from the `shininess`
  13191. * property. This node property allows to overwrite the default
  13192. * and define the shininess with a node instead.
  13193. *
  13194. * If you don't want to overwrite the shininess but modify the existing
  13195. * value instead, use {@link module:MaterialNode.materialShininess}.
  13196. *
  13197. * @type {Node<float>?}
  13198. * @default null
  13199. */
  13200. this.shininessNode = null;
  13201. /**
  13202. * The specular color of phong materials is by default inferred from the
  13203. * `specular` property. This node property allows to overwrite the default
  13204. * and define the specular color with a node instead.
  13205. *
  13206. * If you don't want to overwrite the specular color but modify the existing
  13207. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13208. *
  13209. * @type {Node<vec3>?}
  13210. * @default null
  13211. */
  13212. this.specularNode = null;
  13213. this.setDefaultValues( _defaultValues$7 );
  13214. this.setValues( parameters );
  13215. }
  13216. /**
  13217. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13218. * to implement the default environment mapping.
  13219. *
  13220. * @param {NodeBuilder} builder - The current node builder.
  13221. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13222. */
  13223. setupEnvironment( builder ) {
  13224. const envNode = super.setupEnvironment( builder );
  13225. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13226. }
  13227. /**
  13228. * Setups the lighting model.
  13229. *
  13230. * @return {PhongLightingModel} The lighting model.
  13231. */
  13232. setupLightingModel( /*builder*/ ) {
  13233. return new PhongLightingModel();
  13234. }
  13235. /**
  13236. * Setups the phong specific node variables.
  13237. *
  13238. * @param {NodeBuilder} builder - The current node builder.
  13239. */
  13240. setupVariants( /*builder*/ ) {
  13241. // SHININESS
  13242. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13243. shininess.assign( shininessNode );
  13244. // SPECULAR COLOR
  13245. const specularNode = this.specularNode || materialSpecular;
  13246. specularColor.assign( specularNode );
  13247. }
  13248. copy( source ) {
  13249. this.shininessNode = source.shininessNode;
  13250. this.specularNode = source.specularNode;
  13251. return super.copy( source );
  13252. }
  13253. }
  13254. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13255. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13256. return float( 0 );
  13257. }
  13258. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13259. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13260. return geometryRoughness;
  13261. } );
  13262. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13263. const { roughness } = inputs;
  13264. const geometryRoughness = getGeometryRoughness();
  13265. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13266. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13267. roughnessFactor = roughnessFactor.min( 1.0 );
  13268. return roughnessFactor;
  13269. } );
  13270. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13271. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13272. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13273. const a2 = alpha.pow2();
  13274. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13275. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13276. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13277. } ).setLayout( {
  13278. name: 'V_GGX_SmithCorrelated',
  13279. type: 'float',
  13280. inputs: [
  13281. { name: 'alpha', type: 'float' },
  13282. { name: 'dotNL', type: 'float' },
  13283. { name: 'dotNV', type: 'float' }
  13284. ]
  13285. } ); // validated
  13286. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13287. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13288. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13289. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13290. const v = div( 0.5, gv.add( gl ) );
  13291. return v.saturate();
  13292. } ).setLayout( {
  13293. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13294. type: 'float',
  13295. inputs: [
  13296. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13297. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13298. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13299. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13300. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13301. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13302. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13303. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13304. ]
  13305. } );
  13306. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13307. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13308. // alpha is "roughness squared" in Disney’s reparameterization
  13309. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13310. const a2 = alpha.pow2();
  13311. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13312. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13313. } ).setLayout( {
  13314. name: 'D_GGX',
  13315. type: 'float',
  13316. inputs: [
  13317. { name: 'alpha', type: 'float' },
  13318. { name: 'dotNH', type: 'float' }
  13319. ]
  13320. } ); // validated
  13321. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13322. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13323. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13324. const a2 = alphaT.mul( alphaB );
  13325. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13326. const v2 = v.dot( v );
  13327. const w2 = a2.div( v2 );
  13328. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13329. } ).setLayout( {
  13330. name: 'D_GGX_Anisotropic',
  13331. type: 'float',
  13332. inputs: [
  13333. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13334. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13335. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13336. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13337. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13338. ]
  13339. } );
  13340. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13341. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13342. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13343. const normalView = inputs.normalView || transformedNormalView;
  13344. const alpha = roughness.pow2(); // UE4's roughness
  13345. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13346. const dotNL = normalView.dot( lightDirection ).clamp();
  13347. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13348. const dotNH = normalView.dot( halfDir ).clamp();
  13349. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13350. let F = F_Schlick( { f0, f90, dotVH } );
  13351. let V, D;
  13352. if ( defined( USE_IRIDESCENCE ) ) {
  13353. F = iridescence.mix( F, f );
  13354. }
  13355. if ( defined( USE_ANISOTROPY ) ) {
  13356. const dotTL = anisotropyT.dot( lightDirection );
  13357. const dotTV = anisotropyT.dot( positionViewDirection );
  13358. const dotTH = anisotropyT.dot( halfDir );
  13359. const dotBL = anisotropyB.dot( lightDirection );
  13360. const dotBV = anisotropyB.dot( positionViewDirection );
  13361. const dotBH = anisotropyB.dot( halfDir );
  13362. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13363. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13364. } else {
  13365. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13366. D = D_GGX( { alpha, dotNH } );
  13367. }
  13368. return F.mul( V ).mul( D );
  13369. } ); // validated
  13370. // Analytical approximation of the DFG LUT, one half of the
  13371. // split-sum approximation used in indirect specular lighting.
  13372. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13373. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13374. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13375. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  13376. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  13377. const r = roughness.mul( c0 ).add( c1 );
  13378. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  13379. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  13380. return fab;
  13381. } ).setLayout( {
  13382. name: 'DFGApprox',
  13383. type: 'vec2',
  13384. inputs: [
  13385. { name: 'roughness', type: 'float' },
  13386. { name: 'dotNV', type: 'vec3' }
  13387. ]
  13388. } );
  13389. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13390. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13391. const fab = DFGApprox( { dotNV, roughness } );
  13392. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13393. } );
  13394. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13395. const x = dotVH.oneMinus().saturate();
  13396. const x2 = x.mul( x );
  13397. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13398. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13399. } ).setLayout( {
  13400. name: 'Schlick_to_F0',
  13401. type: 'vec3',
  13402. inputs: [
  13403. { name: 'f', type: 'vec3' },
  13404. { name: 'f90', type: 'float' },
  13405. { name: 'dotVH', type: 'float' }
  13406. ]
  13407. } );
  13408. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13409. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13410. const alpha = roughness.pow2();
  13411. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13412. const invAlpha = float( 1.0 ).div( alpha );
  13413. const cos2h = dotNH.pow2();
  13414. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13415. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13416. } ).setLayout( {
  13417. name: 'D_Charlie',
  13418. type: 'float',
  13419. inputs: [
  13420. { name: 'roughness', type: 'float' },
  13421. { name: 'dotNH', type: 'float' }
  13422. ]
  13423. } );
  13424. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13425. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13426. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13427. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13428. } ).setLayout( {
  13429. name: 'V_Neubelt',
  13430. type: 'float',
  13431. inputs: [
  13432. { name: 'dotNV', type: 'float' },
  13433. { name: 'dotNL', type: 'float' }
  13434. ]
  13435. } );
  13436. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13437. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13438. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13439. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13440. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13441. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13442. const V = V_Neubelt( { dotNV, dotNL } );
  13443. return sheen.mul( D ).mul( V );
  13444. } );
  13445. // Rect Area Light
  13446. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13447. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13448. // code: https://github.com/selfshadow/ltc_code/
  13449. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13450. const LUT_SIZE = 64.0;
  13451. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13452. const LUT_BIAS = 0.5 / LUT_SIZE;
  13453. const dotNV = N.dot( V ).saturate();
  13454. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13455. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13456. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13457. return uv;
  13458. } ).setLayout( {
  13459. name: 'LTC_Uv',
  13460. type: 'vec2',
  13461. inputs: [
  13462. { name: 'N', type: 'vec3' },
  13463. { name: 'V', type: 'vec3' },
  13464. { name: 'roughness', type: 'float' }
  13465. ]
  13466. } );
  13467. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13468. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13469. // An approximation of the form factor of a horizon-clipped rectangle.
  13470. const l = f.length();
  13471. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13472. } ).setLayout( {
  13473. name: 'LTC_ClippedSphereFormFactor',
  13474. type: 'float',
  13475. inputs: [
  13476. { name: 'f', type: 'vec3' }
  13477. ]
  13478. } );
  13479. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13480. const x = v1.dot( v2 );
  13481. const y = x.abs().toVar();
  13482. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13483. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13484. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13485. const v = a.div( b );
  13486. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13487. return v1.cross( v2 ).mul( theta_sintheta );
  13488. } ).setLayout( {
  13489. name: 'LTC_EdgeVectorFormFactor',
  13490. type: 'vec3',
  13491. inputs: [
  13492. { name: 'v1', type: 'vec3' },
  13493. { name: 'v2', type: 'vec3' }
  13494. ]
  13495. } );
  13496. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13497. // bail if point is on back side of plane of light
  13498. // assumes ccw winding order of light vertices
  13499. const v1 = p1.sub( p0 ).toVar();
  13500. const v2 = p3.sub( p0 ).toVar();
  13501. const lightNormal = v1.cross( v2 );
  13502. const result = vec3().toVar();
  13503. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13504. // construct orthonormal basis around N
  13505. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13506. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13507. // compute transform
  13508. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13509. // transform rect
  13510. // & project rect onto sphere
  13511. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13512. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13513. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13514. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13515. // calculate vector form factor
  13516. const vectorFormFactor = vec3( 0 ).toVar();
  13517. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13518. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13519. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13520. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13521. // adjust for horizon clipping
  13522. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13523. } );
  13524. return result;
  13525. } ).setLayout( {
  13526. name: 'LTC_Evaluate',
  13527. type: 'vec3',
  13528. inputs: [
  13529. { name: 'N', type: 'vec3' },
  13530. { name: 'V', type: 'vec3' },
  13531. { name: 'P', type: 'vec3' },
  13532. { name: 'mInv', type: 'mat3' },
  13533. { name: 'p0', type: 'vec3' },
  13534. { name: 'p1', type: 'vec3' },
  13535. { name: 'p2', type: 'vec3' },
  13536. { name: 'p3', type: 'vec3' }
  13537. ]
  13538. } );
  13539. /** @module TextureBicubic **/
  13540. // Mipped Bicubic Texture Filtering by N8
  13541. // https://www.shadertoy.com/view/Dl2SDW
  13542. const bC = 1.0 / 6.0;
  13543. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13544. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13545. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13546. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13547. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13548. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13549. // h0 and h1 are the two offset functions
  13550. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13551. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13552. const bicubic = ( textureNode, texelSize, lod ) => {
  13553. const uv = textureNode.uvNode;
  13554. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13555. const iuv = floor( uvScaled );
  13556. const fuv = fract( uvScaled );
  13557. const g0x = g0( fuv.x );
  13558. const g1x = g1( fuv.x );
  13559. const h0x = h0( fuv.x );
  13560. const h1x = h1( fuv.x );
  13561. const h0y = h0( fuv.y );
  13562. const h1y = h1( fuv.y );
  13563. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13564. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13565. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13566. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13567. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13568. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13569. return a.add( b );
  13570. };
  13571. /**
  13572. * Applies mipped bicubic texture filtering to the given texture node.
  13573. *
  13574. * @method
  13575. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13576. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13577. * @return {Node} The filtered texture sample.
  13578. */
  13579. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13580. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13581. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13582. const fLodSizeInv = div( 1.0, fLodSize );
  13583. const cLodSizeInv = div( 1.0, cLodSize );
  13584. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13585. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13586. return fract( lodNode ).mix( fSample, cSample );
  13587. } );
  13588. //
  13589. // Transmission
  13590. //
  13591. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13592. // Direction of refracted light.
  13593. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13594. // Compute rotation-independent scaling of the model matrix.
  13595. const modelScale = vec3(
  13596. length( modelMatrix[ 0 ].xyz ),
  13597. length( modelMatrix[ 1 ].xyz ),
  13598. length( modelMatrix[ 2 ].xyz )
  13599. );
  13600. // The thickness is specified in local space.
  13601. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13602. } ).setLayout( {
  13603. name: 'getVolumeTransmissionRay',
  13604. type: 'vec3',
  13605. inputs: [
  13606. { name: 'n', type: 'vec3' },
  13607. { name: 'v', type: 'vec3' },
  13608. { name: 'thickness', type: 'float' },
  13609. { name: 'ior', type: 'float' },
  13610. { name: 'modelMatrix', type: 'mat4' }
  13611. ]
  13612. } );
  13613. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13614. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13615. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13616. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13617. } ).setLayout( {
  13618. name: 'applyIorToRoughness',
  13619. type: 'float',
  13620. inputs: [
  13621. { name: 'roughness', type: 'float' },
  13622. { name: 'ior', type: 'float' }
  13623. ]
  13624. } );
  13625. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13626. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13627. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13628. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13629. const transmissionSample = vTexture.sample( fragCoord );
  13630. //const transmissionSample = viewportMipTexture( fragCoord );
  13631. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13632. return textureBicubic( transmissionSample, lod );
  13633. } );
  13634. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13635. If( attenuationDistance.notEqual( 0 ), () => {
  13636. // Compute light attenuation using Beer's law.
  13637. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13638. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13639. return transmittance;
  13640. } );
  13641. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13642. return vec3( 1.0 );
  13643. } ).setLayout( {
  13644. name: 'volumeAttenuation',
  13645. type: 'vec3',
  13646. inputs: [
  13647. { name: 'transmissionDistance', type: 'float' },
  13648. { name: 'attenuationColor', type: 'vec3' },
  13649. { name: 'attenuationDistance', type: 'float' }
  13650. ]
  13651. } );
  13652. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13653. let transmittedLight, transmittance;
  13654. if ( dispersion ) {
  13655. transmittedLight = vec4().toVar();
  13656. transmittance = vec3().toVar();
  13657. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13658. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13659. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13660. const ior = iors.element( i );
  13661. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13662. const refractedRayExit = position.add( transmissionRay );
  13663. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13664. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13665. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13666. refractionCoords.addAssign( 1.0 );
  13667. refractionCoords.divAssign( 2.0 );
  13668. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13669. // Sample framebuffer to get pixel the refracted ray hits.
  13670. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13671. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13672. transmittedLight.a.addAssign( transmissionSample.a );
  13673. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13674. } );
  13675. transmittedLight.a.divAssign( 3.0 );
  13676. } else {
  13677. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13678. const refractedRayExit = position.add( transmissionRay );
  13679. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13680. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13681. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13682. refractionCoords.addAssign( 1.0 );
  13683. refractionCoords.divAssign( 2.0 );
  13684. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13685. // Sample framebuffer to get pixel the refracted ray hits.
  13686. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13687. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13688. }
  13689. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13690. const dotNV = n.dot( v ).clamp();
  13691. // Get the specular component.
  13692. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13693. dotNV,
  13694. specularColor,
  13695. specularF90,
  13696. roughness
  13697. } ) );
  13698. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13699. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13700. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13701. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13702. } );
  13703. //
  13704. // Iridescence
  13705. //
  13706. // XYZ to linear-sRGB color space
  13707. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13708. 3.2404542, -0.969266, 0.0556434,
  13709. -1.5371385, 1.8760108, -0.2040259,
  13710. -0.4985314, 0.0415560, 1.0572252
  13711. );
  13712. // Assume air interface for top
  13713. // Note: We don't handle the case fresnel0 == 1
  13714. const Fresnel0ToIor = ( fresnel0 ) => {
  13715. const sqrtF0 = fresnel0.sqrt();
  13716. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13717. };
  13718. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13719. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13720. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13721. };
  13722. // Fresnel equations for dielectric/dielectric interfaces.
  13723. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13724. // Evaluation XYZ sensitivity curves in Fourier space
  13725. const evalSensitivity = ( OPD, shift ) => {
  13726. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13727. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13728. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13729. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13730. 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() );
  13731. 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() );
  13732. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13733. const rgb = XYZ_TO_REC709.mul( xyz );
  13734. return rgb;
  13735. };
  13736. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13737. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13738. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13739. // Evaluate the cosTheta on the base layer (Snell law)
  13740. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13741. // Handle TIR:
  13742. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13743. If( cosTheta2Sq.lessThan( 0 ), () => {
  13744. return vec3( 1.0 );
  13745. } );
  13746. const cosTheta2 = cosTheta2Sq.sqrt();
  13747. // First interface
  13748. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13749. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13750. //const R21 = R12;
  13751. const T121 = R12.oneMinus();
  13752. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13753. const phi21 = float( Math.PI ).sub( phi12 );
  13754. // Second interface
  13755. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13756. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13757. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13758. const phi23 = vec3(
  13759. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13760. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13761. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13762. );
  13763. // Phase shift
  13764. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13765. const phi = vec3( phi21 ).add( phi23 );
  13766. // Compound terms
  13767. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13768. const r123 = R123.sqrt();
  13769. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13770. // Reflectance term for m = 0 (DC term amplitude)
  13771. const C0 = R12.add( Rs );
  13772. const I = C0.toVar();
  13773. // Reflectance term for m > 0 (pairs of diracs)
  13774. const Cm = Rs.sub( T121 ).toVar();
  13775. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13776. Cm.mulAssign( r123 );
  13777. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13778. I.addAssign( Cm.mul( Sm ) );
  13779. } );
  13780. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13781. return I.max( vec3( 0.0 ) );
  13782. } ).setLayout( {
  13783. name: 'evalIridescence',
  13784. type: 'vec3',
  13785. inputs: [
  13786. { name: 'outsideIOR', type: 'float' },
  13787. { name: 'eta2', type: 'float' },
  13788. { name: 'cosTheta1', type: 'float' },
  13789. { name: 'thinFilmThickness', type: 'float' },
  13790. { name: 'baseF0', type: 'vec3' }
  13791. ]
  13792. } );
  13793. //
  13794. // Sheen
  13795. //
  13796. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13797. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13798. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13799. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13800. const dotNV = normal.dot( viewDir ).saturate();
  13801. const r2 = roughness.pow2();
  13802. const a = select(
  13803. roughness.lessThan( 0.25 ),
  13804. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13805. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13806. );
  13807. const b = select(
  13808. roughness.lessThan( 0.25 ),
  13809. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13810. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13811. );
  13812. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13813. return DG.mul( 1.0 / Math.PI ).saturate();
  13814. } );
  13815. const clearcoatF0 = vec3( 0.04 );
  13816. const clearcoatF90 = float( 1 );
  13817. /**
  13818. * Represents the lighting model for a PBR material.
  13819. *
  13820. * @augments LightingModel
  13821. */
  13822. class PhysicalLightingModel extends LightingModel {
  13823. /**
  13824. * Constructs a new physical lighting model.
  13825. *
  13826. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13827. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13828. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13829. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13830. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13831. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13832. */
  13833. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13834. super();
  13835. /**
  13836. * Whether clearcoat is supported or not.
  13837. *
  13838. * @type {Boolean}
  13839. * @default false
  13840. */
  13841. this.clearcoat = clearcoat;
  13842. /**
  13843. * Whether sheen is supported or not.
  13844. *
  13845. * @type {Boolean}
  13846. * @default false
  13847. */
  13848. this.sheen = sheen;
  13849. /**
  13850. * Whether iridescence is supported or not.
  13851. *
  13852. * @type {Boolean}
  13853. * @default false
  13854. */
  13855. this.iridescence = iridescence;
  13856. /**
  13857. * Whether anisotropy is supported or not.
  13858. *
  13859. * @type {Boolean}
  13860. * @default false
  13861. */
  13862. this.anisotropy = anisotropy;
  13863. /**
  13864. * Whether transmission is supported or not.
  13865. *
  13866. * @type {Boolean}
  13867. * @default false
  13868. */
  13869. this.transmission = transmission;
  13870. /**
  13871. * Whether dispersion is supported or not.
  13872. *
  13873. * @type {Boolean}
  13874. * @default false
  13875. */
  13876. this.dispersion = dispersion;
  13877. /**
  13878. * The clear coat radiance.
  13879. *
  13880. * @type {Node?}
  13881. * @default null
  13882. */
  13883. this.clearcoatRadiance = null;
  13884. /**
  13885. * The clear coat specular direct.
  13886. *
  13887. * @type {Node?}
  13888. * @default null
  13889. */
  13890. this.clearcoatSpecularDirect = null;
  13891. /**
  13892. * The clear coat specular indirect.
  13893. *
  13894. * @type {Node?}
  13895. * @default null
  13896. */
  13897. this.clearcoatSpecularIndirect = null;
  13898. /**
  13899. * The sheen specular direct.
  13900. *
  13901. * @type {Node?}
  13902. * @default null
  13903. */
  13904. this.sheenSpecularDirect = null;
  13905. /**
  13906. * The sheen specular indirect.
  13907. *
  13908. * @type {Node?}
  13909. * @default null
  13910. */
  13911. this.sheenSpecularIndirect = null;
  13912. /**
  13913. * The iridescence Fresnel.
  13914. *
  13915. * @type {Node?}
  13916. * @default null
  13917. */
  13918. this.iridescenceFresnel = null;
  13919. /**
  13920. * The iridescence F0.
  13921. *
  13922. * @type {Node?}
  13923. * @default null
  13924. */
  13925. this.iridescenceF0 = null;
  13926. }
  13927. /**
  13928. * Depending on what features are requested, the method prepares certain node variables
  13929. * which are later used for lighting computations.
  13930. *
  13931. * @param {ContextNode} context - The current node context.
  13932. */
  13933. start( context ) {
  13934. if ( this.clearcoat === true ) {
  13935. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13936. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13937. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13938. }
  13939. if ( this.sheen === true ) {
  13940. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13941. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13942. }
  13943. if ( this.iridescence === true ) {
  13944. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13945. this.iridescenceFresnel = evalIridescence( {
  13946. outsideIOR: float( 1.0 ),
  13947. eta2: iridescenceIOR,
  13948. cosTheta1: dotNVi,
  13949. thinFilmThickness: iridescenceThickness,
  13950. baseF0: specularColor
  13951. } );
  13952. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13953. }
  13954. if ( this.transmission === true ) {
  13955. const position = positionWorld;
  13956. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13957. const n = transformedNormalWorld;
  13958. context.backdrop = getIBLVolumeRefraction(
  13959. n,
  13960. v,
  13961. roughness,
  13962. diffuseColor,
  13963. specularColor,
  13964. specularF90, // specularF90
  13965. position, // positionWorld
  13966. modelWorldMatrix, // modelMatrix
  13967. cameraViewMatrix, // viewMatrix
  13968. cameraProjectionMatrix, // projMatrix
  13969. ior,
  13970. thickness,
  13971. attenuationColor,
  13972. attenuationDistance,
  13973. this.dispersion ? dispersion : null
  13974. );
  13975. context.backdropAlpha = transmission;
  13976. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13977. }
  13978. }
  13979. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13980. // Approximates multi-scattering in order to preserve energy.
  13981. // http://www.jcgt.org/published/0008/01/03/
  13982. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13983. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13984. const fab = DFGApprox( { roughness, dotNV } );
  13985. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13986. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13987. const Ess = fab.x.add( fab.y );
  13988. const Ems = Ess.oneMinus();
  13989. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13990. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13991. singleScatter.addAssign( FssEss );
  13992. multiScatter.addAssign( Fms.mul( Ems ) );
  13993. }
  13994. /**
  13995. * Implements the direct light.
  13996. *
  13997. * @param {Object} input - The input data.
  13998. * @param {StackNode} stack - The current stack.
  13999. * @param {NodeBuilder} builder - The current node builder.
  14000. */
  14001. direct( { lightDirection, lightColor, reflectedLight } ) {
  14002. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14003. const irradiance = dotNL.mul( lightColor );
  14004. if ( this.sheen === true ) {
  14005. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  14006. }
  14007. if ( this.clearcoat === true ) {
  14008. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  14009. const ccIrradiance = dotNLcc.mul( lightColor );
  14010. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  14011. }
  14012. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14013. 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 } ) ) );
  14014. }
  14015. /**
  14016. * This method is intended for implementing the direct light term for
  14017. * rect area light nodes.
  14018. *
  14019. * @param {Object} input - The input data.
  14020. * @param {StackNode} stack - The current stack.
  14021. * @param {NodeBuilder} builder - The current node builder.
  14022. */
  14023. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  14024. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  14025. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  14026. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  14027. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  14028. const N = transformedNormalView;
  14029. const V = positionViewDirection;
  14030. const P = positionView.toVar();
  14031. const uv = LTC_Uv( { N, V, roughness } );
  14032. const t1 = ltc_1.sample( uv ).toVar();
  14033. const t2 = ltc_2.sample( uv ).toVar();
  14034. const mInv = mat3(
  14035. vec3( t1.x, 0, t1.y ),
  14036. vec3( 0, 1, 0 ),
  14037. vec3( t1.z, 0, t1.w )
  14038. ).toVar();
  14039. // LTC Fresnel Approximation by Stephen Hill
  14040. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  14041. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  14042. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  14043. 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 } ) ) );
  14044. }
  14045. /**
  14046. * Implements the indirect lighting.
  14047. *
  14048. * @param {ContextNode} context - The current node context.
  14049. * @param {StackNode} stack - The current stack.
  14050. * @param {NodeBuilder} builder - The current node builder.
  14051. */
  14052. indirect( context, stack, builder ) {
  14053. this.indirectDiffuse( context, stack, builder );
  14054. this.indirectSpecular( context, stack, builder );
  14055. this.ambientOcclusion( context, stack, builder );
  14056. }
  14057. /**
  14058. * Implements the indirect diffuse term.
  14059. *
  14060. * @param {ContextNode} input - The current node context.
  14061. * @param {StackNode} stack - The current stack.
  14062. * @param {NodeBuilder} builder - The current node builder.
  14063. */
  14064. indirectDiffuse( { irradiance, reflectedLight } ) {
  14065. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14066. }
  14067. /**
  14068. * Implements the indirect specular term.
  14069. *
  14070. * @param {ContextNode} input - The current node context.
  14071. * @param {StackNode} stack - The current stack.
  14072. * @param {NodeBuilder} builder - The current node builder.
  14073. */
  14074. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  14075. if ( this.sheen === true ) {
  14076. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  14077. sheen,
  14078. IBLSheenBRDF( {
  14079. normal: transformedNormalView,
  14080. viewDir: positionViewDirection,
  14081. roughness: sheenRoughness
  14082. } )
  14083. ) );
  14084. }
  14085. if ( this.clearcoat === true ) {
  14086. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14087. const clearcoatEnv = EnvironmentBRDF( {
  14088. dotNV: dotNVcc,
  14089. specularColor: clearcoatF0,
  14090. specularF90: clearcoatF90,
  14091. roughness: clearcoatRoughness
  14092. } );
  14093. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  14094. }
  14095. // Both indirect specular and indirect diffuse light accumulate here
  14096. const singleScattering = vec3().toVar( 'singleScattering' );
  14097. const multiScattering = vec3().toVar( 'multiScattering' );
  14098. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  14099. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  14100. const totalScattering = singleScattering.add( multiScattering );
  14101. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  14102. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  14103. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  14104. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  14105. }
  14106. /**
  14107. * Implements the ambient occlusion term.
  14108. *
  14109. * @param {ContextNode} input - The current node context.
  14110. * @param {StackNode} stack - The current stack.
  14111. * @param {NodeBuilder} builder - The current node builder.
  14112. */
  14113. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  14114. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14115. const aoNV = dotNV.add( ambientOcclusion );
  14116. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  14117. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  14118. if ( this.clearcoat === true ) {
  14119. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  14120. }
  14121. if ( this.sheen === true ) {
  14122. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  14123. }
  14124. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14125. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14126. }
  14127. /**
  14128. * Used for final lighting accumulations depending on the requested features.
  14129. *
  14130. * @param {ContextNode} context - The current node context.
  14131. * @param {StackNode} stack - The current stack.
  14132. * @param {NodeBuilder} builder - The current node builder.
  14133. */
  14134. finish( context ) {
  14135. const { outgoingLight } = context;
  14136. if ( this.clearcoat === true ) {
  14137. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14138. const Fcc = F_Schlick( {
  14139. dotVH: dotNVcc,
  14140. f0: clearcoatF0,
  14141. f90: clearcoatF90
  14142. } );
  14143. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14144. outgoingLight.assign( clearcoatLight );
  14145. }
  14146. if ( this.sheen === true ) {
  14147. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14148. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14149. outgoingLight.assign( sheenLight );
  14150. }
  14151. }
  14152. }
  14153. // These defines must match with PMREMGenerator
  14154. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14155. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  14156. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14157. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  14158. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14159. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14160. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14161. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14162. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14163. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14164. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14165. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14166. // These shader functions convert between the UV coordinates of a single face of
  14167. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14168. // sampling a textureCube (not generally normalized ).
  14169. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14170. const absDirection = vec3( abs( direction ) ).toVar();
  14171. const face = float( -1 ).toVar();
  14172. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14173. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14174. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14175. } ).Else( () => {
  14176. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14177. } );
  14178. } ).Else( () => {
  14179. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14180. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14181. } ).Else( () => {
  14182. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14183. } );
  14184. } );
  14185. return face;
  14186. } ).setLayout( {
  14187. name: 'getFace',
  14188. type: 'float',
  14189. inputs: [
  14190. { name: 'direction', type: 'vec3' }
  14191. ]
  14192. } );
  14193. // RH coordinate system; PMREM face-indexing convention
  14194. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14195. const uv = vec2().toVar();
  14196. If( face.equal( 0.0 ), () => {
  14197. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14198. } ).ElseIf( face.equal( 1.0 ), () => {
  14199. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14200. } ).ElseIf( face.equal( 2.0 ), () => {
  14201. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14202. } ).ElseIf( face.equal( 3.0 ), () => {
  14203. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14204. } ).ElseIf( face.equal( 4.0 ), () => {
  14205. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14206. } ).Else( () => {
  14207. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14208. } );
  14209. return mul( 0.5, uv.add( 1.0 ) );
  14210. } ).setLayout( {
  14211. name: 'getUV',
  14212. type: 'vec2',
  14213. inputs: [
  14214. { name: 'direction', type: 'vec3' },
  14215. { name: 'face', type: 'float' }
  14216. ]
  14217. } );
  14218. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14219. const mip = float( 0.0 ).toVar();
  14220. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14221. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14222. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14223. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14224. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14225. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14226. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14227. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14228. } ).Else( () => {
  14229. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14230. } );
  14231. return mip;
  14232. } ).setLayout( {
  14233. name: 'roughnessToMip',
  14234. type: 'float',
  14235. inputs: [
  14236. { name: 'roughness', type: 'float' }
  14237. ]
  14238. } );
  14239. // RH coordinate system; PMREM face-indexing convention
  14240. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14241. const uv = uv_immutable.toVar();
  14242. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14243. const direction = vec3( uv, 1.0 ).toVar();
  14244. If( face.equal( 0.0 ), () => {
  14245. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14246. } ).ElseIf( face.equal( 1.0 ), () => {
  14247. direction.assign( direction.xzy );
  14248. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  14249. } ).ElseIf( face.equal( 2.0 ), () => {
  14250. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  14251. } ).ElseIf( face.equal( 3.0 ), () => {
  14252. direction.assign( direction.zyx );
  14253. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  14254. } ).ElseIf( face.equal( 4.0 ), () => {
  14255. direction.assign( direction.xzy );
  14256. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  14257. } ).ElseIf( face.equal( 5.0 ), () => {
  14258. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  14259. } );
  14260. return direction;
  14261. } ).setLayout( {
  14262. name: 'getDirection',
  14263. type: 'vec3',
  14264. inputs: [
  14265. { name: 'uv', type: 'vec2' },
  14266. { name: 'face', type: 'float' }
  14267. ]
  14268. } );
  14269. //
  14270. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14271. const roughness = float( roughness_immutable );
  14272. const sampleDir = vec3( sampleDir_immutable );
  14273. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14274. const mipF = fract( mip );
  14275. const mipInt = floor( mip );
  14276. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14277. If( mipF.notEqual( 0.0 ), () => {
  14278. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14279. color0.assign( mix( color0, color1, mipF ) );
  14280. } );
  14281. return color0;
  14282. } );
  14283. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14284. const mipInt = float( mipInt_immutable ).toVar();
  14285. const direction = vec3( direction_immutable );
  14286. const face = float( getFace( direction ) ).toVar();
  14287. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14288. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14289. const faceSize = float( exp2( mipInt ) ).toVar();
  14290. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14291. If( face.greaterThan( 2.0 ), () => {
  14292. uv.y.addAssign( faceSize );
  14293. face.subAssign( 3.0 );
  14294. } );
  14295. uv.x.addAssign( face.mul( faceSize ) );
  14296. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14297. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14298. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14299. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14300. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14301. } );
  14302. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14303. const cosTheta = cos( theta );
  14304. // Rodrigues' axis-angle rotation
  14305. const sampleDirection = outputDirection.mul( cosTheta )
  14306. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14307. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14308. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14309. } );
  14310. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14311. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14312. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14313. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14314. } );
  14315. axis.assign( normalize( axis ) );
  14316. const gl_FragColor = vec3().toVar();
  14317. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14318. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14319. If( i.greaterThanEqual( samples ), () => {
  14320. Break();
  14321. } );
  14322. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14323. 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 } ) ) );
  14324. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14325. } );
  14326. return vec4( gl_FragColor, 1 );
  14327. } );
  14328. /** @module PMREMNode **/
  14329. let _generator = null;
  14330. const _cache = new WeakMap();
  14331. /**
  14332. * Generates the cubeUV size based on the given image height.
  14333. *
  14334. * @private
  14335. * @param {Number} imageHeight - The image height.
  14336. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14337. */
  14338. function _generateCubeUVSize( imageHeight ) {
  14339. const maxMip = Math.log2( imageHeight ) - 2;
  14340. const texelHeight = 1.0 / imageHeight;
  14341. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14342. return { texelWidth, texelHeight, maxMip };
  14343. }
  14344. /**
  14345. * Generates a PMREM from the given texture .
  14346. *
  14347. * @private
  14348. * @param {Texture} texture - The texture to create the PMREM for.
  14349. * @return {Texture} The PMREM.
  14350. */
  14351. function _getPMREMFromTexture( texture ) {
  14352. let cacheTexture = _cache.get( texture );
  14353. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  14354. if ( pmremVersion !== texture.pmremVersion ) {
  14355. const image = texture.image;
  14356. if ( texture.isCubeTexture ) {
  14357. if ( isCubeMapReady( image ) ) {
  14358. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14359. } else {
  14360. return null;
  14361. }
  14362. } else {
  14363. if ( isEquirectangularMapReady( image ) ) {
  14364. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14365. } else {
  14366. return null;
  14367. }
  14368. }
  14369. cacheTexture.pmremVersion = texture.pmremVersion;
  14370. _cache.set( texture, cacheTexture );
  14371. }
  14372. return cacheTexture.texture;
  14373. }
  14374. /**
  14375. * This node represents a PMREM which is a special type of preprocessed
  14376. * environment map intended for PBR materials.
  14377. *
  14378. * ```js
  14379. * const material = new MeshStandardNodeMaterial();
  14380. * material.envNode = pmremTexture( envMap );
  14381. * ```
  14382. *
  14383. * @augments TempNode
  14384. */
  14385. class PMREMNode extends TempNode {
  14386. static get type() {
  14387. return 'PMREMNode';
  14388. }
  14389. /**
  14390. * Constructs a new function overloading node.
  14391. *
  14392. * @param {Texture} value - The input texture.
  14393. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14394. * @param {Node<float>} [levelNode=null] - The level node.
  14395. */
  14396. constructor( value, uvNode = null, levelNode = null ) {
  14397. super( 'vec3' );
  14398. /**
  14399. * Reference to the input texture.
  14400. *
  14401. * @private
  14402. * @type {Texture}
  14403. */
  14404. this._value = value;
  14405. /**
  14406. * Reference to the generated PMREM.
  14407. *
  14408. * @private
  14409. * @type {Texture | null}
  14410. * @default null
  14411. */
  14412. this._pmrem = null;
  14413. /**
  14414. * The uv node.
  14415. *
  14416. * @type {Node<vec2>}
  14417. */
  14418. this.uvNode = uvNode;
  14419. /**
  14420. * The level node.
  14421. *
  14422. * @type {Node<float>}
  14423. */
  14424. this.levelNode = levelNode;
  14425. /**
  14426. * Reference to a PMREM generator.
  14427. *
  14428. * @private
  14429. * @type {PMREMGenerator}
  14430. * @default null
  14431. */
  14432. this._generator = null;
  14433. const defaultTexture = new Texture();
  14434. defaultTexture.isRenderTargetTexture = true;
  14435. /**
  14436. * The texture node holding the generated PMREM.
  14437. *
  14438. * @private
  14439. * @type {TextureNode}
  14440. */
  14441. this._texture = texture( defaultTexture );
  14442. /**
  14443. * A uniform representing the PMREM's width.
  14444. *
  14445. * @private
  14446. * @type {UniformNode<float>}
  14447. */
  14448. this._width = uniform( 0 );
  14449. /**
  14450. * A uniform representing the PMREM's height.
  14451. *
  14452. * @private
  14453. * @type {UniformNode<float>}
  14454. */
  14455. this._height = uniform( 0 );
  14456. /**
  14457. * A uniform representing the PMREM's max Mip.
  14458. *
  14459. * @private
  14460. * @type {UniformNode<float>}
  14461. */
  14462. this._maxMip = uniform( 0 );
  14463. /**
  14464. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14465. *
  14466. * @type {String}
  14467. * @default 'render'
  14468. */
  14469. this.updateBeforeType = NodeUpdateType.RENDER;
  14470. }
  14471. set value( value ) {
  14472. this._value = value;
  14473. this._pmrem = null;
  14474. }
  14475. /**
  14476. * The node's texture value.
  14477. *
  14478. * @type {Texture}
  14479. */
  14480. get value() {
  14481. return this._value;
  14482. }
  14483. /**
  14484. * Uses the given PMREM texture to update internal values.
  14485. *
  14486. * @param {Texture} texture - The PMREM texture.
  14487. */
  14488. updateFromTexture( texture ) {
  14489. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14490. this._texture.value = texture;
  14491. this._width.value = cubeUVSize.texelWidth;
  14492. this._height.value = cubeUVSize.texelHeight;
  14493. this._maxMip.value = cubeUVSize.maxMip;
  14494. }
  14495. updateBefore() {
  14496. let pmrem = this._pmrem;
  14497. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  14498. const texture = this._value;
  14499. if ( pmremVersion !== texture.pmremVersion ) {
  14500. if ( texture.isPMREMTexture === true ) {
  14501. pmrem = texture;
  14502. } else {
  14503. pmrem = _getPMREMFromTexture( texture );
  14504. }
  14505. if ( pmrem !== null ) {
  14506. this._pmrem = pmrem;
  14507. this.updateFromTexture( pmrem );
  14508. }
  14509. }
  14510. }
  14511. setup( builder ) {
  14512. if ( _generator === null ) {
  14513. _generator = builder.createPMREMGenerator();
  14514. }
  14515. //
  14516. this.updateBefore( builder );
  14517. //
  14518. let uvNode = this.uvNode;
  14519. if ( uvNode === null && builder.context.getUV ) {
  14520. uvNode = builder.context.getUV( this );
  14521. }
  14522. //
  14523. const texture = this.value;
  14524. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14525. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14526. }
  14527. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14528. //
  14529. let levelNode = this.levelNode;
  14530. if ( levelNode === null && builder.context.getTextureLevel ) {
  14531. levelNode = builder.context.getTextureLevel( this );
  14532. }
  14533. //
  14534. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14535. }
  14536. }
  14537. /**
  14538. * Returns `true` if the given cube map image has been fully loaded.
  14539. *
  14540. * @private
  14541. * @param {Array<(Image|Object)>} image - The cube map image.
  14542. * @return {Boolean} Whether the given cube map is ready or not.
  14543. */
  14544. function isCubeMapReady( image ) {
  14545. if ( image === null || image === undefined ) return false;
  14546. let count = 0;
  14547. const length = 6;
  14548. for ( let i = 0; i < length; i ++ ) {
  14549. if ( image[ i ] !== undefined ) count ++;
  14550. }
  14551. return count === length;
  14552. }
  14553. /**
  14554. * Returns `true` if the given equirectangular image has been fully loaded.
  14555. *
  14556. * @private
  14557. * @param {(Image|Object)} image - The equirectangular image.
  14558. * @return {Boolean} Whether the given cube map is ready or not.
  14559. */
  14560. function isEquirectangularMapReady( image ) {
  14561. if ( image === null || image === undefined ) return false;
  14562. return image.height > 0;
  14563. }
  14564. /**
  14565. * TSL function for creating a PMREM node.
  14566. *
  14567. * @function
  14568. * @param {Texture} value - The input texture.
  14569. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14570. * @param {Node<float>} [levelNode=null] - The level node.
  14571. * @returns {PMREMNode}
  14572. */
  14573. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14574. const _envNodeCache = new WeakMap();
  14575. /**
  14576. * Represents a physical model for Image-based lighting (IBL). The environment
  14577. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14578. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14579. *
  14580. * @augments LightingNode
  14581. */
  14582. class EnvironmentNode extends LightingNode {
  14583. static get type() {
  14584. return 'EnvironmentNode';
  14585. }
  14586. /**
  14587. * Constructs a new environment node.
  14588. *
  14589. * @param {Node} [envNode=null] - A node representing the environment.
  14590. */
  14591. constructor( envNode = null ) {
  14592. super();
  14593. /**
  14594. * A node representing the environment.
  14595. *
  14596. * @type {Node?}
  14597. * @default null
  14598. */
  14599. this.envNode = envNode;
  14600. }
  14601. setup( builder ) {
  14602. const { material } = builder;
  14603. let envNode = this.envNode;
  14604. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14605. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14606. let cacheEnvNode = _envNodeCache.get( value );
  14607. if ( cacheEnvNode === undefined ) {
  14608. cacheEnvNode = pmremTexture( value );
  14609. _envNodeCache.set( value, cacheEnvNode );
  14610. }
  14611. envNode = cacheEnvNode;
  14612. }
  14613. //
  14614. const envMap = material.envMap;
  14615. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14616. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14617. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14618. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14619. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14620. const isolateRadiance = cache( radiance );
  14621. const isolateIrradiance = cache( irradiance );
  14622. //
  14623. builder.context.radiance.addAssign( isolateRadiance );
  14624. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14625. //
  14626. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14627. if ( clearcoatRadiance ) {
  14628. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14629. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14630. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14631. }
  14632. }
  14633. }
  14634. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14635. let reflectVec = null;
  14636. return {
  14637. getUV: () => {
  14638. if ( reflectVec === null ) {
  14639. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14640. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14641. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14642. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14643. }
  14644. return reflectVec;
  14645. },
  14646. getTextureLevel: () => {
  14647. return roughnessNode;
  14648. }
  14649. };
  14650. };
  14651. const createIrradianceContext = ( normalWorldNode ) => {
  14652. return {
  14653. getUV: () => {
  14654. return normalWorldNode;
  14655. },
  14656. getTextureLevel: () => {
  14657. return float( 1.0 );
  14658. }
  14659. };
  14660. };
  14661. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14662. /**
  14663. * Node material version of `MeshStandardMaterial`.
  14664. *
  14665. * @augments NodeMaterial
  14666. */
  14667. class MeshStandardNodeMaterial extends NodeMaterial {
  14668. static get type() {
  14669. return 'MeshStandardNodeMaterial';
  14670. }
  14671. /**
  14672. * Constructs a new mesh standard node material.
  14673. *
  14674. * @param {Object?} parameters - The configuration parameter.
  14675. */
  14676. constructor( parameters ) {
  14677. super();
  14678. /**
  14679. * This flag can be used for type testing.
  14680. *
  14681. * @type {Boolean}
  14682. * @readonly
  14683. * @default true
  14684. */
  14685. this.isMeshStandardNodeMaterial = true;
  14686. /**
  14687. * Set to `true` because standard materials react on lights.
  14688. *
  14689. * @type {Boolean}
  14690. * @default true
  14691. */
  14692. this.lights = true;
  14693. /**
  14694. * The emissive color of standard materials is by default inferred from the `emissive`,
  14695. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14696. * overwrite the default and define the emissive color with a node instead.
  14697. *
  14698. * If you don't want to overwrite the emissive color but modify the existing
  14699. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14700. *
  14701. * @type {Node<vec3>?}
  14702. * @default null
  14703. */
  14704. this.emissiveNode = null;
  14705. /**
  14706. * The metalness of standard materials is by default inferred from the `metalness`,
  14707. * and `metalnessMap` properties. This node property allows to
  14708. * overwrite the default and define the metalness with a node instead.
  14709. *
  14710. * If you don't want to overwrite the metalness but modify the existing
  14711. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14712. *
  14713. * @type {Node<float>?}
  14714. * @default null
  14715. */
  14716. this.metalnessNode = null;
  14717. /**
  14718. * The roughness of standard materials is by default inferred from the `roughness`,
  14719. * and `roughnessMap` properties. This node property allows to
  14720. * overwrite the default and define the roughness with a node instead.
  14721. *
  14722. * If you don't want to overwrite the roughness but modify the existing
  14723. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14724. *
  14725. * @type {Node<float>?}
  14726. * @default null
  14727. */
  14728. this.roughnessNode = null;
  14729. this.setDefaultValues( _defaultValues$6 );
  14730. this.setValues( parameters );
  14731. }
  14732. /**
  14733. * Overwritten since this type of material uses {@link EnvironmentNode}
  14734. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14735. * method honors `Scene.environment`.
  14736. *
  14737. * @param {NodeBuilder} builder - The current node builder.
  14738. * @return {EnvironmentNode<vec3>?} The environment node.
  14739. */
  14740. setupEnvironment( builder ) {
  14741. let envNode = super.setupEnvironment( builder );
  14742. if ( envNode === null && builder.environmentNode ) {
  14743. envNode = builder.environmentNode;
  14744. }
  14745. return envNode ? new EnvironmentNode( envNode ) : null;
  14746. }
  14747. /**
  14748. * Setups the lighting model.
  14749. *
  14750. * @return {PhysicalLightingModel} The lighting model.
  14751. */
  14752. setupLightingModel( /*builder*/ ) {
  14753. return new PhysicalLightingModel();
  14754. }
  14755. /**
  14756. * Setups the specular related node variables.
  14757. */
  14758. setupSpecular() {
  14759. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14760. specularColor.assign( specularColorNode );
  14761. specularF90.assign( 1.0 );
  14762. }
  14763. /**
  14764. * Setups the standard specific node variables.
  14765. *
  14766. * @param {NodeBuilder} builder - The current node builder.
  14767. */
  14768. setupVariants() {
  14769. // METALNESS
  14770. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14771. metalness.assign( metalnessNode );
  14772. // ROUGHNESS
  14773. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14774. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14775. roughness.assign( roughnessNode );
  14776. // SPECULAR COLOR
  14777. this.setupSpecular();
  14778. // DIFFUSE COLOR
  14779. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14780. }
  14781. copy( source ) {
  14782. this.emissiveNode = source.emissiveNode;
  14783. this.metalnessNode = source.metalnessNode;
  14784. this.roughnessNode = source.roughnessNode;
  14785. return super.copy( source );
  14786. }
  14787. }
  14788. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14789. /**
  14790. * Node material version of `MeshPhysicalMaterial`.
  14791. *
  14792. * @augments MeshStandardNodeMaterial
  14793. */
  14794. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14795. static get type() {
  14796. return 'MeshPhysicalNodeMaterial';
  14797. }
  14798. /**
  14799. * Constructs a new mesh physical node material.
  14800. *
  14801. * @param {Object?} parameters - The configuration parameter.
  14802. */
  14803. constructor( parameters ) {
  14804. super();
  14805. /**
  14806. * This flag can be used for type testing.
  14807. *
  14808. * @type {Boolean}
  14809. * @readonly
  14810. * @default true
  14811. */
  14812. this.isMeshPhysicalNodeMaterial = true;
  14813. /**
  14814. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14815. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14816. * and define the clearcoat with a node instead.
  14817. *
  14818. * If you don't want to overwrite the clearcoat but modify the existing
  14819. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14820. *
  14821. * @type {Node<float>?}
  14822. * @default null
  14823. */
  14824. this.clearcoatNode = null;
  14825. /**
  14826. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14827. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14828. * and define the clearcoat roughness with a node instead.
  14829. *
  14830. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14831. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14832. *
  14833. * @type {Node<float>?}
  14834. * @default null
  14835. */
  14836. this.clearcoatRoughnessNode = null;
  14837. /**
  14838. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14839. * property. This node property allows to overwrite the default
  14840. * and define the clearcoat normal with a node instead.
  14841. *
  14842. * If you don't want to overwrite the clearcoat normal but modify the existing
  14843. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14844. *
  14845. * @type {Node<vec3>?}
  14846. * @default null
  14847. */
  14848. this.clearcoatNormalNode = null;
  14849. /**
  14850. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14851. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14852. * and define the sheen with a node instead.
  14853. *
  14854. * If you don't want to overwrite the sheen but modify the existing
  14855. * value instead, use {@link module:MaterialNode.materialSheen}.
  14856. *
  14857. * @type {Node<vec3>?}
  14858. * @default null
  14859. */
  14860. this.sheenNode = null;
  14861. /**
  14862. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14863. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14864. * and define the sheen roughness with a node instead.
  14865. *
  14866. * If you don't want to overwrite the sheen roughness but modify the existing
  14867. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14868. *
  14869. * @type {Node<float>?}
  14870. * @default null
  14871. */
  14872. this.sheenRoughnessNode = null;
  14873. /**
  14874. * The iridescence of physical materials is by default inferred from the `iridescence`
  14875. * property. This node property allows to overwrite the default
  14876. * and define the iridescence with a node instead.
  14877. *
  14878. * If you don't want to overwrite the iridescence but modify the existing
  14879. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14880. *
  14881. * @type {Node<float>?}
  14882. * @default null
  14883. */
  14884. this.iridescenceNode = null;
  14885. /**
  14886. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14887. * property. This node property allows to overwrite the default
  14888. * and define the iridescence IOR with a node instead.
  14889. *
  14890. * If you don't want to overwrite the iridescence IOR but modify the existing
  14891. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14892. *
  14893. * @type {Node<float>?}
  14894. * @default null
  14895. */
  14896. this.iridescenceIORNode = null;
  14897. /**
  14898. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14899. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14900. * and define the iridescence thickness with a node instead.
  14901. *
  14902. * If you don't want to overwrite the iridescence thickness but modify the existing
  14903. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14904. *
  14905. * @type {Node<float>?}
  14906. * @default null
  14907. */
  14908. this.iridescenceThicknessNode = null;
  14909. /**
  14910. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14911. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14912. * and define the specular intensity with a node instead.
  14913. *
  14914. * If you don't want to overwrite the specular intensity but modify the existing
  14915. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14916. *
  14917. * @type {Node<float>?}
  14918. * @default null
  14919. */
  14920. this.specularIntensityNode = null;
  14921. /**
  14922. * The specular color of physical materials is by default inferred from the `specularColor`
  14923. * and `specularColorMap` properties. This node property allows to overwrite the default
  14924. * and define the specular color with a node instead.
  14925. *
  14926. * If you don't want to overwrite the specular color but modify the existing
  14927. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14928. *
  14929. * @type {Node<vec3>?}
  14930. * @default null
  14931. */
  14932. this.specularColorNode = null;
  14933. /**
  14934. * The ior of physical materials is by default inferred from the `ior`
  14935. * property. This node property allows to overwrite the default
  14936. * and define the ior with a node instead.
  14937. *
  14938. * If you don't want to overwrite the ior but modify the existing
  14939. * value instead, use {@link module:MaterialNode.materialIOR}.
  14940. *
  14941. * @type {Node<float>?}
  14942. * @default null
  14943. */
  14944. this.iorNode = null;
  14945. /**
  14946. * The transmission of physical materials is by default inferred from the `transmission` and
  14947. * `transmissionMap` properties. This node property allows to overwrite the default
  14948. * and define the transmission with a node instead.
  14949. *
  14950. * If you don't want to overwrite the transmission but modify the existing
  14951. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14952. *
  14953. * @type {Node<float>?}
  14954. * @default null
  14955. */
  14956. this.transmissionNode = null;
  14957. /**
  14958. * The thickness of physical materials is by default inferred from the `thickness` and
  14959. * `thicknessMap` properties. This node property allows to overwrite the default
  14960. * and define the thickness with a node instead.
  14961. *
  14962. * If you don't want to overwrite the thickness but modify the existing
  14963. * value instead, use {@link module:MaterialNode.materialThickness}.
  14964. *
  14965. * @type {Node<float>?}
  14966. * @default null
  14967. */
  14968. this.thicknessNode = null;
  14969. /**
  14970. * The attenuation distance of physical materials is by default inferred from the
  14971. * `attenuationDistance` property. This node property allows to overwrite the default
  14972. * and define the attenuation distance with a node instead.
  14973. *
  14974. * If you don't want to overwrite the attenuation distance but modify the existing
  14975. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14976. *
  14977. * @type {Node<float>?}
  14978. * @default null
  14979. */
  14980. this.attenuationDistanceNode = null;
  14981. /**
  14982. * The attenuation color of physical materials is by default inferred from the
  14983. * `attenuationColor` property. This node property allows to overwrite the default
  14984. * and define the attenuation color with a node instead.
  14985. *
  14986. * If you don't want to overwrite the attenuation color but modify the existing
  14987. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14988. *
  14989. * @type {Node<vec3>?}
  14990. * @default null
  14991. */
  14992. this.attenuationColorNode = null;
  14993. /**
  14994. * The dispersion of physical materials is by default inferred from the
  14995. * `dispersion` property. This node property allows to overwrite the default
  14996. * and define the dispersion with a node instead.
  14997. *
  14998. * If you don't want to overwrite the dispersion but modify the existing
  14999. * value instead, use {@link module:MaterialNode.materialDispersion}.
  15000. *
  15001. * @type {Node<float>?}
  15002. * @default null
  15003. */
  15004. this.dispersionNode = null;
  15005. /**
  15006. * The anisotropy of physical materials is by default inferred from the
  15007. * `anisotropy` property. This node property allows to overwrite the default
  15008. * and define the anisotropy with a node instead.
  15009. *
  15010. * If you don't want to overwrite the anisotropy but modify the existing
  15011. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  15012. *
  15013. * @type {Node<float>?}
  15014. * @default null
  15015. */
  15016. this.anisotropyNode = null;
  15017. this.setDefaultValues( _defaultValues$5 );
  15018. this.setValues( parameters );
  15019. }
  15020. /**
  15021. * Whether the lighting model should use clearcoat or not.
  15022. *
  15023. * @type {Boolean}
  15024. * @default true
  15025. */
  15026. get useClearcoat() {
  15027. return this.clearcoat > 0 || this.clearcoatNode !== null;
  15028. }
  15029. /**
  15030. * Whether the lighting model should use iridescence or not.
  15031. *
  15032. * @type {Boolean}
  15033. * @default true
  15034. */
  15035. get useIridescence() {
  15036. return this.iridescence > 0 || this.iridescenceNode !== null;
  15037. }
  15038. /**
  15039. * Whether the lighting model should use sheen or not.
  15040. *
  15041. * @type {Boolean}
  15042. * @default true
  15043. */
  15044. get useSheen() {
  15045. return this.sheen > 0 || this.sheenNode !== null;
  15046. }
  15047. /**
  15048. * Whether the lighting model should use anisotropy or not.
  15049. *
  15050. * @type {Boolean}
  15051. * @default true
  15052. */
  15053. get useAnisotropy() {
  15054. return this.anisotropy > 0 || this.anisotropyNode !== null;
  15055. }
  15056. /**
  15057. * Whether the lighting model should use transmission or not.
  15058. *
  15059. * @type {Boolean}
  15060. * @default true
  15061. */
  15062. get useTransmission() {
  15063. return this.transmission > 0 || this.transmissionNode !== null;
  15064. }
  15065. /**
  15066. * Whether the lighting model should use dispersion or not.
  15067. *
  15068. * @type {Boolean}
  15069. * @default true
  15070. */
  15071. get useDispersion() {
  15072. return this.dispersion > 0 || this.dispersionNode !== null;
  15073. }
  15074. /**
  15075. * Setups the specular related node variables.
  15076. */
  15077. setupSpecular() {
  15078. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  15079. ior.assign( iorNode );
  15080. 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 ) );
  15081. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  15082. }
  15083. /**
  15084. * Setups the lighting model.
  15085. *
  15086. * @return {PhysicalLightingModel} The lighting model.
  15087. */
  15088. setupLightingModel( /*builder*/ ) {
  15089. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  15090. }
  15091. /**
  15092. * Setups the physical specific node variables.
  15093. *
  15094. * @param {NodeBuilder} builder - The current node builder.
  15095. */
  15096. setupVariants( builder ) {
  15097. super.setupVariants( builder );
  15098. // CLEARCOAT
  15099. if ( this.useClearcoat ) {
  15100. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  15101. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  15102. clearcoat.assign( clearcoatNode );
  15103. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  15104. }
  15105. // SHEEN
  15106. if ( this.useSheen ) {
  15107. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  15108. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  15109. sheen.assign( sheenNode );
  15110. sheenRoughness.assign( sheenRoughnessNode );
  15111. }
  15112. // IRIDESCENCE
  15113. if ( this.useIridescence ) {
  15114. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  15115. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  15116. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  15117. iridescence.assign( iridescenceNode );
  15118. iridescenceIOR.assign( iridescenceIORNode );
  15119. iridescenceThickness.assign( iridescenceThicknessNode );
  15120. }
  15121. // ANISOTROPY
  15122. if ( this.useAnisotropy ) {
  15123. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  15124. anisotropy.assign( anisotropyV.length() );
  15125. If( anisotropy.equal( 0.0 ), () => {
  15126. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  15127. } ).Else( () => {
  15128. anisotropyV.divAssign( vec2( anisotropy ) );
  15129. anisotropy.assign( anisotropy.saturate() );
  15130. } );
  15131. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  15132. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  15133. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  15134. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15135. }
  15136. // TRANSMISSION
  15137. if ( this.useTransmission ) {
  15138. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15139. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15140. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15141. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15142. transmission.assign( transmissionNode );
  15143. thickness.assign( thicknessNode );
  15144. attenuationDistance.assign( attenuationDistanceNode );
  15145. attenuationColor.assign( attenuationColorNode );
  15146. if ( this.useDispersion ) {
  15147. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15148. dispersion.assign( dispersionNode );
  15149. }
  15150. }
  15151. }
  15152. /**
  15153. * Setups the clearcoat normal node.
  15154. *
  15155. * @return {Node<vec3>} The clearcoat normal.
  15156. */
  15157. setupClearcoatNormal() {
  15158. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15159. }
  15160. setup( builder ) {
  15161. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15162. super.setup( builder );
  15163. }
  15164. copy( source ) {
  15165. this.clearcoatNode = source.clearcoatNode;
  15166. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15167. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15168. this.sheenNode = source.sheenNode;
  15169. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15170. this.iridescenceNode = source.iridescenceNode;
  15171. this.iridescenceIORNode = source.iridescenceIORNode;
  15172. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15173. this.specularIntensityNode = source.specularIntensityNode;
  15174. this.specularColorNode = source.specularColorNode;
  15175. this.transmissionNode = source.transmissionNode;
  15176. this.thicknessNode = source.thicknessNode;
  15177. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15178. this.attenuationColorNode = source.attenuationColorNode;
  15179. this.dispersionNode = source.dispersionNode;
  15180. this.anisotropyNode = source.anisotropyNode;
  15181. return super.copy( source );
  15182. }
  15183. }
  15184. /** @module MeshSSSNodeMaterial **/
  15185. /**
  15186. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15187. *
  15188. * @augments PhysicalLightingModel
  15189. */
  15190. class SSSLightingModel extends PhysicalLightingModel {
  15191. /**
  15192. * Constructs a new physical lighting model.
  15193. *
  15194. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15195. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15196. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15197. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15198. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15199. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15200. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15201. */
  15202. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15203. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15204. /**
  15205. * Whether the lighting model should use SSS or not.
  15206. *
  15207. * @type {Boolean}
  15208. * @default false
  15209. */
  15210. this.useSSS = sss;
  15211. }
  15212. /**
  15213. * Extends the default implementation with a SSS term.
  15214. *
  15215. * 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/}
  15216. *
  15217. * @param {Object} input - The input data.
  15218. * @param {StackNode} stack - The current stack.
  15219. * @param {NodeBuilder} builder - The current node builder.
  15220. */
  15221. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15222. if ( this.useSSS === true ) {
  15223. const material = builder.material;
  15224. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15225. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15226. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15227. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15228. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15229. }
  15230. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15231. }
  15232. }
  15233. /**
  15234. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15235. * that implements a Subsurface scattering (SSS) term.
  15236. *
  15237. * @augments MeshPhysicalNodeMaterial
  15238. */
  15239. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15240. static get type() {
  15241. return 'MeshSSSNodeMaterial';
  15242. }
  15243. /**
  15244. * Constructs a new mesh SSS node material.
  15245. *
  15246. * @param {Object?} parameters - The configuration parameter.
  15247. */
  15248. constructor( parameters ) {
  15249. super( parameters );
  15250. /**
  15251. * Represents the thickness color.
  15252. *
  15253. * @type {Node<vec3>?}
  15254. * @default null
  15255. */
  15256. this.thicknessColorNode = null;
  15257. /**
  15258. * Represents the distortion factor.
  15259. *
  15260. * @type {Node<float>?}
  15261. */
  15262. this.thicknessDistortionNode = float( 0.1 );
  15263. /**
  15264. * Represents the thickness ambient factor.
  15265. *
  15266. * @type {Node<float>?}
  15267. */
  15268. this.thicknessAmbientNode = float( 0.0 );
  15269. /**
  15270. * Represents the thickness attenuation.
  15271. *
  15272. * @type {Node<float>?}
  15273. */
  15274. this.thicknessAttenuationNode = float( .1 );
  15275. /**
  15276. * Represents the thickness power.
  15277. *
  15278. * @type {Node<float>?}
  15279. */
  15280. this.thicknessPowerNode = float( 2.0 );
  15281. /**
  15282. * Represents the thickness scale.
  15283. *
  15284. * @type {Node<float>?}
  15285. */
  15286. this.thicknessScaleNode = float( 10.0 );
  15287. }
  15288. /**
  15289. * Whether the lighting model should use SSS or not.
  15290. *
  15291. * @type {Boolean}
  15292. * @default true
  15293. */
  15294. get useSSS() {
  15295. return this.thicknessColorNode !== null;
  15296. }
  15297. /**
  15298. * Setups the lighting model.
  15299. *
  15300. * @return {SSSLightingModel} The lighting model.
  15301. */
  15302. setupLightingModel( /*builder*/ ) {
  15303. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15304. }
  15305. copy( source ) {
  15306. this.thicknessColorNode = source.thicknessColorNode;
  15307. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15308. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15309. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15310. this.thicknessPowerNode = source.thicknessPowerNode;
  15311. this.thicknessScaleNode = source.thicknessScaleNode;
  15312. return super.copy( source );
  15313. }
  15314. }
  15315. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15316. // dotNL will be from -1.0 to 1.0
  15317. const dotNL = normal.dot( lightDirection );
  15318. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15319. if ( builder.material.gradientMap ) {
  15320. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15321. return vec3( gradientMap.r );
  15322. } else {
  15323. const fw = coord.fwidth().mul( 0.5 );
  15324. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15325. }
  15326. } );
  15327. /**
  15328. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15329. *
  15330. * @augments LightingModel
  15331. */
  15332. class ToonLightingModel extends LightingModel {
  15333. /**
  15334. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15335. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15336. *
  15337. * @param {Object} input - The input data.
  15338. * @param {StackNode} stack - The current stack.
  15339. * @param {NodeBuilder} builder - The current node builder.
  15340. */
  15341. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15342. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15343. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15344. }
  15345. /**
  15346. * Implements the indirect lighting.
  15347. *
  15348. * @param {ContextNode} input - The current node context.
  15349. * @param {StackNode} stack - The current stack.
  15350. * @param {NodeBuilder} builder - The current node builder.
  15351. */
  15352. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15353. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15354. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15355. }
  15356. }
  15357. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15358. /**
  15359. * Node material version of `MeshToonMaterial`.
  15360. *
  15361. * @augments NodeMaterial
  15362. */
  15363. class MeshToonNodeMaterial extends NodeMaterial {
  15364. static get type() {
  15365. return 'MeshToonNodeMaterial';
  15366. }
  15367. /**
  15368. * Constructs a new mesh toon node material.
  15369. *
  15370. * @param {Object?} parameters - The configuration parameter.
  15371. */
  15372. constructor( parameters ) {
  15373. super();
  15374. /**
  15375. * This flag can be used for type testing.
  15376. *
  15377. * @type {Boolean}
  15378. * @readonly
  15379. * @default true
  15380. */
  15381. this.isMeshToonNodeMaterial = true;
  15382. /**
  15383. * Set to `true` because toon materials react on lights.
  15384. *
  15385. * @type {Boolean}
  15386. * @default true
  15387. */
  15388. this.lights = true;
  15389. this.setDefaultValues( _defaultValues$4 );
  15390. this.setValues( parameters );
  15391. }
  15392. /**
  15393. * Setups the lighting model.
  15394. *
  15395. * @return {ToonLightingModel} The lighting model.
  15396. */
  15397. setupLightingModel( /*builder*/ ) {
  15398. return new ToonLightingModel();
  15399. }
  15400. }
  15401. /** @module MatcapUVNode **/
  15402. /**
  15403. * Can be used to compute texture coordinates for projecting a
  15404. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15405. *
  15406. * @augments TempNode
  15407. */
  15408. class MatcapUVNode extends TempNode {
  15409. static get type() {
  15410. return 'MatcapUVNode';
  15411. }
  15412. /**
  15413. * Constructs a new matcap uv node.
  15414. */
  15415. constructor() {
  15416. super( 'vec2' );
  15417. }
  15418. setup() {
  15419. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15420. const y = positionViewDirection.cross( x );
  15421. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15422. }
  15423. }
  15424. /**
  15425. * TSL function for creating a matcap uv node.
  15426. *
  15427. * @function
  15428. * @returns {MatcapUVNode}
  15429. */
  15430. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15431. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15432. /**
  15433. * Node material version of `MeshMatcapMaterial`.
  15434. *
  15435. * @augments NodeMaterial
  15436. */
  15437. class MeshMatcapNodeMaterial extends NodeMaterial {
  15438. static get type() {
  15439. return 'MeshMatcapNodeMaterial';
  15440. }
  15441. /**
  15442. * Constructs a new mesh normal node material.
  15443. *
  15444. * @param {Object?} parameters - The configuration parameter.
  15445. */
  15446. constructor( parameters ) {
  15447. super();
  15448. /**
  15449. * This flag can be used for type testing.
  15450. *
  15451. * @type {Boolean}
  15452. * @readonly
  15453. * @default true
  15454. */
  15455. this.isMeshMatcapNodeMaterial = true;
  15456. this.setDefaultValues( _defaultValues$3 );
  15457. this.setValues( parameters );
  15458. }
  15459. /**
  15460. * Setups the matcap specific node variables.
  15461. *
  15462. * @param {NodeBuilder} builder - The current node builder.
  15463. */
  15464. setupVariants( builder ) {
  15465. const uv = matcapUV;
  15466. let matcapColor;
  15467. if ( builder.material.matcap ) {
  15468. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15469. } else {
  15470. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15471. }
  15472. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15473. }
  15474. }
  15475. /** @module RotateNode **/
  15476. /**
  15477. * Applies a rotation to the given position node.
  15478. *
  15479. * @augments TempNode
  15480. */
  15481. class RotateNode extends TempNode {
  15482. static get type() {
  15483. return 'RotateNode';
  15484. }
  15485. /**
  15486. * Constructs a new rotate node.
  15487. *
  15488. * @param {Node} positionNode - The position node.
  15489. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15490. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15491. */
  15492. constructor( positionNode, rotationNode ) {
  15493. super();
  15494. /**
  15495. * The position node.
  15496. *
  15497. * @type {Node}
  15498. */
  15499. this.positionNode = positionNode;
  15500. /**
  15501. * Represents the rotation that is applied to the position node.
  15502. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15503. *
  15504. * @type {Node}
  15505. */
  15506. this.rotationNode = rotationNode;
  15507. }
  15508. /**
  15509. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15510. *
  15511. * @param {NodeBuilder} builder - The current node builder.
  15512. * @return {String} The node's type.
  15513. */
  15514. getNodeType( builder ) {
  15515. return this.positionNode.getNodeType( builder );
  15516. }
  15517. setup( builder ) {
  15518. const { rotationNode, positionNode } = this;
  15519. const nodeType = this.getNodeType( builder );
  15520. if ( nodeType === 'vec2' ) {
  15521. const cosAngle = rotationNode.cos();
  15522. const sinAngle = rotationNode.sin();
  15523. const rotationMatrix = mat2(
  15524. cosAngle, sinAngle,
  15525. sinAngle.negate(), cosAngle
  15526. );
  15527. return rotationMatrix.mul( positionNode );
  15528. } else {
  15529. const rotation = rotationNode;
  15530. 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 ) );
  15531. 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 ) );
  15532. 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 ) );
  15533. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15534. }
  15535. }
  15536. }
  15537. /**
  15538. * TSL function for creating a rotate node.
  15539. *
  15540. * @function
  15541. * @param {Node} positionNode - The position node.
  15542. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15543. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15544. * @returns {RotateNode}
  15545. */
  15546. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15547. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15548. /**
  15549. * Node material version of `SpriteMaterial`.
  15550. *
  15551. * @augments NodeMaterial
  15552. */
  15553. class SpriteNodeMaterial extends NodeMaterial {
  15554. static get type() {
  15555. return 'SpriteNodeMaterial';
  15556. }
  15557. /**
  15558. * Constructs a new sprite node material.
  15559. *
  15560. * @param {Object?} parameters - The configuration parameter.
  15561. */
  15562. constructor( parameters ) {
  15563. super();
  15564. /**
  15565. * This flag can be used for type testing.
  15566. *
  15567. * @type {Boolean}
  15568. * @readonly
  15569. * @default true
  15570. */
  15571. this.isSpriteNodeMaterial = true;
  15572. this._useSizeAttenuation = true;
  15573. /**
  15574. * This property makes it possible to define the position of the sprite with a
  15575. * node. That can be useful when the material is used with instanced rendering
  15576. * and node data are defined with an instanced attribute node:
  15577. * ```js
  15578. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15579. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15580. * ```
  15581. * Another possibility is to compute the instanced data with a compute shader:
  15582. * ```js
  15583. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15584. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15585. * ```
  15586. *
  15587. * @type {Node<vec2>?}
  15588. * @default null
  15589. */
  15590. this.positionNode = null;
  15591. /**
  15592. * The rotation of sprite materials is by default inferred from the `rotation`,
  15593. * property. This node property allows to overwrite the default and define
  15594. * the rotation with a node instead.
  15595. *
  15596. * If you don't want to overwrite the rotation but modify the existing
  15597. * value instead, use {@link module:MaterialNode.materialRotation}.
  15598. *
  15599. * @type {Node<float>?}
  15600. * @default null
  15601. */
  15602. this.rotationNode = null;
  15603. /**
  15604. * This node property provides an additional way to scale sprites next to
  15605. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15606. * is multiplied with the scale value of this node in the vertex shader.
  15607. *
  15608. * @type {Node<vec2>?}
  15609. * @default null
  15610. */
  15611. this.scaleNode = null;
  15612. this.setDefaultValues( _defaultValues$2 );
  15613. this.setValues( parameters );
  15614. }
  15615. /**
  15616. * Setups the position node in view space. This method implements
  15617. * the sprite specific vertex shader.
  15618. *
  15619. * @param {NodeBuilder} builder - The current node builder.
  15620. * @return {Node<vec3>} The position in view space.
  15621. */
  15622. setupPositionView( builder ) {
  15623. const { object, camera } = builder;
  15624. const sizeAttenuation = this.sizeAttenuation;
  15625. const { positionNode, rotationNode, scaleNode } = this;
  15626. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15627. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15628. if ( scaleNode !== null ) {
  15629. scale = scale.mul( float( scaleNode ) );
  15630. }
  15631. if ( sizeAttenuation === false ) {
  15632. if ( camera.isPerspectiveCamera ) {
  15633. scale = scale.mul( mvPosition.z.negate() );
  15634. } else {
  15635. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15636. scale = scale.mul( orthoScale.mul( 2 ) );
  15637. }
  15638. }
  15639. let alignedPosition = positionGeometry.xy;
  15640. if ( object.center && object.center.isVector2 === true ) {
  15641. const center = reference$1( 'center', 'vec2', object );
  15642. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15643. }
  15644. alignedPosition = alignedPosition.mul( scale );
  15645. const rotation = float( rotationNode || materialRotation );
  15646. const rotatedPosition = rotate( alignedPosition, rotation );
  15647. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15648. }
  15649. copy( source ) {
  15650. this.positionNode = source.positionNode;
  15651. this.rotationNode = source.rotationNode;
  15652. this.scaleNode = source.scaleNode;
  15653. return super.copy( source );
  15654. }
  15655. /**
  15656. * Whether to use size attenuation or not.
  15657. *
  15658. * @type {Boolean}
  15659. * @default true
  15660. */
  15661. get sizeAttenuation() {
  15662. return this._useSizeAttenuation;
  15663. }
  15664. set sizeAttenuation( value ) {
  15665. if ( this._useSizeAttenuation !== value ) {
  15666. this._useSizeAttenuation = value;
  15667. this.needsUpdate = true;
  15668. }
  15669. }
  15670. }
  15671. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  15672. /**
  15673. * Node material version of `PointsMaterial`.
  15674. *
  15675. * @augments NodeMaterial
  15676. */
  15677. class PointsNodeMaterial extends SpriteNodeMaterial {
  15678. static get type() {
  15679. return 'PointsNodeMaterial';
  15680. }
  15681. /**
  15682. * Constructs a new points node material.
  15683. *
  15684. * @param {Object?} parameters - The configuration parameter.
  15685. */
  15686. constructor( parameters ) {
  15687. super();
  15688. /**
  15689. * This node property provides an additional way to set the point size.
  15690. *
  15691. * @type {Node<vec2>?}
  15692. * @default null
  15693. */
  15694. this.sizeNode = null;
  15695. /**
  15696. * This flag can be used for type testing.
  15697. *
  15698. * @type {Boolean}
  15699. * @readonly
  15700. * @default true
  15701. */
  15702. this.isPointsNodeMaterial = true;
  15703. this.setDefaultValues( _defaultValues$1 );
  15704. this.setValues( parameters );
  15705. }
  15706. setupPositionView() {
  15707. const { positionNode } = this;
  15708. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  15709. }
  15710. setupVertex( builder ) {
  15711. const mvp = super.setupVertex( builder );
  15712. // skip further processing if the material is not a node material
  15713. if ( builder.material.isNodeMaterial !== true ) {
  15714. return mvp;
  15715. }
  15716. // ndc space
  15717. const { rotationNode, scaleNode, sizeNode } = this;
  15718. const alignedPosition = positionGeometry.xy.toVar();
  15719. const aspect = viewport.z.div( viewport.w );
  15720. // rotation
  15721. if ( rotationNode && rotationNode.isNode ) {
  15722. const rotation = float( rotationNode );
  15723. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  15724. }
  15725. // point size
  15726. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  15727. if ( this.sizeAttenuation === true ) {
  15728. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  15729. }
  15730. // scale
  15731. if ( scaleNode && scaleNode.isNode ) {
  15732. pointSize = pointSize.mul( vec2( scaleNode ) );
  15733. }
  15734. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  15735. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  15736. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  15737. // back to clip space
  15738. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  15739. //clipPos.xy += offset;
  15740. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  15741. return mvp;
  15742. }
  15743. /**
  15744. * Whether alpha to coverage should be used or not.
  15745. *
  15746. * @type {Boolean}
  15747. * @default true
  15748. */
  15749. get alphaToCoverage() {
  15750. return this._useAlphaToCoverage;
  15751. }
  15752. set alphaToCoverage( value ) {
  15753. if ( this._useAlphaToCoverage !== value ) {
  15754. this._useAlphaToCoverage = value;
  15755. this.needsUpdate = true;
  15756. }
  15757. }
  15758. }
  15759. /**
  15760. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15761. *
  15762. * @augments LightingModel
  15763. */
  15764. class ShadowMaskModel extends LightingModel {
  15765. /**
  15766. * Constructs a new shadow mask model.
  15767. */
  15768. constructor() {
  15769. super();
  15770. /**
  15771. * The shadow mask node.
  15772. *
  15773. * @type {Node}
  15774. */
  15775. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15776. }
  15777. /**
  15778. * Only used to save the shadow mask.
  15779. *
  15780. * @param {Object} input - The input data.
  15781. */
  15782. direct( { shadowMask } ) {
  15783. this.shadowNode.mulAssign( shadowMask );
  15784. }
  15785. /**
  15786. * Uses the shadow mask to produce the final color.
  15787. *
  15788. * @param {ContextNode} context - The current node context.
  15789. */
  15790. finish( context ) {
  15791. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15792. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15793. }
  15794. }
  15795. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15796. /**
  15797. * Node material version of `ShadowMaterial`.
  15798. *
  15799. * @augments NodeMaterial
  15800. */
  15801. class ShadowNodeMaterial extends NodeMaterial {
  15802. static get type() {
  15803. return 'ShadowNodeMaterial';
  15804. }
  15805. /**
  15806. * Constructs a new shadow node material.
  15807. *
  15808. * @param {Object?} parameters - The configuration parameter.
  15809. */
  15810. constructor( parameters ) {
  15811. super();
  15812. /**
  15813. * This flag can be used for type testing.
  15814. *
  15815. * @type {Boolean}
  15816. * @readonly
  15817. * @default true
  15818. */
  15819. this.isShadowNodeMaterial = true;
  15820. /**
  15821. * Set to `true` because so it's possible to implement
  15822. * the shadow mask effect.
  15823. *
  15824. * @type {Boolean}
  15825. * @default true
  15826. */
  15827. this.lights = true;
  15828. this.setDefaultValues( _defaultValues );
  15829. this.setValues( parameters );
  15830. }
  15831. /**
  15832. * Setups the lighting model.
  15833. *
  15834. * @return {ShadowMaskModel} The lighting model.
  15835. */
  15836. setupLightingModel( /*builder*/ ) {
  15837. return new ShadowMaskModel();
  15838. }
  15839. }
  15840. /** @module Texture3DNode **/
  15841. const normal = Fn( ( { texture, uv } ) => {
  15842. const epsilon = 0.0001;
  15843. const ret = vec3().toVar();
  15844. If( uv.x.lessThan( epsilon ), () => {
  15845. ret.assign( vec3( 1, 0, 0 ) );
  15846. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15847. ret.assign( vec3( 0, 1, 0 ) );
  15848. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15849. ret.assign( vec3( 0, 0, 1 ) );
  15850. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15851. ret.assign( vec3( -1, 0, 0 ) );
  15852. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15853. ret.assign( vec3( 0, -1, 0 ) );
  15854. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15855. ret.assign( vec3( 0, 0, -1 ) );
  15856. } ).Else( () => {
  15857. const step = 0.01;
  15858. 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 );
  15859. 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 );
  15860. 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 );
  15861. ret.assign( vec3( x, y, z ) );
  15862. } );
  15863. return ret.normalize();
  15864. } );
  15865. /**
  15866. * This type of uniform node represents a 3D texture.
  15867. *
  15868. * @augments module:TextureNode~TextureNode
  15869. */
  15870. class Texture3DNode extends TextureNode {
  15871. static get type() {
  15872. return 'Texture3DNode';
  15873. }
  15874. /**
  15875. * Constructs a new 3D texture node.
  15876. *
  15877. * @param {Data3DTexture} value - The 3D texture.
  15878. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15879. * @param {Node<int>?} [levelNode=null] - The level node.
  15880. */
  15881. constructor( value, uvNode = null, levelNode = null ) {
  15882. super( value, uvNode, levelNode );
  15883. /**
  15884. * This flag can be used for type testing.
  15885. *
  15886. * @type {Boolean}
  15887. * @readonly
  15888. * @default true
  15889. */
  15890. this.isTexture3DNode = true;
  15891. }
  15892. /**
  15893. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15894. *
  15895. * @param {NodeBuilder} builder - The current node builder.
  15896. * @return {String} The input type.
  15897. */
  15898. getInputType( /*builder*/ ) {
  15899. return 'texture3D';
  15900. }
  15901. /**
  15902. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15903. * uv node.
  15904. *
  15905. * @return {Node<vec3>} The default uv node.
  15906. */
  15907. getDefaultUV() {
  15908. return vec3( 0.5, 0.5, 0.5 );
  15909. }
  15910. /**
  15911. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15912. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15913. *
  15914. * @param {Boolean} value - The update toggle.
  15915. */
  15916. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15917. /**
  15918. * Overwrites the default implementation to return the unmodified uv node.
  15919. *
  15920. * @param {NodeBuilder} builder - The current node builder.
  15921. * @param {Node} uvNode - The uv node to setup.
  15922. * @return {Node} The unmodified uv node.
  15923. */
  15924. setupUV( builder, uvNode ) {
  15925. const texture = this.value;
  15926. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15927. if ( this.sampler ) {
  15928. uvNode = uvNode.flipY();
  15929. } else {
  15930. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15931. }
  15932. }
  15933. return uvNode;
  15934. }
  15935. /**
  15936. * Generates the uv code snippet.
  15937. *
  15938. * @param {NodeBuilder} builder - The current node builder.
  15939. * @param {Node} uvNode - The uv node to generate code for.
  15940. * @return {String} The generated code snippet.
  15941. */
  15942. generateUV( builder, uvNode ) {
  15943. return uvNode.build( builder, 'vec3' );
  15944. }
  15945. /**
  15946. * TODO.
  15947. *
  15948. * @param {Node<vec3>} uvNode - The uv node .
  15949. * @return {Node<vec3>} TODO.
  15950. */
  15951. normal( uvNode ) {
  15952. return normal( { texture: this, uv: uvNode } );
  15953. }
  15954. }
  15955. /**
  15956. * TSL function for creating a 3D texture node.
  15957. *
  15958. * @function
  15959. * @param {Data3DTexture} value - The 3D texture.
  15960. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15961. * @param {Node<int>?} [levelNode=null] - The level node.
  15962. * @returns {Texture3DNode}
  15963. */
  15964. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15965. /** @module VolumeNodeMaterial **/
  15966. /**
  15967. * Node material intended for volume rendering. The volumetric data are
  15968. * defined with an instance of {@link Data3DTexture}.
  15969. *
  15970. * @augments NodeMaterial
  15971. */
  15972. class VolumeNodeMaterial extends NodeMaterial {
  15973. static get type() {
  15974. return 'VolumeNodeMaterial';
  15975. }
  15976. /**
  15977. * Constructs a new volume node material.
  15978. *
  15979. * @param {Object?} parameters - The configuration parameter.
  15980. */
  15981. constructor( parameters ) {
  15982. super();
  15983. /**
  15984. * This flag can be used for type testing.
  15985. *
  15986. * @type {Boolean}
  15987. * @readonly
  15988. * @default true
  15989. */
  15990. this.isVolumeNodeMaterial = true;
  15991. /**
  15992. * The base color of the volume.
  15993. *
  15994. * @type {Color}
  15995. * @default 100
  15996. */
  15997. this.base = new Color( 0xffffff );
  15998. /**
  15999. * A 3D data texture holding the volumetric data.
  16000. *
  16001. * @type {Data3DTexture?}
  16002. * @default null
  16003. */
  16004. this.map = null;
  16005. /**
  16006. * This number of samples for each ray that hits the mesh's surface
  16007. * and travels through the volume.
  16008. *
  16009. * @type {Number}
  16010. * @default 100
  16011. */
  16012. this.steps = 100;
  16013. /**
  16014. * Callback for {@link VolumeNodeMaterial#testNode}.
  16015. *
  16016. * @callback testNodeCallback
  16017. * @param {Data3DTexture<float>} map - The 3D texture.
  16018. * @param {Node<float>} mapValue - The sampled value inside the volume.
  16019. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  16020. * @param {Node<vec4>} finalColor - The final color.
  16021. */
  16022. /**
  16023. * The volume rendering of this material works by shooting rays
  16024. * from the camera position through each fragment of the mesh's
  16025. * surface and sample the inner volume in a raymarching fashion
  16026. * multiple times.
  16027. *
  16028. * This node can be used to assign a callback function of type `Fn`
  16029. * that will be executed per sample. The callback receives the
  16030. * texture, the sampled texture value as well as position on the surface
  16031. * where the rays enters the volume. The last parameter is a color
  16032. * that allows the callback to determine the final color.
  16033. *
  16034. * @type {testNodeCallback?}
  16035. * @default null
  16036. */
  16037. this.testNode = null;
  16038. this.setValues( parameters );
  16039. }
  16040. /**
  16041. * Setups the vertex and fragment stage of this node material.
  16042. *
  16043. * @param {NodeBuilder} builder - The current node builder.
  16044. */
  16045. setup( builder ) {
  16046. const map = texture3D( this.map, null, 0 );
  16047. const hitBox = Fn( ( { orig, dir } ) => {
  16048. const box_min = vec3( -0.5 );
  16049. const box_max = vec3( 0.5 );
  16050. const inv_dir = dir.reciprocal();
  16051. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  16052. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  16053. const tmin = min$1( tmin_tmp, tmax_tmp );
  16054. const tmax = max$1( tmin_tmp, tmax_tmp );
  16055. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  16056. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  16057. return vec2( t0, t1 );
  16058. } );
  16059. this.fragmentNode = Fn( () => {
  16060. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  16061. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  16062. const rayDir = vDirection.normalize();
  16063. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  16064. bounds.x.greaterThan( bounds.y ).discard();
  16065. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  16066. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  16067. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  16068. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  16069. delta.divAssign( materialReference( 'steps', 'float' ) );
  16070. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  16071. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  16072. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  16073. if ( this.testNode !== null ) {
  16074. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  16075. } else {
  16076. // default to show surface of mesh
  16077. ac.a.assign( 1 );
  16078. Break();
  16079. }
  16080. p.addAssign( rayDir.mul( delta ) );
  16081. } );
  16082. ac.a.equal( 0 ).discard();
  16083. return vec4( ac );
  16084. } )();
  16085. super.setup( builder );
  16086. }
  16087. }
  16088. /**
  16089. * This module manages the internal animation loop of the renderer.
  16090. *
  16091. * @private
  16092. */
  16093. class Animation {
  16094. /**
  16095. * Constructs a new animation loop management component.
  16096. *
  16097. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16098. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16099. */
  16100. constructor( nodes, info ) {
  16101. /**
  16102. * Renderer component for managing nodes related logic.
  16103. *
  16104. * @type {Nodes}
  16105. */
  16106. this.nodes = nodes;
  16107. /**
  16108. * Renderer component for managing metrics and monitoring data.
  16109. *
  16110. * @type {Info}
  16111. */
  16112. this.info = info;
  16113. /**
  16114. * A reference to the context from `requestAnimationFrame()` can
  16115. * be called (usually `window`).
  16116. *
  16117. * @type {Window|XRSession}
  16118. */
  16119. this._context = self;
  16120. /**
  16121. * The user-defined animation loop.
  16122. *
  16123. * @type {Function?}
  16124. * @default null
  16125. */
  16126. this._animationLoop = null;
  16127. /**
  16128. * The requestId which is returned from the `requestAnimationFrame()` call.
  16129. * Can be used to cancel the stop the animation loop.
  16130. *
  16131. * @type {Number?}
  16132. * @default null
  16133. */
  16134. this._requestId = null;
  16135. }
  16136. /**
  16137. * Starts the internal animation loop.
  16138. */
  16139. start() {
  16140. const update = ( time, frame ) => {
  16141. this._requestId = this._context.requestAnimationFrame( update );
  16142. if ( this.info.autoReset === true ) this.info.reset();
  16143. this.nodes.nodeFrame.update();
  16144. this.info.frame = this.nodes.nodeFrame.frameId;
  16145. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16146. };
  16147. update();
  16148. }
  16149. /**
  16150. * Stops the internal animation loop.
  16151. */
  16152. stop() {
  16153. this._context.cancelAnimationFrame( this._requestId );
  16154. this._requestId = null;
  16155. }
  16156. /**
  16157. * Returns the user-level animation loop.
  16158. *
  16159. * @return {Function} The animation loop.
  16160. */
  16161. getAnimationLoop() {
  16162. return this._animationLoop;
  16163. }
  16164. /**
  16165. * Defines the user-level animation loop.
  16166. *
  16167. * @param {Function} callback - The animation loop.
  16168. */
  16169. setAnimationLoop( callback ) {
  16170. this._animationLoop = callback;
  16171. }
  16172. /**
  16173. * Returns the animation context.
  16174. *
  16175. * @return {Window|XRSession} The animation context.
  16176. */
  16177. getContext() {
  16178. return this._context;
  16179. }
  16180. /**
  16181. * Defines the context in which `requestAnimationFrame()` is executed.
  16182. *
  16183. * @param {Window|XRSession} context - The context to set.
  16184. */
  16185. setContext( context ) {
  16186. this._context = context;
  16187. }
  16188. /**
  16189. * Frees all internal resources and stops the animation loop.
  16190. */
  16191. dispose() {
  16192. this.stop();
  16193. }
  16194. }
  16195. /**
  16196. * Data structure for the renderer. It allows defining values
  16197. * with chained, hierarchical keys. Keys are meant to be
  16198. * objects since the module internally works with Weak Maps
  16199. * for performance reasons.
  16200. *
  16201. * @private
  16202. */
  16203. class ChainMap {
  16204. /**
  16205. * Constructs a new Chain Map.
  16206. */
  16207. constructor() {
  16208. /**
  16209. * The root Weak Map.
  16210. *
  16211. * @type {WeakMap}
  16212. */
  16213. this.weakMap = new WeakMap();
  16214. }
  16215. /**
  16216. * Returns the value for the given array of keys.
  16217. *
  16218. * @param {Array<Object>} keys - List of keys.
  16219. * @return {Any} The value. Returns `undefined` if no value was found.
  16220. */
  16221. get( keys ) {
  16222. let map = this.weakMap;
  16223. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16224. map = map.get( keys[ i ] );
  16225. if ( map === undefined ) return undefined;
  16226. }
  16227. return map.get( keys[ keys.length - 1 ] );
  16228. }
  16229. /**
  16230. * Sets the value for the given keys.
  16231. *
  16232. * @param {Array<Object>} keys - List of keys.
  16233. * @param {Any} value - The value to set.
  16234. * @return {ChainMap} A reference to this Chain Map.
  16235. */
  16236. set( keys, value ) {
  16237. let map = this.weakMap;
  16238. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16239. const key = keys[ i ];
  16240. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16241. map = map.get( key );
  16242. }
  16243. map.set( keys[ keys.length - 1 ], value );
  16244. return this;
  16245. }
  16246. /**
  16247. * Deletes a value for the given keys.
  16248. *
  16249. * @param {Array<Object>} keys - The keys.
  16250. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16251. */
  16252. delete( keys ) {
  16253. let map = this.weakMap;
  16254. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16255. map = map.get( keys[ i ] );
  16256. if ( map === undefined ) return false;
  16257. }
  16258. return map.delete( keys[ keys.length - 1 ] );
  16259. }
  16260. }
  16261. let _id$9 = 0;
  16262. function getKeys( obj ) {
  16263. const keys = Object.keys( obj );
  16264. let proto = Object.getPrototypeOf( obj );
  16265. while ( proto ) {
  16266. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16267. for ( const key in descriptors ) {
  16268. if ( descriptors[ key ] !== undefined ) {
  16269. const descriptor = descriptors[ key ];
  16270. if ( descriptor && typeof descriptor.get === 'function' ) {
  16271. keys.push( key );
  16272. }
  16273. }
  16274. }
  16275. proto = Object.getPrototypeOf( proto );
  16276. }
  16277. return keys;
  16278. }
  16279. /**
  16280. * A render object is the renderer's representation of single entity that gets drawn
  16281. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16282. * scene since render objects also depend from the used material, the current render context
  16283. * and the current scene's lighting.
  16284. *
  16285. * In general, the basic process of the renderer is:
  16286. *
  16287. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16288. * - Process the render lists by calling one or more render commands for each render item.
  16289. * - For each render command, request a render object and perform the draw.
  16290. *
  16291. * The module provides an interface to get data required for the draw command like the actual
  16292. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16293. * creating render objects should only be done when necessary.
  16294. *
  16295. * @private
  16296. */
  16297. class RenderObject {
  16298. /**
  16299. * Constructs a new render object.
  16300. *
  16301. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16302. * @param {Geometries} geometries - Renderer component for managing geometries.
  16303. * @param {Renderer} renderer - The renderer.
  16304. * @param {Object3D} object - The 3D object.
  16305. * @param {Material} material - The 3D object's material.
  16306. * @param {Scene} scene - The scene the 3D object belongs to.
  16307. * @param {Camera} camera - The camera the object should be rendered with.
  16308. * @param {LightsNode} lightsNode - The lights node.
  16309. * @param {RenderContext} renderContext - The render context.
  16310. * @param {ClippingContext} clippingContext - The clipping context.
  16311. */
  16312. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16313. this.id = _id$9 ++;
  16314. /**
  16315. * Renderer component for managing nodes related logic.
  16316. *
  16317. * @type {Nodes}
  16318. * @private
  16319. */
  16320. this._nodes = nodes;
  16321. /**
  16322. * Renderer component for managing geometries.
  16323. *
  16324. * @type {Geometries}
  16325. * @private
  16326. */
  16327. this._geometries = geometries;
  16328. /**
  16329. * The renderer.
  16330. *
  16331. * @type {Renderer}
  16332. */
  16333. this.renderer = renderer;
  16334. /**
  16335. * The 3D object.
  16336. *
  16337. * @type {Object3D}
  16338. */
  16339. this.object = object;
  16340. /**
  16341. * The 3D object's material.
  16342. *
  16343. * @type {Material}
  16344. */
  16345. this.material = material;
  16346. /**
  16347. * The scene the 3D object belongs to.
  16348. *
  16349. * @type {Scene}
  16350. */
  16351. this.scene = scene;
  16352. /**
  16353. * The camera the 3D object should be rendered with.
  16354. *
  16355. * @type {Camera}
  16356. */
  16357. this.camera = camera;
  16358. /**
  16359. * The lights node.
  16360. *
  16361. * @type {LightsNode}
  16362. */
  16363. this.lightsNode = lightsNode;
  16364. /**
  16365. * The render context.
  16366. *
  16367. * @type {RenderContext}
  16368. */
  16369. this.context = renderContext;
  16370. /**
  16371. * The 3D object's geometry.
  16372. *
  16373. * @type {BufferGeometry}
  16374. */
  16375. this.geometry = object.geometry;
  16376. /**
  16377. * The render object's version.
  16378. *
  16379. * @type {Number}
  16380. */
  16381. this.version = material.version;
  16382. /**
  16383. * The draw range of the geometry.
  16384. *
  16385. * @type {Object?}
  16386. * @default null
  16387. */
  16388. this.drawRange = null;
  16389. /**
  16390. * An array holding the buffer attributes
  16391. * of the render object. This entails attribute
  16392. * definitions on geometry and node level.
  16393. *
  16394. * @type {Array<BufferAttribute>?}
  16395. * @default null
  16396. */
  16397. this.attributes = null;
  16398. /**
  16399. * A reference to a render pipeline the render
  16400. * object is processed with.
  16401. *
  16402. * @type {RenderPipeline}
  16403. * @default null
  16404. */
  16405. this.pipeline = null;
  16406. /**
  16407. * Only relevant for objects using
  16408. * multiple materials. This represents a group entry
  16409. * from the respective `BufferGeometry`.
  16410. *
  16411. * @type {{start: Number, count: Number}?}
  16412. * @default null
  16413. */
  16414. this.group = null;
  16415. /**
  16416. * An array holding the vertex buffers which can
  16417. * be buffer attributes but also interleaved buffers.
  16418. *
  16419. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16420. * @default null
  16421. */
  16422. this.vertexBuffers = null;
  16423. /**
  16424. * The parameters for the draw command.
  16425. *
  16426. * @type {Object?}
  16427. * @default null
  16428. */
  16429. this.drawParams = null;
  16430. /**
  16431. * If this render object is used inside a render bundle,
  16432. * this property points to the respective bundle group.
  16433. *
  16434. * @type {BundleGroup?}
  16435. * @default null
  16436. */
  16437. this.bundle = null;
  16438. /**
  16439. * The clipping context.
  16440. *
  16441. * @type {ClippingContext}
  16442. */
  16443. this.clippingContext = clippingContext;
  16444. /**
  16445. * The clipping context's cache key.
  16446. *
  16447. * @type {String}
  16448. */
  16449. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16450. /**
  16451. * The initial node cache key.
  16452. *
  16453. * @type {Number}
  16454. */
  16455. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16456. /**
  16457. * The initial cache key.
  16458. *
  16459. * @type {Number}
  16460. */
  16461. this.initialCacheKey = this.getCacheKey();
  16462. /**
  16463. * The node builder state.
  16464. *
  16465. * @type {NodeBuilderState?}
  16466. * @private
  16467. * @default null
  16468. */
  16469. this._nodeBuilderState = null;
  16470. /**
  16471. * An array of bindings.
  16472. *
  16473. * @type {Array<BindGroup>?}
  16474. * @private
  16475. * @default null
  16476. */
  16477. this._bindings = null;
  16478. /**
  16479. * Reference to the node material observer.
  16480. *
  16481. * @type {NodeMaterialObserver?}
  16482. * @private
  16483. * @default null
  16484. */
  16485. this._monitor = null;
  16486. /**
  16487. * An event listener which is defined by `RenderObjects`. It performs
  16488. * clean up tasks when `dispose()` on this render object.
  16489. *
  16490. * @method
  16491. */
  16492. this.onDispose = null;
  16493. /**
  16494. * This flag can be used for type testing.
  16495. *
  16496. * @type {Boolean}
  16497. * @readonly
  16498. * @default true
  16499. */
  16500. this.isRenderObject = true;
  16501. /**
  16502. * An event listener which is executed when `dispose()` is called on
  16503. * the render object's material.
  16504. *
  16505. * @method
  16506. */
  16507. this.onMaterialDispose = () => {
  16508. this.dispose();
  16509. };
  16510. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16511. }
  16512. /**
  16513. * Updates the clipping context.
  16514. *
  16515. * @param {ClippingContext} context - The clipping context to set.
  16516. */
  16517. updateClipping( context ) {
  16518. this.clippingContext = context;
  16519. }
  16520. /**
  16521. * Whether the clipping requires an update or not.
  16522. *
  16523. * @type {Boolean}
  16524. * @readonly
  16525. */
  16526. get clippingNeedsUpdate() {
  16527. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16528. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16529. return true;
  16530. }
  16531. /**
  16532. * The number of clipping planes defined in context of hardware clipping.
  16533. *
  16534. * @type {Number}
  16535. * @readonly
  16536. */
  16537. get hardwareClippingPlanes() {
  16538. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16539. }
  16540. /**
  16541. * Returns the node builder state of this render object.
  16542. *
  16543. * @return {NodeBuilderState} The node builder state.
  16544. */
  16545. getNodeBuilderState() {
  16546. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16547. }
  16548. /**
  16549. * Returns the node material observer of this render object.
  16550. *
  16551. * @return {NodeMaterialObserver} The node material observer.
  16552. */
  16553. getMonitor() {
  16554. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  16555. }
  16556. /**
  16557. * Returns an array of bind groups of this render object.
  16558. *
  16559. * @return {Array<BindGroup>} The bindings.
  16560. */
  16561. getBindings() {
  16562. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16563. }
  16564. /**
  16565. * Returns a binding group by group name of this render object.
  16566. *
  16567. * @param {String} name - The name of the binding group.
  16568. * @return {BindGroup?} The bindings.
  16569. */
  16570. getBindingGroup( name ) {
  16571. for ( const bindingGroup of this.getBindings() ) {
  16572. if ( bindingGroup.name === name ) {
  16573. return bindingGroup;
  16574. }
  16575. }
  16576. }
  16577. /**
  16578. * Returns the index of the render object's geometry.
  16579. *
  16580. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16581. */
  16582. getIndex() {
  16583. return this._geometries.getIndex( this );
  16584. }
  16585. /**
  16586. * Returns the indirect buffer attribute.
  16587. *
  16588. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16589. */
  16590. getIndirect() {
  16591. return this._geometries.getIndirect( this );
  16592. }
  16593. /**
  16594. * Returns an array that acts as a key for identifying the render object in a chain map.
  16595. *
  16596. * @return {Array<Object>} An array with object references.
  16597. */
  16598. getChainArray() {
  16599. return [ this.object, this.material, this.context, this.lightsNode ];
  16600. }
  16601. /**
  16602. * This method is used when the geometry of a 3D object has been exchanged and the
  16603. * respective render object now requires an update.
  16604. *
  16605. * @param {BufferGeometry} geometry - The geometry to set.
  16606. */
  16607. setGeometry( geometry ) {
  16608. this.geometry = geometry;
  16609. this.attributes = null;
  16610. }
  16611. /**
  16612. * Returns the buffer attributes of the render object. The returned array holds
  16613. * attribute definitions on geometry and node level.
  16614. *
  16615. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16616. */
  16617. getAttributes() {
  16618. if ( this.attributes !== null ) return this.attributes;
  16619. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16620. const geometry = this.geometry;
  16621. const attributes = [];
  16622. const vertexBuffers = new Set();
  16623. for ( const nodeAttribute of nodeAttributes ) {
  16624. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16625. if ( attribute === undefined ) continue;
  16626. attributes.push( attribute );
  16627. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16628. vertexBuffers.add( bufferAttribute );
  16629. }
  16630. this.attributes = attributes;
  16631. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16632. return attributes;
  16633. }
  16634. /**
  16635. * Returns the vertex buffers of the render object.
  16636. *
  16637. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16638. */
  16639. getVertexBuffers() {
  16640. if ( this.vertexBuffers === null ) this.getAttributes();
  16641. return this.vertexBuffers;
  16642. }
  16643. /**
  16644. * Returns the draw parameters for the render object.
  16645. *
  16646. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16647. */
  16648. getDrawParameters() {
  16649. const { object, material, geometry, group, drawRange } = this;
  16650. const drawParams = this.drawParams || ( this.drawParams = {
  16651. vertexCount: 0,
  16652. firstVertex: 0,
  16653. instanceCount: 0,
  16654. firstInstance: 0
  16655. } );
  16656. const index = this.getIndex();
  16657. const hasIndex = ( index !== null );
  16658. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16659. if ( instanceCount === 0 ) return null;
  16660. drawParams.instanceCount = instanceCount;
  16661. if ( object.isBatchedMesh === true ) return drawParams;
  16662. let rangeFactor = 1;
  16663. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16664. rangeFactor = 2;
  16665. }
  16666. let firstVertex = drawRange.start * rangeFactor;
  16667. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16668. if ( group !== null ) {
  16669. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16670. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16671. }
  16672. const position = geometry.attributes.position;
  16673. let itemCount = Infinity;
  16674. if ( hasIndex ) {
  16675. itemCount = index.count;
  16676. } else if ( position !== undefined && position !== null ) {
  16677. itemCount = position.count;
  16678. }
  16679. firstVertex = Math.max( firstVertex, 0 );
  16680. lastVertex = Math.min( lastVertex, itemCount );
  16681. const count = lastVertex - firstVertex;
  16682. if ( count < 0 || count === Infinity ) return null;
  16683. drawParams.vertexCount = count;
  16684. drawParams.firstVertex = firstVertex;
  16685. return drawParams;
  16686. }
  16687. /**
  16688. * Returns the render object's geometry cache key.
  16689. *
  16690. * The geometry cache key is part of the material cache key.
  16691. *
  16692. * @return {String} The geometry cache key.
  16693. */
  16694. getGeometryCacheKey() {
  16695. const { geometry } = this;
  16696. let cacheKey = '';
  16697. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16698. const attribute = geometry.attributes[ name ];
  16699. cacheKey += name + ',';
  16700. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16701. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16702. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16703. if ( attribute.normalized ) cacheKey += 'n,';
  16704. }
  16705. // structural equality isn't sufficient for morph targets since the
  16706. // data are maintained in textures. only if the targets are all equal
  16707. // the texture and thus the instance of `MorphNode` can be shared.
  16708. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  16709. const targets = geometry.morphAttributes[ name ];
  16710. cacheKey += 'morph-' + name + ',';
  16711. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  16712. const attribute = targets[ i ];
  16713. cacheKey += attribute.id + ',';
  16714. }
  16715. }
  16716. if ( geometry.index ) {
  16717. cacheKey += 'index,';
  16718. }
  16719. return cacheKey;
  16720. }
  16721. /**
  16722. * Returns the render object's material cache key.
  16723. *
  16724. * The material cache key is part of the render object cache key.
  16725. *
  16726. * @return {Number} The material cache key.
  16727. */
  16728. getMaterialCacheKey() {
  16729. const { object, material } = this;
  16730. let cacheKey = material.customProgramCacheKey();
  16731. for ( const property of getKeys( material ) ) {
  16732. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16733. const value = material[ property ];
  16734. let valueKey;
  16735. if ( value !== null ) {
  16736. // some material values require a formatting
  16737. const type = typeof value;
  16738. if ( type === 'number' ) {
  16739. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16740. } else if ( type === 'object' ) {
  16741. valueKey = '{';
  16742. if ( value.isTexture ) {
  16743. valueKey += value.mapping;
  16744. }
  16745. valueKey += '}';
  16746. } else {
  16747. valueKey = String( value );
  16748. }
  16749. } else {
  16750. valueKey = String( value );
  16751. }
  16752. cacheKey += /*property + ':' +*/ valueKey + ',';
  16753. }
  16754. cacheKey += this.clippingContextCacheKey + ',';
  16755. if ( object.geometry ) {
  16756. cacheKey += this.getGeometryCacheKey();
  16757. }
  16758. if ( object.skeleton ) {
  16759. cacheKey += object.skeleton.bones.length + ',';
  16760. }
  16761. if ( object.isBatchedMesh ) {
  16762. cacheKey += object._matricesTexture.uuid + ',';
  16763. if ( object._colorsTexture !== null ) {
  16764. cacheKey += object._colorsTexture.uuid + ',';
  16765. }
  16766. }
  16767. if ( object.count > 1 ) {
  16768. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16769. cacheKey += object.uuid + ',';
  16770. }
  16771. cacheKey += object.receiveShadow + ',';
  16772. return hashString( cacheKey );
  16773. }
  16774. /**
  16775. * Whether the geometry requires an update or not.
  16776. *
  16777. * @type {Boolean}
  16778. * @readonly
  16779. */
  16780. get needsGeometryUpdate() {
  16781. return this.geometry.id !== this.object.geometry.id;
  16782. }
  16783. /**
  16784. * Whether the render object requires an update or not.
  16785. *
  16786. * Note: There are two distinct places where render objects are checked for an update.
  16787. *
  16788. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16789. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16790. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16791. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16792. * a need for a refresh due to material, geometry or object related value changes.
  16793. *
  16794. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16795. * that performs the 'needsUpdate' check.
  16796. *
  16797. * @type {Boolean}
  16798. * @readonly
  16799. */
  16800. get needsUpdate() {
  16801. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16802. }
  16803. /**
  16804. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16805. *
  16806. * @return {Number} The cache key.
  16807. */
  16808. getDynamicCacheKey() {
  16809. let cacheKey = 0;
  16810. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  16811. // the renderer is inside a shadow pass.
  16812. if ( this.material.isShadowPassMaterial !== true ) {
  16813. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16814. }
  16815. if ( this.camera.isArrayCamera ) {
  16816. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  16817. }
  16818. if ( this.object.receiveShadow ) {
  16819. cacheKey = hash$1( cacheKey, 1 );
  16820. }
  16821. return cacheKey;
  16822. }
  16823. /**
  16824. * Returns the render object's cache key.
  16825. *
  16826. * @return {Number} The cache key.
  16827. */
  16828. getCacheKey() {
  16829. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16830. }
  16831. /**
  16832. * Frees internal resources.
  16833. */
  16834. dispose() {
  16835. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16836. this.onDispose();
  16837. }
  16838. }
  16839. const _chainKeys$5 = [];
  16840. /**
  16841. * This module manages the render objects of the renderer.
  16842. *
  16843. * @private
  16844. */
  16845. class RenderObjects {
  16846. /**
  16847. * Constructs a new render object management component.
  16848. *
  16849. * @param {Renderer} renderer - The renderer.
  16850. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16851. * @param {Geometries} geometries - Renderer component for managing geometries.
  16852. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16853. * @param {Bindings} bindings - Renderer component for managing bindings.
  16854. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16855. */
  16856. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16857. /**
  16858. * The renderer.
  16859. *
  16860. * @type {Renderer}
  16861. */
  16862. this.renderer = renderer;
  16863. /**
  16864. * Renderer component for managing nodes related logic.
  16865. *
  16866. * @type {Nodes}
  16867. */
  16868. this.nodes = nodes;
  16869. /**
  16870. * Renderer component for managing geometries.
  16871. *
  16872. * @type {Geometries}
  16873. */
  16874. this.geometries = geometries;
  16875. /**
  16876. * Renderer component for managing pipelines.
  16877. *
  16878. * @type {Pipelines}
  16879. */
  16880. this.pipelines = pipelines;
  16881. /**
  16882. * Renderer component for managing bindings.
  16883. *
  16884. * @type {Bindings}
  16885. */
  16886. this.bindings = bindings;
  16887. /**
  16888. * Renderer component for managing metrics and monitoring data.
  16889. *
  16890. * @type {Info}
  16891. */
  16892. this.info = info;
  16893. /**
  16894. * A dictionary that manages render contexts in chain maps
  16895. * for each pass ID.
  16896. *
  16897. * @type {Object<String,ChainMap>}
  16898. */
  16899. this.chainMaps = {};
  16900. }
  16901. /**
  16902. * Returns a render object for the given object and state data.
  16903. *
  16904. * @param {Object3D} object - The 3D object.
  16905. * @param {Material} material - The 3D object's material.
  16906. * @param {Scene} scene - The scene the 3D object belongs to.
  16907. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16908. * @param {LightsNode} lightsNode - The lights node.
  16909. * @param {RenderContext} renderContext - The render context.
  16910. * @param {ClippingContext} clippingContext - The clipping context.
  16911. * @param {String?} passId - An optional ID for identifying the pass.
  16912. * @return {RenderObject} The render object.
  16913. */
  16914. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16915. const chainMap = this.getChainMap( passId );
  16916. // reuse chainArray
  16917. _chainKeys$5[ 0 ] = object;
  16918. _chainKeys$5[ 1 ] = material;
  16919. _chainKeys$5[ 2 ] = renderContext;
  16920. _chainKeys$5[ 3 ] = lightsNode;
  16921. let renderObject = chainMap.get( _chainKeys$5 );
  16922. if ( renderObject === undefined ) {
  16923. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16924. chainMap.set( _chainKeys$5, renderObject );
  16925. } else {
  16926. renderObject.updateClipping( clippingContext );
  16927. if ( renderObject.needsGeometryUpdate ) {
  16928. renderObject.setGeometry( object.geometry );
  16929. }
  16930. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16931. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16932. renderObject.dispose();
  16933. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16934. } else {
  16935. renderObject.version = material.version;
  16936. }
  16937. }
  16938. }
  16939. _chainKeys$5.length = 0;
  16940. return renderObject;
  16941. }
  16942. /**
  16943. * Returns a chain map for the given pass ID.
  16944. *
  16945. * @param {String} [passId='default'] - The pass ID.
  16946. * @return {ChainMap} The chain map.
  16947. */
  16948. getChainMap( passId = 'default' ) {
  16949. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16950. }
  16951. /**
  16952. * Frees internal resources.
  16953. */
  16954. dispose() {
  16955. this.chainMaps = {};
  16956. }
  16957. /**
  16958. * Factory method for creating render objects with the given list of parameters.
  16959. *
  16960. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16961. * @param {Geometries} geometries - Renderer component for managing geometries.
  16962. * @param {Renderer} renderer - The renderer.
  16963. * @param {Object3D} object - The 3D object.
  16964. * @param {Material} material - The object's material.
  16965. * @param {Scene} scene - The scene the 3D object belongs to.
  16966. * @param {Camera} camera - The camera the object should be rendered with.
  16967. * @param {LightsNode} lightsNode - The lights node.
  16968. * @param {RenderContext} renderContext - The render context.
  16969. * @param {ClippingContext} clippingContext - The clipping context.
  16970. * @param {String?} passId - An optional ID for identifying the pass.
  16971. * @return {RenderObject} The render object.
  16972. */
  16973. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16974. const chainMap = this.getChainMap( passId );
  16975. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16976. renderObject.onDispose = () => {
  16977. this.pipelines.delete( renderObject );
  16978. this.bindings.delete( renderObject );
  16979. this.nodes.delete( renderObject );
  16980. chainMap.delete( renderObject.getChainArray() );
  16981. };
  16982. return renderObject;
  16983. }
  16984. }
  16985. /**
  16986. * Data structure for the renderer. It is intended to manage
  16987. * data of objects in dictionaries.
  16988. *
  16989. * @private
  16990. */
  16991. class DataMap {
  16992. /**
  16993. * Constructs a new data map.
  16994. */
  16995. constructor() {
  16996. /**
  16997. * `DataMap` internally uses a weak map
  16998. * to manage its data.
  16999. *
  17000. * @type {WeakMap}
  17001. */
  17002. this.data = new WeakMap();
  17003. }
  17004. /**
  17005. * Returns the dictionary for the given object.
  17006. *
  17007. * @param {Object} object - The object.
  17008. * @return {Object} The dictionary.
  17009. */
  17010. get( object ) {
  17011. let map = this.data.get( object );
  17012. if ( map === undefined ) {
  17013. map = {};
  17014. this.data.set( object, map );
  17015. }
  17016. return map;
  17017. }
  17018. /**
  17019. * Deletes the dictionary for the given object.
  17020. *
  17021. * @param {Object} object - The object.
  17022. * @return {Object?} The deleted dictionary.
  17023. */
  17024. delete( object ) {
  17025. let map = null;
  17026. if ( this.data.has( object ) ) {
  17027. map = this.data.get( object );
  17028. this.data.delete( object );
  17029. }
  17030. return map;
  17031. }
  17032. /**
  17033. * Returns `true` if the given object has a dictionary defined.
  17034. *
  17035. * @param {Object} object - The object to test.
  17036. * @return {Boolean} Whether a dictionary is defined or not.
  17037. */
  17038. has( object ) {
  17039. return this.data.has( object );
  17040. }
  17041. /**
  17042. * Frees internal resources.
  17043. */
  17044. dispose() {
  17045. this.data = new WeakMap();
  17046. }
  17047. }
  17048. const AttributeType = {
  17049. VERTEX: 1,
  17050. INDEX: 2,
  17051. STORAGE: 3,
  17052. INDIRECT: 4
  17053. };
  17054. // size of a chunk in bytes (STD140 layout)
  17055. const GPU_CHUNK_BYTES = 16;
  17056. // @TODO: Move to src/constants.js
  17057. const BlendColorFactor = 211;
  17058. const OneMinusBlendColorFactor = 212;
  17059. /**
  17060. * This renderer module manages geometry attributes.
  17061. *
  17062. * @private
  17063. * @augments DataMap
  17064. */
  17065. class Attributes extends DataMap {
  17066. /**
  17067. * Constructs a new attribute management component.
  17068. *
  17069. * @param {Backend} backend - The renderer's backend.
  17070. */
  17071. constructor( backend ) {
  17072. super();
  17073. /**
  17074. * The renderer's backend.
  17075. *
  17076. * @type {Backend}
  17077. */
  17078. this.backend = backend;
  17079. }
  17080. /**
  17081. * Deletes the data for the given attribute.
  17082. *
  17083. * @param {BufferAttribute} attribute - The attribute.
  17084. * @return {Object} The deleted attribute data.
  17085. */
  17086. delete( attribute ) {
  17087. const attributeData = super.delete( attribute );
  17088. if ( attributeData !== undefined ) {
  17089. this.backend.destroyAttribute( attribute );
  17090. }
  17091. return attributeData;
  17092. }
  17093. /**
  17094. * Updates the given attribute. This method creates attribute buffers
  17095. * for new attributes and updates data for existing ones.
  17096. *
  17097. * @param {BufferAttribute} attribute - The attribute to update.
  17098. * @param {Number} type - The attribute type.
  17099. */
  17100. update( attribute, type ) {
  17101. const data = this.get( attribute );
  17102. if ( data.version === undefined ) {
  17103. if ( type === AttributeType.VERTEX ) {
  17104. this.backend.createAttribute( attribute );
  17105. } else if ( type === AttributeType.INDEX ) {
  17106. this.backend.createIndexAttribute( attribute );
  17107. } else if ( type === AttributeType.STORAGE ) {
  17108. this.backend.createStorageAttribute( attribute );
  17109. } else if ( type === AttributeType.INDIRECT ) {
  17110. this.backend.createIndirectStorageAttribute( attribute );
  17111. }
  17112. data.version = this._getBufferAttribute( attribute ).version;
  17113. } else {
  17114. const bufferAttribute = this._getBufferAttribute( attribute );
  17115. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  17116. this.backend.updateAttribute( attribute );
  17117. data.version = bufferAttribute.version;
  17118. }
  17119. }
  17120. }
  17121. /**
  17122. * Utility method for handling interleaved buffer attributes correctly.
  17123. * To process them, their `InterleavedBuffer` is returned.
  17124. *
  17125. * @param {BufferAttribute} attribute - The attribute.
  17126. * @return {BufferAttribute|InterleavedBuffer}
  17127. */
  17128. _getBufferAttribute( attribute ) {
  17129. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  17130. return attribute;
  17131. }
  17132. }
  17133. /**
  17134. * Returns `true` if the given array has values that require an Uint32 array type.
  17135. *
  17136. * @private
  17137. * @function
  17138. * @param {Array<Number>} array - The array to test.
  17139. * @return {Boolean} Whether the given array has values that require an Uint32 array type or not.
  17140. */
  17141. function arrayNeedsUint32( array ) {
  17142. // assumes larger values usually on last
  17143. for ( let i = array.length - 1; i >= 0; -- i ) {
  17144. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  17145. }
  17146. return false;
  17147. }
  17148. /**
  17149. * Returns the wireframe version for the given geometry.
  17150. *
  17151. * @private
  17152. * @function
  17153. * @param {BufferGeometry} geometry - The geometry.
  17154. * @return {Number} The version.
  17155. */
  17156. function getWireframeVersion( geometry ) {
  17157. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17158. }
  17159. /**
  17160. * Returns a wireframe index attribute for the given geometry.
  17161. *
  17162. * @private
  17163. * @function
  17164. * @param {BufferGeometry} geometry - The geometry.
  17165. * @return {BufferAttribute} The wireframe index attribute.
  17166. */
  17167. function getWireframeIndex( geometry ) {
  17168. const indices = [];
  17169. const geometryIndex = geometry.index;
  17170. const geometryPosition = geometry.attributes.position;
  17171. if ( geometryIndex !== null ) {
  17172. const array = geometryIndex.array;
  17173. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17174. const a = array[ i + 0 ];
  17175. const b = array[ i + 1 ];
  17176. const c = array[ i + 2 ];
  17177. indices.push( a, b, b, c, c, a );
  17178. }
  17179. } else {
  17180. const array = geometryPosition.array;
  17181. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17182. const a = i + 0;
  17183. const b = i + 1;
  17184. const c = i + 2;
  17185. indices.push( a, b, b, c, c, a );
  17186. }
  17187. }
  17188. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17189. attribute.version = getWireframeVersion( geometry );
  17190. return attribute;
  17191. }
  17192. /**
  17193. * This renderer module manages geometries.
  17194. *
  17195. * @private
  17196. * @augments DataMap
  17197. */
  17198. class Geometries extends DataMap {
  17199. /**
  17200. * Constructs a new geometry management component.
  17201. *
  17202. * @param {Attributes} attributes - Renderer component for managing attributes.
  17203. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17204. */
  17205. constructor( attributes, info ) {
  17206. super();
  17207. /**
  17208. * Renderer component for managing attributes.
  17209. *
  17210. * @type {Attributes}
  17211. */
  17212. this.attributes = attributes;
  17213. /**
  17214. * Renderer component for managing metrics and monitoring data.
  17215. *
  17216. * @type {Info}
  17217. */
  17218. this.info = info;
  17219. /**
  17220. * Weak Map for managing attributes for wireframe rendering.
  17221. *
  17222. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17223. */
  17224. this.wireframes = new WeakMap();
  17225. /**
  17226. * This Weak Map is used to make sure buffer attributes are
  17227. * updated only once per render call.
  17228. *
  17229. * @type {WeakMap<BufferAttribute,Number>}
  17230. */
  17231. this.attributeCall = new WeakMap();
  17232. }
  17233. /**
  17234. * Returns `true` if the given render object has an initialized geometry.
  17235. *
  17236. * @param {RenderObject} renderObject - The render object.
  17237. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  17238. */
  17239. has( renderObject ) {
  17240. const geometry = renderObject.geometry;
  17241. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17242. }
  17243. /**
  17244. * Prepares the geometry of the given render object for rendering.
  17245. *
  17246. * @param {RenderObject} renderObject - The render object.
  17247. */
  17248. updateForRender( renderObject ) {
  17249. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17250. this.updateAttributes( renderObject );
  17251. }
  17252. /**
  17253. * Initializes the geometry of the given render object.
  17254. *
  17255. * @param {RenderObject} renderObject - The render object.
  17256. */
  17257. initGeometry( renderObject ) {
  17258. const geometry = renderObject.geometry;
  17259. const geometryData = this.get( geometry );
  17260. geometryData.initialized = true;
  17261. this.info.memory.geometries ++;
  17262. const onDispose = () => {
  17263. this.info.memory.geometries --;
  17264. const index = geometry.index;
  17265. const geometryAttributes = renderObject.getAttributes();
  17266. if ( index !== null ) {
  17267. this.attributes.delete( index );
  17268. }
  17269. for ( const geometryAttribute of geometryAttributes ) {
  17270. this.attributes.delete( geometryAttribute );
  17271. }
  17272. const wireframeAttribute = this.wireframes.get( geometry );
  17273. if ( wireframeAttribute !== undefined ) {
  17274. this.attributes.delete( wireframeAttribute );
  17275. }
  17276. geometry.removeEventListener( 'dispose', onDispose );
  17277. };
  17278. geometry.addEventListener( 'dispose', onDispose );
  17279. }
  17280. /**
  17281. * Updates the geometry attributes of the given render object.
  17282. *
  17283. * @param {RenderObject} renderObject - The render object.
  17284. */
  17285. updateAttributes( renderObject ) {
  17286. // attributes
  17287. const attributes = renderObject.getAttributes();
  17288. for ( const attribute of attributes ) {
  17289. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17290. this.updateAttribute( attribute, AttributeType.STORAGE );
  17291. } else {
  17292. this.updateAttribute( attribute, AttributeType.VERTEX );
  17293. }
  17294. }
  17295. // indexes
  17296. const index = this.getIndex( renderObject );
  17297. if ( index !== null ) {
  17298. this.updateAttribute( index, AttributeType.INDEX );
  17299. }
  17300. // indirect
  17301. const indirect = renderObject.geometry.indirect;
  17302. if ( indirect !== null ) {
  17303. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17304. }
  17305. }
  17306. /**
  17307. * Updates the given attribute.
  17308. *
  17309. * @param {BufferAttribute} attribute - The attribute to update.
  17310. * @param {Number} type - The attribute type.
  17311. */
  17312. updateAttribute( attribute, type ) {
  17313. const callId = this.info.render.calls;
  17314. if ( ! attribute.isInterleavedBufferAttribute ) {
  17315. if ( this.attributeCall.get( attribute ) !== callId ) {
  17316. this.attributes.update( attribute, type );
  17317. this.attributeCall.set( attribute, callId );
  17318. }
  17319. } else {
  17320. if ( this.attributeCall.get( attribute ) === undefined ) {
  17321. this.attributes.update( attribute, type );
  17322. this.attributeCall.set( attribute, callId );
  17323. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17324. this.attributes.update( attribute, type );
  17325. this.attributeCall.set( attribute.data, callId );
  17326. this.attributeCall.set( attribute, callId );
  17327. }
  17328. }
  17329. }
  17330. /**
  17331. * Returns the indirect buffer attribute of the given render object.
  17332. *
  17333. * @param {RenderObject} renderObject - The render object.
  17334. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17335. */
  17336. getIndirect( renderObject ) {
  17337. return renderObject.geometry.indirect;
  17338. }
  17339. /**
  17340. * Returns the index of the given render object's geometry. This is implemented
  17341. * in a method to return a wireframe index if necessary.
  17342. *
  17343. * @param {RenderObject} renderObject - The render object.
  17344. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17345. */
  17346. getIndex( renderObject ) {
  17347. const { geometry, material } = renderObject;
  17348. let index = geometry.index;
  17349. if ( material.wireframe === true ) {
  17350. const wireframes = this.wireframes;
  17351. let wireframeAttribute = wireframes.get( geometry );
  17352. if ( wireframeAttribute === undefined ) {
  17353. wireframeAttribute = getWireframeIndex( geometry );
  17354. wireframes.set( geometry, wireframeAttribute );
  17355. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17356. this.attributes.delete( wireframeAttribute );
  17357. wireframeAttribute = getWireframeIndex( geometry );
  17358. wireframes.set( geometry, wireframeAttribute );
  17359. }
  17360. index = wireframeAttribute;
  17361. }
  17362. return index;
  17363. }
  17364. }
  17365. /**
  17366. * This renderer module provides a series of statistical information
  17367. * about the GPU memory and the rendering process. Useful for debugging
  17368. * and monitoring.
  17369. */
  17370. class Info {
  17371. /**
  17372. * Constructs a new info component.
  17373. */
  17374. constructor() {
  17375. /**
  17376. * Whether frame related metrics should automatically
  17377. * be resetted or not. This property should be set to `false`
  17378. * by apps which manage their own animation loop. They must
  17379. * then call `renderer.info.reset()` once per frame manually.
  17380. *
  17381. * @type {Boolean}
  17382. * @default true
  17383. */
  17384. this.autoReset = true;
  17385. /**
  17386. * The current frame ID. This ID is managed
  17387. * by `NodeFrame`.
  17388. *
  17389. * @type {Number}
  17390. * @readonly
  17391. * @default 0
  17392. */
  17393. this.frame = 0;
  17394. /**
  17395. * The number of render calls since the
  17396. * app has been started.
  17397. *
  17398. * @type {Number}
  17399. * @readonly
  17400. * @default 0
  17401. */
  17402. this.calls = 0;
  17403. /**
  17404. * Render related metrics.
  17405. *
  17406. * @type {Object}
  17407. * @readonly
  17408. * @property {Number} calls - The number of render calls since the app has been started.
  17409. * @property {Number} frameCalls - The number of render calls of the current frame.
  17410. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17411. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17412. * @property {Number} points - The number of rendered point primitives of the current frame.
  17413. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17414. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17415. */
  17416. this.render = {
  17417. calls: 0,
  17418. frameCalls: 0,
  17419. drawCalls: 0,
  17420. triangles: 0,
  17421. points: 0,
  17422. lines: 0,
  17423. timestamp: 0,
  17424. };
  17425. /**
  17426. * Compute related metrics.
  17427. *
  17428. * @type {Object}
  17429. * @readonly
  17430. * @property {Number} calls - The number of compute calls since the app has been started.
  17431. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17432. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17433. */
  17434. this.compute = {
  17435. calls: 0,
  17436. frameCalls: 0,
  17437. timestamp: 0
  17438. };
  17439. /**
  17440. * Memory related metrics.
  17441. *
  17442. * @type {Object}
  17443. * @readonly
  17444. * @property {Number} geometries - The number of active geometries.
  17445. * @property {Number} frameCalls - The number of active textures.
  17446. */
  17447. this.memory = {
  17448. geometries: 0,
  17449. textures: 0
  17450. };
  17451. }
  17452. /**
  17453. * This method should be executed per draw call and updates the corresponding metrics.
  17454. *
  17455. * @param {Object3D} object - The 3D object that is going to be rendered.
  17456. * @param {Number} count - The vertex or index count.
  17457. * @param {Number} instanceCount - The instance count.
  17458. */
  17459. update( object, count, instanceCount ) {
  17460. this.render.drawCalls ++;
  17461. if ( object.isMesh || object.isSprite ) {
  17462. this.render.triangles += instanceCount * ( count / 3 );
  17463. } else if ( object.isPoints ) {
  17464. this.render.points += instanceCount * count;
  17465. } else if ( object.isLineSegments ) {
  17466. this.render.lines += instanceCount * ( count / 2 );
  17467. } else if ( object.isLine ) {
  17468. this.render.lines += instanceCount * ( count - 1 );
  17469. } else {
  17470. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17471. }
  17472. }
  17473. /**
  17474. * Resets frame related metrics.
  17475. */
  17476. reset() {
  17477. this.render.drawCalls = 0;
  17478. this.render.frameCalls = 0;
  17479. this.compute.frameCalls = 0;
  17480. this.render.triangles = 0;
  17481. this.render.points = 0;
  17482. this.render.lines = 0;
  17483. }
  17484. /**
  17485. * Performs a complete reset of the object.
  17486. */
  17487. dispose() {
  17488. this.reset();
  17489. this.calls = 0;
  17490. this.render.calls = 0;
  17491. this.compute.calls = 0;
  17492. this.render.timestamp = 0;
  17493. this.compute.timestamp = 0;
  17494. this.memory.geometries = 0;
  17495. this.memory.textures = 0;
  17496. }
  17497. }
  17498. /**
  17499. * Abstract class for representing pipelines.
  17500. *
  17501. * @private
  17502. * @abstract
  17503. */
  17504. class Pipeline {
  17505. /**
  17506. * Constructs a new pipeline.
  17507. *
  17508. * @param {String} cacheKey - The pipeline's cache key.
  17509. */
  17510. constructor( cacheKey ) {
  17511. /**
  17512. * The pipeline's cache key.
  17513. *
  17514. * @type {String}
  17515. */
  17516. this.cacheKey = cacheKey;
  17517. /**
  17518. * How often the pipeline is currently in use.
  17519. *
  17520. * @type {Number}
  17521. * @default 0
  17522. */
  17523. this.usedTimes = 0;
  17524. }
  17525. }
  17526. /**
  17527. * Class for representing render pipelines.
  17528. *
  17529. * @private
  17530. * @augments Pipeline
  17531. */
  17532. class RenderPipeline extends Pipeline {
  17533. /**
  17534. * Constructs a new render pipeline.
  17535. *
  17536. * @param {String} cacheKey - The pipeline's cache key.
  17537. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17538. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17539. */
  17540. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17541. super( cacheKey );
  17542. /**
  17543. * The pipeline's vertex shader.
  17544. *
  17545. * @type {ProgrammableStage}
  17546. */
  17547. this.vertexProgram = vertexProgram;
  17548. /**
  17549. * The pipeline's fragment shader.
  17550. *
  17551. * @type {ProgrammableStage}
  17552. */
  17553. this.fragmentProgram = fragmentProgram;
  17554. }
  17555. }
  17556. /**
  17557. * Class for representing compute pipelines.
  17558. *
  17559. * @private
  17560. * @augments Pipeline
  17561. */
  17562. class ComputePipeline extends Pipeline {
  17563. /**
  17564. * Constructs a new render pipeline.
  17565. *
  17566. * @param {String} cacheKey - The pipeline's cache key.
  17567. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17568. */
  17569. constructor( cacheKey, computeProgram ) {
  17570. super( cacheKey );
  17571. /**
  17572. * The pipeline's compute shader.
  17573. *
  17574. * @type {ProgrammableStage}
  17575. */
  17576. this.computeProgram = computeProgram;
  17577. /**
  17578. * This flag can be used for type testing.
  17579. *
  17580. * @type {Boolean}
  17581. * @readonly
  17582. * @default true
  17583. */
  17584. this.isComputePipeline = true;
  17585. }
  17586. }
  17587. let _id$8 = 0;
  17588. /**
  17589. * Class for representing programmable stages which are vertex,
  17590. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17591. * they represent the programmable part of a pipeline.
  17592. *
  17593. * @private
  17594. */
  17595. class ProgrammableStage {
  17596. /**
  17597. * Constructs a new programmable stage.
  17598. *
  17599. * @param {String} code - The shader code.
  17600. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17601. * @param {String} name - The name of the shader.
  17602. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17603. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17604. */
  17605. constructor( code, stage, name, transforms = null, attributes = null ) {
  17606. /**
  17607. * The id of the programmable stage.
  17608. *
  17609. * @type {Number}
  17610. */
  17611. this.id = _id$8 ++;
  17612. /**
  17613. * The shader code.
  17614. *
  17615. * @type {String}
  17616. */
  17617. this.code = code;
  17618. /**
  17619. * The type of stage.
  17620. *
  17621. * @type {String}
  17622. */
  17623. this.stage = stage;
  17624. /**
  17625. * The name of the stage.
  17626. * This is used for debugging purposes.
  17627. *
  17628. * @type {String}
  17629. */
  17630. this.name = name;
  17631. /**
  17632. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17633. *
  17634. * @type {Array<Object>?}
  17635. */
  17636. this.transforms = transforms;
  17637. /**
  17638. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17639. *
  17640. * @type {Array<Object>?}
  17641. */
  17642. this.attributes = attributes;
  17643. /**
  17644. * How often the programmable stage is currently in use.
  17645. *
  17646. * @type {Number}
  17647. * @default 0
  17648. */
  17649. this.usedTimes = 0;
  17650. }
  17651. }
  17652. /**
  17653. * This renderer module manages the pipelines of the renderer.
  17654. *
  17655. * @private
  17656. * @augments DataMap
  17657. */
  17658. class Pipelines extends DataMap {
  17659. /**
  17660. * Constructs a new pipeline management component.
  17661. *
  17662. * @param {Backend} backend - The renderer's backend.
  17663. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17664. */
  17665. constructor( backend, nodes ) {
  17666. super();
  17667. /**
  17668. * The renderer's backend.
  17669. *
  17670. * @type {Backend}
  17671. */
  17672. this.backend = backend;
  17673. /**
  17674. * Renderer component for managing nodes related logic.
  17675. *
  17676. * @type {Nodes}
  17677. */
  17678. this.nodes = nodes;
  17679. /**
  17680. * A references to the bindings management component.
  17681. * This reference will be set inside the `Bindings`
  17682. * constructor.
  17683. *
  17684. * @type {Bindings?}
  17685. * @default null
  17686. */
  17687. this.bindings = null;
  17688. /**
  17689. * Internal cache for maintaining pipelines.
  17690. * The key of the map is a cache key, the value the pipeline.
  17691. *
  17692. * @type {Map<String,Pipeline>}
  17693. */
  17694. this.caches = new Map();
  17695. /**
  17696. * This dictionary maintains for each shader stage type (vertex,
  17697. * fragment and compute) the programmable stage objects which
  17698. * represent the actual shader code.
  17699. *
  17700. * @type {Object<String,Map>}
  17701. */
  17702. this.programs = {
  17703. vertex: new Map(),
  17704. fragment: new Map(),
  17705. compute: new Map()
  17706. };
  17707. }
  17708. /**
  17709. * Returns a compute pipeline for the given compute node.
  17710. *
  17711. * @param {Node} computeNode - The compute node.
  17712. * @param {Array<BindGroup>} bindings - The bindings.
  17713. * @return {ComputePipeline} The compute pipeline.
  17714. */
  17715. getForCompute( computeNode, bindings ) {
  17716. const { backend } = this;
  17717. const data = this.get( computeNode );
  17718. if ( this._needsComputeUpdate( computeNode ) ) {
  17719. const previousPipeline = data.pipeline;
  17720. if ( previousPipeline ) {
  17721. previousPipeline.usedTimes --;
  17722. previousPipeline.computeProgram.usedTimes --;
  17723. }
  17724. // get shader
  17725. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17726. // programmable stage
  17727. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17728. if ( stageCompute === undefined ) {
  17729. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17730. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17731. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17732. backend.createProgram( stageCompute );
  17733. }
  17734. // determine compute pipeline
  17735. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17736. let pipeline = this.caches.get( cacheKey );
  17737. if ( pipeline === undefined ) {
  17738. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17739. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17740. }
  17741. // keep track of all used times
  17742. pipeline.usedTimes ++;
  17743. stageCompute.usedTimes ++;
  17744. //
  17745. data.version = computeNode.version;
  17746. data.pipeline = pipeline;
  17747. }
  17748. return data.pipeline;
  17749. }
  17750. /**
  17751. * Returns a render pipeline for the given render object.
  17752. *
  17753. * @param {RenderObject} renderObject - The render object.
  17754. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17755. * @return {RenderPipeline} The render pipeline.
  17756. */
  17757. getForRender( renderObject, promises = null ) {
  17758. const { backend } = this;
  17759. const data = this.get( renderObject );
  17760. if ( this._needsRenderUpdate( renderObject ) ) {
  17761. const previousPipeline = data.pipeline;
  17762. if ( previousPipeline ) {
  17763. previousPipeline.usedTimes --;
  17764. previousPipeline.vertexProgram.usedTimes --;
  17765. previousPipeline.fragmentProgram.usedTimes --;
  17766. }
  17767. // get shader
  17768. const nodeBuilderState = renderObject.getNodeBuilderState();
  17769. const name = renderObject.material ? renderObject.material.name : '';
  17770. // programmable stages
  17771. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17772. if ( stageVertex === undefined ) {
  17773. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17774. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17775. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17776. backend.createProgram( stageVertex );
  17777. }
  17778. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17779. if ( stageFragment === undefined ) {
  17780. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17781. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17782. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17783. backend.createProgram( stageFragment );
  17784. }
  17785. // determine render pipeline
  17786. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17787. let pipeline = this.caches.get( cacheKey );
  17788. if ( pipeline === undefined ) {
  17789. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17790. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17791. } else {
  17792. renderObject.pipeline = pipeline;
  17793. }
  17794. // keep track of all used times
  17795. pipeline.usedTimes ++;
  17796. stageVertex.usedTimes ++;
  17797. stageFragment.usedTimes ++;
  17798. //
  17799. data.pipeline = pipeline;
  17800. }
  17801. return data.pipeline;
  17802. }
  17803. /**
  17804. * Deletes the pipeline for the given render object.
  17805. *
  17806. * @param {RenderObject} object - The render object.
  17807. * @return {Object?} The deleted dictionary.
  17808. */
  17809. delete( object ) {
  17810. const pipeline = this.get( object ).pipeline;
  17811. if ( pipeline ) {
  17812. // pipeline
  17813. pipeline.usedTimes --;
  17814. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17815. // programs
  17816. if ( pipeline.isComputePipeline ) {
  17817. pipeline.computeProgram.usedTimes --;
  17818. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17819. } else {
  17820. pipeline.fragmentProgram.usedTimes --;
  17821. pipeline.vertexProgram.usedTimes --;
  17822. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17823. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17824. }
  17825. }
  17826. return super.delete( object );
  17827. }
  17828. /**
  17829. * Frees internal resources.
  17830. */
  17831. dispose() {
  17832. super.dispose();
  17833. this.caches = new Map();
  17834. this.programs = {
  17835. vertex: new Map(),
  17836. fragment: new Map(),
  17837. compute: new Map()
  17838. };
  17839. }
  17840. /**
  17841. * Updates the pipeline for the given render object.
  17842. *
  17843. * @param {RenderObject} renderObject - The render object.
  17844. */
  17845. updateForRender( renderObject ) {
  17846. this.getForRender( renderObject );
  17847. }
  17848. /**
  17849. * Returns a compute pipeline for the given parameters.
  17850. *
  17851. * @private
  17852. * @param {Node} computeNode - The compute node.
  17853. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17854. * @param {String} cacheKey - The cache key.
  17855. * @param {Array<BindGroup>} bindings - The bindings.
  17856. * @return {ComputePipeline} The compute pipeline.
  17857. */
  17858. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17859. // check for existing pipeline
  17860. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17861. let pipeline = this.caches.get( cacheKey );
  17862. if ( pipeline === undefined ) {
  17863. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17864. this.caches.set( cacheKey, pipeline );
  17865. this.backend.createComputePipeline( pipeline, bindings );
  17866. }
  17867. return pipeline;
  17868. }
  17869. /**
  17870. * Returns a render pipeline for the given parameters.
  17871. *
  17872. * @private
  17873. * @param {RenderObject} renderObject - The render object.
  17874. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17875. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17876. * @param {String} cacheKey - The cache key.
  17877. * @param {Array<Promise>?} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17878. * @return {ComputePipeline} The compute pipeline.
  17879. */
  17880. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17881. // check for existing pipeline
  17882. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17883. let pipeline = this.caches.get( cacheKey );
  17884. if ( pipeline === undefined ) {
  17885. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17886. this.caches.set( cacheKey, pipeline );
  17887. renderObject.pipeline = pipeline;
  17888. // The `promises` array is `null` by default and only set to an empty array when
  17889. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17890. // pending promises that resolve when the render pipelines are ready for rendering.
  17891. this.backend.createRenderPipeline( renderObject, promises );
  17892. }
  17893. return pipeline;
  17894. }
  17895. /**
  17896. * Computes a cache key representing a compute pipeline.
  17897. *
  17898. * @private
  17899. * @param {Node} computeNode - The compute node.
  17900. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17901. * @return {String} The cache key.
  17902. */
  17903. _getComputeCacheKey( computeNode, stageCompute ) {
  17904. return computeNode.id + ',' + stageCompute.id;
  17905. }
  17906. /**
  17907. * Computes a cache key representing a render pipeline.
  17908. *
  17909. * @private
  17910. * @param {RenderObject} renderObject - The render object.
  17911. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17912. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17913. * @return {String} The cache key.
  17914. */
  17915. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17916. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17917. }
  17918. /**
  17919. * Releases the given pipeline.
  17920. *
  17921. * @private
  17922. * @param {Pipeline} pipeline - The pipeline to release.
  17923. */
  17924. _releasePipeline( pipeline ) {
  17925. this.caches.delete( pipeline.cacheKey );
  17926. }
  17927. /**
  17928. * Releases the shader program.
  17929. *
  17930. * @private
  17931. * @param {Object} program - The shader program to release.
  17932. */
  17933. _releaseProgram( program ) {
  17934. const code = program.code;
  17935. const stage = program.stage;
  17936. this.programs[ stage ].delete( code );
  17937. }
  17938. /**
  17939. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17940. *
  17941. * @private
  17942. * @param {Node} computeNode - The compute node.
  17943. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17944. */
  17945. _needsComputeUpdate( computeNode ) {
  17946. const data = this.get( computeNode );
  17947. return data.pipeline === undefined || data.version !== computeNode.version;
  17948. }
  17949. /**
  17950. * Returns `true` if the render pipeline for the given render object requires an update.
  17951. *
  17952. * @private
  17953. * @param {RenderObject} renderObject - The render object.
  17954. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17955. */
  17956. _needsRenderUpdate( renderObject ) {
  17957. const data = this.get( renderObject );
  17958. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17959. }
  17960. }
  17961. /**
  17962. * This renderer module manages the bindings of the renderer.
  17963. *
  17964. * @private
  17965. * @augments DataMap
  17966. */
  17967. class Bindings extends DataMap {
  17968. /**
  17969. * Constructs a new bindings management component.
  17970. *
  17971. * @param {Backend} backend - The renderer's backend.
  17972. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17973. * @param {Textures} textures - Renderer component for managing textures.
  17974. * @param {Attributes} attributes - Renderer component for managing attributes.
  17975. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17976. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17977. */
  17978. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17979. super();
  17980. /**
  17981. * The renderer's backend.
  17982. *
  17983. * @type {Backend}
  17984. */
  17985. this.backend = backend;
  17986. /**
  17987. * Renderer component for managing textures.
  17988. *
  17989. * @type {Textures}
  17990. */
  17991. this.textures = textures;
  17992. /**
  17993. * Renderer component for managing pipelines.
  17994. *
  17995. * @type {Pipelines}
  17996. */
  17997. this.pipelines = pipelines;
  17998. /**
  17999. * Renderer component for managing attributes.
  18000. *
  18001. * @type {Attributes}
  18002. */
  18003. this.attributes = attributes;
  18004. /**
  18005. * Renderer component for managing nodes related logic.
  18006. *
  18007. * @type {Nodes}
  18008. */
  18009. this.nodes = nodes;
  18010. /**
  18011. * Renderer component for managing metrics and monitoring data.
  18012. *
  18013. * @type {Info}
  18014. */
  18015. this.info = info;
  18016. this.pipelines.bindings = this; // assign bindings to pipelines
  18017. }
  18018. /**
  18019. * Returns the bind groups for the given render object.
  18020. *
  18021. * @param {RenderObject} renderObject - The render object.
  18022. * @return {Array<BindGroup>} The bind groups.
  18023. */
  18024. getForRender( renderObject ) {
  18025. const bindings = renderObject.getBindings();
  18026. for ( const bindGroup of bindings ) {
  18027. const groupData = this.get( bindGroup );
  18028. if ( groupData.bindGroup === undefined ) {
  18029. // each object defines an array of bindings (ubos, textures, samplers etc.)
  18030. this._init( bindGroup );
  18031. this.backend.createBindings( bindGroup, bindings, 0 );
  18032. groupData.bindGroup = bindGroup;
  18033. }
  18034. }
  18035. return bindings;
  18036. }
  18037. /**
  18038. * Returns the bind groups for the given compute node.
  18039. *
  18040. * @param {Node} computeNode - The compute node.
  18041. * @return {Array<BindGroup>} The bind groups.
  18042. */
  18043. getForCompute( computeNode ) {
  18044. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  18045. for ( const bindGroup of bindings ) {
  18046. const groupData = this.get( bindGroup );
  18047. if ( groupData.bindGroup === undefined ) {
  18048. this._init( bindGroup );
  18049. this.backend.createBindings( bindGroup, bindings, 0 );
  18050. groupData.bindGroup = bindGroup;
  18051. }
  18052. }
  18053. return bindings;
  18054. }
  18055. /**
  18056. * Updates the bindings for the given compute node.
  18057. *
  18058. * @param {Node} computeNode - The compute node.
  18059. */
  18060. updateForCompute( computeNode ) {
  18061. this._updateBindings( this.getForCompute( computeNode ) );
  18062. }
  18063. /**
  18064. * Updates the bindings for the given render object.
  18065. *
  18066. * @param {RenderObject} renderObject - The render object.
  18067. */
  18068. updateForRender( renderObject ) {
  18069. this._updateBindings( this.getForRender( renderObject ) );
  18070. }
  18071. /**
  18072. * Updates the given array of bindings.
  18073. *
  18074. * @param {Array<BindGroup>} bindings - The bind groups.
  18075. */
  18076. _updateBindings( bindings ) {
  18077. for ( const bindGroup of bindings ) {
  18078. this._update( bindGroup, bindings );
  18079. }
  18080. }
  18081. /**
  18082. * Initializes the given bind group.
  18083. *
  18084. * @param {BindGroup} bindGroup - The bind group to initialize.
  18085. */
  18086. _init( bindGroup ) {
  18087. for ( const binding of bindGroup.bindings ) {
  18088. if ( binding.isSampledTexture ) {
  18089. this.textures.updateTexture( binding.texture );
  18090. } else if ( binding.isStorageBuffer ) {
  18091. const attribute = binding.attribute;
  18092. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  18093. this.attributes.update( attribute, attributeType );
  18094. }
  18095. }
  18096. }
  18097. /**
  18098. * Updates the given bind group.
  18099. *
  18100. * @param {BindGroup} bindGroup - The bind group to update.
  18101. * @param {Array<BindGroup>} bindings - The bind groups.
  18102. */
  18103. _update( bindGroup, bindings ) {
  18104. const { backend } = this;
  18105. let needsBindingsUpdate = false;
  18106. let cacheBindings = true;
  18107. let cacheIndex = 0;
  18108. let version = 0;
  18109. // iterate over all bindings and check if buffer updates or a new binding group is required
  18110. for ( const binding of bindGroup.bindings ) {
  18111. if ( binding.isNodeUniformsGroup ) {
  18112. const updated = this.nodes.updateGroup( binding );
  18113. // every uniforms group is a uniform buffer. So if no update is required,
  18114. // we move one with the next binding. Otherwise the next if block will update the group.
  18115. if ( updated === false ) continue;
  18116. }
  18117. if ( binding.isUniformBuffer ) {
  18118. const updated = binding.update();
  18119. if ( updated ) {
  18120. backend.updateBinding( binding );
  18121. }
  18122. } else if ( binding.isSampler ) {
  18123. binding.update();
  18124. } else if ( binding.isSampledTexture ) {
  18125. const texturesTextureData = this.textures.get( binding.texture );
  18126. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18127. const updated = binding.update();
  18128. const texture = binding.texture;
  18129. if ( updated ) {
  18130. this.textures.updateTexture( texture );
  18131. }
  18132. const textureData = backend.get( texture );
  18133. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18134. cacheBindings = false;
  18135. } else {
  18136. cacheIndex = cacheIndex * 10 + texture.id;
  18137. version += texture.version;
  18138. }
  18139. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18140. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18141. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18142. this.textures.updateTexture( texture );
  18143. needsBindingsUpdate = true;
  18144. }
  18145. if ( texture.isStorageTexture === true ) {
  18146. const textureData = this.get( texture );
  18147. if ( binding.store === true ) {
  18148. textureData.needsMipmap = true;
  18149. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18150. this.backend.generateMipmaps( texture );
  18151. textureData.needsMipmap = false;
  18152. }
  18153. }
  18154. }
  18155. }
  18156. if ( needsBindingsUpdate === true ) {
  18157. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18158. }
  18159. }
  18160. }
  18161. /**
  18162. * Default sorting function for opaque render items.
  18163. *
  18164. * @private
  18165. * @function
  18166. * @param {Object} a - The first render item.
  18167. * @param {Object} b - The second render item.
  18168. * @return {Number} A numeric value which defines the sort order.
  18169. */
  18170. function painterSortStable( a, b ) {
  18171. if ( a.groupOrder !== b.groupOrder ) {
  18172. return a.groupOrder - b.groupOrder;
  18173. } else if ( a.renderOrder !== b.renderOrder ) {
  18174. return a.renderOrder - b.renderOrder;
  18175. } else if ( a.material.id !== b.material.id ) {
  18176. return a.material.id - b.material.id;
  18177. } else if ( a.z !== b.z ) {
  18178. return a.z - b.z;
  18179. } else {
  18180. return a.id - b.id;
  18181. }
  18182. }
  18183. /**
  18184. * Default sorting function for transparent render items.
  18185. *
  18186. * @private
  18187. * @function
  18188. * @param {Object} a - The first render item.
  18189. * @param {Object} b - The second render item.
  18190. * @return {Number} A numeric value which defines the sort order.
  18191. */
  18192. function reversePainterSortStable( a, b ) {
  18193. if ( a.groupOrder !== b.groupOrder ) {
  18194. return a.groupOrder - b.groupOrder;
  18195. } else if ( a.renderOrder !== b.renderOrder ) {
  18196. return a.renderOrder - b.renderOrder;
  18197. } else if ( a.z !== b.z ) {
  18198. return b.z - a.z;
  18199. } else {
  18200. return a.id - b.id;
  18201. }
  18202. }
  18203. /**
  18204. * Returns `true` if the given transparent material requires a double pass.
  18205. *
  18206. * @private
  18207. * @function
  18208. * @param {Material} material - The transparent material.
  18209. * @return {Boolean} Whether the given material requires a double pass or not.
  18210. */
  18211. function needsDoublePass( material ) {
  18212. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18213. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18214. }
  18215. /**
  18216. * When the renderer analyzes the scene at the beginning of a render call,
  18217. * it stores 3D object for further processing in render lists. Depending on the
  18218. * properties of a 3D objects (like their transformation or material state), the
  18219. * objects are maintained in ordered lists for the actual rendering.
  18220. *
  18221. * Render lists are unique per scene and camera combination.
  18222. *
  18223. * @private
  18224. * @augments Pipeline
  18225. */
  18226. class RenderList {
  18227. /**
  18228. * Constructs a render list.
  18229. *
  18230. * @param {Lighting} lighting - The lighting management component.
  18231. * @param {Scene} scene - The scene.
  18232. * @param {Camera} camera - The camera the scene is rendered with.
  18233. */
  18234. constructor( lighting, scene, camera ) {
  18235. /**
  18236. * 3D objects are transformed into render items and stored in this array.
  18237. *
  18238. * @type {Array<Object>}
  18239. */
  18240. this.renderItems = [];
  18241. /**
  18242. * The current render items index.
  18243. *
  18244. * @type {Number}
  18245. * @default 0
  18246. */
  18247. this.renderItemsIndex = 0;
  18248. /**
  18249. * A list with opaque render items.
  18250. *
  18251. * @type {Array<Object>}
  18252. */
  18253. this.opaque = [];
  18254. /**
  18255. * A list with transparent render items which require
  18256. * double pass rendering (e.g. transmissive objects).
  18257. *
  18258. * @type {Array<Object>}
  18259. */
  18260. this.transparentDoublePass = [];
  18261. /**
  18262. * A list with transparent render items.
  18263. *
  18264. * @type {Array<Object>}
  18265. */
  18266. this.transparent = [];
  18267. /**
  18268. * A list with transparent render bundle data.
  18269. *
  18270. * @type {Array<Object>}
  18271. */
  18272. this.bundles = [];
  18273. /**
  18274. * The render list's lights node. This node is later
  18275. * relevant for the actual analytical light nodes which
  18276. * compute the scene's lighting in the shader.
  18277. *
  18278. * @type {LightsNode}
  18279. */
  18280. this.lightsNode = lighting.getNode( scene, camera );
  18281. /**
  18282. * The scene's lights stored in an array. This array
  18283. * is used to setup the lights node.
  18284. *
  18285. * @type {Array<Light>}
  18286. */
  18287. this.lightsArray = [];
  18288. /**
  18289. * The scene.
  18290. *
  18291. * @type {Scene}
  18292. */
  18293. this.scene = scene;
  18294. /**
  18295. * The camera the scene is rendered with.
  18296. *
  18297. * @type {Camera}
  18298. */
  18299. this.camera = camera;
  18300. /**
  18301. * How many objects perform occlusion query tests.
  18302. *
  18303. * @type {Number}
  18304. * @default 0
  18305. */
  18306. this.occlusionQueryCount = 0;
  18307. }
  18308. /**
  18309. * This method is called right at the beginning of a render call
  18310. * before the scene is analyzed. It prepares the internal data
  18311. * structures for the upcoming render lists generation.
  18312. *
  18313. * @return {RenderList} A reference to this render list.
  18314. */
  18315. begin() {
  18316. this.renderItemsIndex = 0;
  18317. this.opaque.length = 0;
  18318. this.transparentDoublePass.length = 0;
  18319. this.transparent.length = 0;
  18320. this.bundles.length = 0;
  18321. this.lightsArray.length = 0;
  18322. this.occlusionQueryCount = 0;
  18323. return this;
  18324. }
  18325. /**
  18326. * Returns a render item for the giving render item state. The state is defined
  18327. * by a series of object-related parameters.
  18328. *
  18329. * The method avoids object creation by holding render items and reusing them in
  18330. * subsequent render calls (just with different property values).
  18331. *
  18332. * @param {Object3D} object - The 3D object.
  18333. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18334. * @param {Material} material - The 3D object's material.
  18335. * @param {Number} groupOrder - The current group order.
  18336. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18337. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18338. * @param {ClippingContext} clippingContext - The current clipping context.
  18339. * @return {Object} The render item.
  18340. */
  18341. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18342. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18343. if ( renderItem === undefined ) {
  18344. renderItem = {
  18345. id: object.id,
  18346. object: object,
  18347. geometry: geometry,
  18348. material: material,
  18349. groupOrder: groupOrder,
  18350. renderOrder: object.renderOrder,
  18351. z: z,
  18352. group: group,
  18353. clippingContext: clippingContext
  18354. };
  18355. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18356. } else {
  18357. renderItem.id = object.id;
  18358. renderItem.object = object;
  18359. renderItem.geometry = geometry;
  18360. renderItem.material = material;
  18361. renderItem.groupOrder = groupOrder;
  18362. renderItem.renderOrder = object.renderOrder;
  18363. renderItem.z = z;
  18364. renderItem.group = group;
  18365. renderItem.clippingContext = clippingContext;
  18366. }
  18367. this.renderItemsIndex ++;
  18368. return renderItem;
  18369. }
  18370. /**
  18371. * Pushes the given object as a render item to the internal render lists.
  18372. * The selected lists depend on the object properties.
  18373. *
  18374. * @param {Object3D} object - The 3D object.
  18375. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18376. * @param {Material} material - The 3D object's material.
  18377. * @param {Number} groupOrder - The current group order.
  18378. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18379. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18380. * @param {ClippingContext} clippingContext - The current clipping context.
  18381. */
  18382. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18383. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18384. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18385. if ( material.transparent === true || material.transmission > 0 ) {
  18386. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18387. this.transparent.push( renderItem );
  18388. } else {
  18389. this.opaque.push( renderItem );
  18390. }
  18391. }
  18392. /**
  18393. * Inserts the given object as a render item at the start of the internal render lists.
  18394. * The selected lists depend on the object properties.
  18395. *
  18396. * @param {Object3D} object - The 3D object.
  18397. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18398. * @param {Material} material - The 3D object's material.
  18399. * @param {Number} groupOrder - The current group order.
  18400. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18401. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18402. * @param {ClippingContext} clippingContext - The current clipping context.
  18403. */
  18404. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18405. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18406. if ( material.transparent === true || material.transmission > 0 ) {
  18407. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18408. this.transparent.unshift( renderItem );
  18409. } else {
  18410. this.opaque.unshift( renderItem );
  18411. }
  18412. }
  18413. /**
  18414. * Pushes render bundle group data into the render list.
  18415. *
  18416. * @param {Object} group - Bundle group data.
  18417. */
  18418. pushBundle( group ) {
  18419. this.bundles.push( group );
  18420. }
  18421. /**
  18422. * Pushes a light into the render list.
  18423. *
  18424. * @param {Light} light - The light.
  18425. */
  18426. pushLight( light ) {
  18427. this.lightsArray.push( light );
  18428. }
  18429. /**
  18430. * Sorts the internal render lists.
  18431. *
  18432. * @param {function(Any, Any): Number} customOpaqueSort - A custom sort function for opaque objects.
  18433. * @param {function(Any, Any): Number} customTransparentSort - A custom sort function for transparent objects.
  18434. */
  18435. sort( customOpaqueSort, customTransparentSort ) {
  18436. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18437. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18438. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18439. }
  18440. /**
  18441. * This method performs finalizing tasks right after the render lists
  18442. * have been generated.
  18443. */
  18444. finish() {
  18445. // update lights
  18446. this.lightsNode.setLights( this.lightsArray );
  18447. // Clear references from inactive renderItems in the list
  18448. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18449. const renderItem = this.renderItems[ i ];
  18450. if ( renderItem.id === null ) break;
  18451. renderItem.id = null;
  18452. renderItem.object = null;
  18453. renderItem.geometry = null;
  18454. renderItem.material = null;
  18455. renderItem.groupOrder = null;
  18456. renderItem.renderOrder = null;
  18457. renderItem.z = null;
  18458. renderItem.group = null;
  18459. renderItem.clippingContext = null;
  18460. }
  18461. }
  18462. }
  18463. const _chainKeys$4 = [];
  18464. /**
  18465. * This renderer module manages the render lists which are unique
  18466. * per scene and camera combination.
  18467. *
  18468. * @private
  18469. */
  18470. class RenderLists {
  18471. /**
  18472. * Constructs a render lists management component.
  18473. *
  18474. * @param {Lighting} lighting - The lighting management component.
  18475. */
  18476. constructor( lighting ) {
  18477. /**
  18478. * The lighting management component.
  18479. *
  18480. * @type {Lighting}
  18481. */
  18482. this.lighting = lighting;
  18483. /**
  18484. * The internal chain map which holds the render lists.
  18485. *
  18486. * @type {ChainMap}
  18487. */
  18488. this.lists = new ChainMap();
  18489. }
  18490. /**
  18491. * Returns a render list for the given scene and camera.
  18492. *
  18493. * @param {Scene} scene - The scene.
  18494. * @param {Camera} camera - The camera.
  18495. * @return {RenderList} The render list.
  18496. */
  18497. get( scene, camera ) {
  18498. const lists = this.lists;
  18499. _chainKeys$4[ 0 ] = scene;
  18500. _chainKeys$4[ 1 ] = camera;
  18501. let list = lists.get( _chainKeys$4 );
  18502. if ( list === undefined ) {
  18503. list = new RenderList( this.lighting, scene, camera );
  18504. lists.set( _chainKeys$4, list );
  18505. }
  18506. _chainKeys$4.length = 0;
  18507. return list;
  18508. }
  18509. /**
  18510. * Frees all internal resources.
  18511. */
  18512. dispose() {
  18513. this.lists = new ChainMap();
  18514. }
  18515. }
  18516. let _id$7 = 0;
  18517. /**
  18518. * Any render or compute command is executed in a specific context that defines
  18519. * the state of the renderer and its backend. Typical examples for such context
  18520. * data are the current clear values or data from the active framebuffer. This
  18521. * module is used to represent these contexts as objects.
  18522. *
  18523. * @private
  18524. */
  18525. class RenderContext {
  18526. /**
  18527. * Constructs a new render context.
  18528. */
  18529. constructor() {
  18530. /**
  18531. * The context's ID.
  18532. *
  18533. * @type {Number}
  18534. */
  18535. this.id = _id$7 ++;
  18536. /**
  18537. * Whether the current active framebuffer has a color attachment.
  18538. *
  18539. * @type {Boolean}
  18540. * @default true
  18541. */
  18542. this.color = true;
  18543. /**
  18544. * Whether the color attachment should be cleared or not.
  18545. *
  18546. * @type {Boolean}
  18547. * @default true
  18548. */
  18549. this.clearColor = true;
  18550. /**
  18551. * The clear color value.
  18552. *
  18553. * @type {Object}
  18554. * @default true
  18555. */
  18556. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18557. /**
  18558. * Whether the current active framebuffer has a depth attachment.
  18559. *
  18560. * @type {Boolean}
  18561. * @default true
  18562. */
  18563. this.depth = true;
  18564. /**
  18565. * Whether the depth attachment should be cleared or not.
  18566. *
  18567. * @type {Boolean}
  18568. * @default true
  18569. */
  18570. this.clearDepth = true;
  18571. /**
  18572. * The clear depth value.
  18573. *
  18574. * @type {Number}
  18575. * @default 1
  18576. */
  18577. this.clearDepthValue = 1;
  18578. /**
  18579. * Whether the current active framebuffer has a stencil attachment.
  18580. *
  18581. * @type {Boolean}
  18582. * @default false
  18583. */
  18584. this.stencil = false;
  18585. /**
  18586. * Whether the stencil attachment should be cleared or not.
  18587. *
  18588. * @type {Boolean}
  18589. * @default true
  18590. */
  18591. this.clearStencil = true;
  18592. /**
  18593. * The clear stencil value.
  18594. *
  18595. * @type {Number}
  18596. * @default 1
  18597. */
  18598. this.clearStencilValue = 1;
  18599. /**
  18600. * By default the viewport encloses the entire framebuffer If a smaller
  18601. * viewport is manually defined, this property is to `true` by the renderer.
  18602. *
  18603. * @type {Boolean}
  18604. * @default false
  18605. */
  18606. this.viewport = false;
  18607. /**
  18608. * The viewport value. This value is in physical pixels meaning it incorporates
  18609. * the renderer's pixel ratio. The viewport property of render targets or
  18610. * the renderer is in logical pixels.
  18611. *
  18612. * @type {Vector4}
  18613. */
  18614. this.viewportValue = new Vector4();
  18615. /**
  18616. * When the scissor test is active and scissor rectangle smaller than the
  18617. * framebuffers dimensions, this property is to `true` by the renderer.
  18618. *
  18619. * @type {Boolean}
  18620. * @default false
  18621. */
  18622. this.scissor = false;
  18623. /**
  18624. * The scissor rectangle.
  18625. *
  18626. * @type {Vector4}
  18627. */
  18628. this.scissorValue = new Vector4();
  18629. /**
  18630. * The active render target.
  18631. *
  18632. * @type {RenderTarget?}
  18633. * @default null
  18634. */
  18635. this.renderTarget = null;
  18636. /**
  18637. * The textures of the active render target.
  18638. * `null` when no render target is set.
  18639. *
  18640. * @type {Array<Texture>?}
  18641. * @default null
  18642. */
  18643. this.textures = null;
  18644. /**
  18645. * The depth texture of the active render target.
  18646. * `null` when no render target is set.
  18647. *
  18648. * @type {DepthTexture?}
  18649. * @default null
  18650. */
  18651. this.depthTexture = null;
  18652. /**
  18653. * The active cube face.
  18654. *
  18655. * @type {Number}
  18656. * @default 0
  18657. */
  18658. this.activeCubeFace = 0;
  18659. /**
  18660. * The active mipmap level.
  18661. *
  18662. * @type {Number}
  18663. * @default 0
  18664. */
  18665. this.activeMipmapLevel = 0;
  18666. /**
  18667. * The number of MSAA samples. This value is always `1` when
  18668. * MSAA isn't used.
  18669. *
  18670. * @type {Number}
  18671. * @default 1
  18672. */
  18673. this.sampleCount = 1;
  18674. /**
  18675. * The active render target's width in physical pixels.
  18676. *
  18677. * @type {Number}
  18678. * @default 0
  18679. */
  18680. this.width = 0;
  18681. /**
  18682. * The active render target's height in physical pixels.
  18683. *
  18684. * @type {Number}
  18685. * @default 0
  18686. */
  18687. this.height = 0;
  18688. /**
  18689. * The occlusion query count.
  18690. *
  18691. * @type {Number}
  18692. * @default 0
  18693. */
  18694. this.occlusionQueryCount = 0;
  18695. /**
  18696. * The current clipping context.
  18697. *
  18698. * @type {ClippingContext?}
  18699. * @default null
  18700. */
  18701. this.clippingContext = null;
  18702. /**
  18703. * This flag can be used for type testing.
  18704. *
  18705. * @type {Boolean}
  18706. * @readonly
  18707. * @default true
  18708. */
  18709. this.isRenderContext = true;
  18710. }
  18711. /**
  18712. * Returns the cache key of this render context.
  18713. *
  18714. * @return {Number} The cache key.
  18715. */
  18716. getCacheKey() {
  18717. return getCacheKey( this );
  18718. }
  18719. }
  18720. /**
  18721. * Computes a cache key for the given render context. This key
  18722. * should identify the render target state so it is possible to
  18723. * configure the correct attachments in the respective backend.
  18724. *
  18725. * @param {RenderContext} renderContext - The render context.
  18726. * @return {Number} The cache key.
  18727. */
  18728. function getCacheKey( renderContext ) {
  18729. const { textures, activeCubeFace } = renderContext;
  18730. const values = [ activeCubeFace ];
  18731. for ( const texture of textures ) {
  18732. values.push( texture.id );
  18733. }
  18734. return hashArray( values );
  18735. }
  18736. const _chainKeys$3 = [];
  18737. const _defaultScene = /*@__PURE__*/ new Scene();
  18738. const _defaultCamera = /*@__PURE__*/ new Camera();
  18739. /**
  18740. * This module manages the render contexts of the renderer.
  18741. *
  18742. * @private
  18743. */
  18744. class RenderContexts {
  18745. /**
  18746. * Constructs a new render context management component.
  18747. */
  18748. constructor() {
  18749. /**
  18750. * A dictionary that manages render contexts in chain maps
  18751. * for each attachment state.
  18752. *
  18753. * @type {Object<String,ChainMap>}
  18754. */
  18755. this.chainMaps = {};
  18756. }
  18757. /**
  18758. * Returns a render context for the given scene, camera and render target.
  18759. *
  18760. * @param {Scene} scene - The scene.
  18761. * @param {Camera} camera - The camera that is used to render the scene.
  18762. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18763. * @return {RenderContext} The render context.
  18764. */
  18765. get( scene, camera, renderTarget = null ) {
  18766. _chainKeys$3[ 0 ] = scene;
  18767. _chainKeys$3[ 1 ] = camera;
  18768. let attachmentState;
  18769. if ( renderTarget === null ) {
  18770. attachmentState = 'default';
  18771. } else {
  18772. const format = renderTarget.texture.format;
  18773. const count = renderTarget.textures.length;
  18774. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18775. }
  18776. const chainMap = this._getChainMap( attachmentState );
  18777. let renderState = chainMap.get( _chainKeys$3 );
  18778. if ( renderState === undefined ) {
  18779. renderState = new RenderContext();
  18780. chainMap.set( _chainKeys$3, renderState );
  18781. }
  18782. _chainKeys$3.length = 0;
  18783. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18784. return renderState;
  18785. }
  18786. /**
  18787. * Returns a render context intended for clear operations.
  18788. *
  18789. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18790. * @return {RenderContext} The render context.
  18791. */
  18792. getForClear( renderTarget = null ) {
  18793. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18794. }
  18795. /**
  18796. * Returns a chain map for the given attachment state.
  18797. *
  18798. * @private
  18799. * @param {String} attachmentState - The attachment state.
  18800. * @return {ChainMap} The chain map.
  18801. */
  18802. _getChainMap( attachmentState ) {
  18803. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18804. }
  18805. /**
  18806. * Frees internal resources.
  18807. */
  18808. dispose() {
  18809. this.chainMaps = {};
  18810. }
  18811. }
  18812. const _size$3 = /*@__PURE__*/ new Vector3();
  18813. /**
  18814. * This module manages the textures of the renderer.
  18815. *
  18816. * @private
  18817. * @augments DataMap
  18818. */
  18819. class Textures extends DataMap {
  18820. /**
  18821. * Constructs a new texture management component.
  18822. *
  18823. * @param {Renderer} renderer - The renderer.
  18824. * @param {Backend} backend - The renderer's backend.
  18825. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18826. */
  18827. constructor( renderer, backend, info ) {
  18828. super();
  18829. /**
  18830. * The renderer.
  18831. *
  18832. * @type {Renderer}
  18833. */
  18834. this.renderer = renderer;
  18835. /**
  18836. * The backend.
  18837. *
  18838. * @type {Backend}
  18839. */
  18840. this.backend = backend;
  18841. /**
  18842. * Renderer component for managing metrics and monitoring data.
  18843. *
  18844. * @type {Info}
  18845. */
  18846. this.info = info;
  18847. }
  18848. /**
  18849. * Updates the given render target. Based on the given render target configuration,
  18850. * it updates the texture states representing the attachments of the framebuffer.
  18851. *
  18852. * @param {RenderTarget} renderTarget - The render target to update.
  18853. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18854. */
  18855. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18856. const renderTargetData = this.get( renderTarget );
  18857. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18858. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18859. const textures = renderTarget.textures;
  18860. const size = this.getSize( textures[ 0 ] );
  18861. const mipWidth = size.width >> activeMipmapLevel;
  18862. const mipHeight = size.height >> activeMipmapLevel;
  18863. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18864. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18865. let textureNeedsUpdate = false;
  18866. if ( depthTexture === undefined && useDepthTexture ) {
  18867. depthTexture = new DepthTexture();
  18868. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18869. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18870. depthTexture.image.width = mipWidth;
  18871. depthTexture.image.height = mipHeight;
  18872. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18873. }
  18874. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18875. textureNeedsUpdate = true;
  18876. if ( depthTexture ) {
  18877. depthTexture.needsUpdate = true;
  18878. depthTexture.image.width = mipWidth;
  18879. depthTexture.image.height = mipHeight;
  18880. }
  18881. }
  18882. renderTargetData.width = size.width;
  18883. renderTargetData.height = size.height;
  18884. renderTargetData.textures = textures;
  18885. renderTargetData.depthTexture = depthTexture || null;
  18886. renderTargetData.depth = renderTarget.depthBuffer;
  18887. renderTargetData.stencil = renderTarget.stencilBuffer;
  18888. renderTargetData.renderTarget = renderTarget;
  18889. if ( renderTargetData.sampleCount !== sampleCount ) {
  18890. textureNeedsUpdate = true;
  18891. if ( depthTexture ) {
  18892. depthTexture.needsUpdate = true;
  18893. }
  18894. renderTargetData.sampleCount = sampleCount;
  18895. }
  18896. //
  18897. const options = { sampleCount };
  18898. // when using the WebXR Layers API, the render target uses external textures which
  18899. // require no manual updates
  18900. if ( renderTarget.isXRRenderTarget === true && renderTarget.hasExternalTextures === true ) {
  18901. if ( depthTexture && renderTarget.autoAllocateDepthBuffer === true ) {
  18902. this.updateTexture( depthTexture, options );
  18903. }
  18904. } else {
  18905. for ( let i = 0; i < textures.length; i ++ ) {
  18906. const texture = textures[ i ];
  18907. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18908. this.updateTexture( texture, options );
  18909. }
  18910. if ( depthTexture ) {
  18911. this.updateTexture( depthTexture, options );
  18912. }
  18913. }
  18914. // dispose handler
  18915. if ( renderTargetData.initialized !== true ) {
  18916. renderTargetData.initialized = true;
  18917. // dispose
  18918. const onDispose = () => {
  18919. renderTarget.removeEventListener( 'dispose', onDispose );
  18920. for ( let i = 0; i < textures.length; i ++ ) {
  18921. this._destroyTexture( textures[ i ] );
  18922. }
  18923. if ( depthTexture ) {
  18924. this._destroyTexture( depthTexture );
  18925. }
  18926. this.delete( renderTarget );
  18927. };
  18928. renderTarget.addEventListener( 'dispose', onDispose );
  18929. }
  18930. }
  18931. /**
  18932. * Updates the given texture. Depending on the texture state, this method
  18933. * triggers the upload of texture data to the GPU memory. If the texture data are
  18934. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18935. *
  18936. * @param {Texture} texture - The texture to update.
  18937. * @param {Object} [options={}] - The options.
  18938. */
  18939. updateTexture( texture, options = {} ) {
  18940. const textureData = this.get( texture );
  18941. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18942. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18943. const backend = this.backend;
  18944. if ( isRenderTarget && textureData.initialized === true ) {
  18945. // it's an update
  18946. backend.destroySampler( texture );
  18947. backend.destroyTexture( texture );
  18948. }
  18949. //
  18950. if ( texture.isFramebufferTexture ) {
  18951. const renderTarget = this.renderer.getRenderTarget();
  18952. if ( renderTarget ) {
  18953. texture.type = renderTarget.texture.type;
  18954. } else {
  18955. texture.type = UnsignedByteType;
  18956. }
  18957. }
  18958. //
  18959. const { width, height, depth } = this.getSize( texture );
  18960. options.width = width;
  18961. options.height = height;
  18962. options.depth = depth;
  18963. options.needsMipmaps = this.needsMipmaps( texture );
  18964. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18965. //
  18966. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18967. backend.createSampler( texture );
  18968. backend.createTexture( texture, options );
  18969. textureData.generation = texture.version;
  18970. } else {
  18971. const needsCreate = textureData.initialized !== true;
  18972. if ( needsCreate ) backend.createSampler( texture );
  18973. if ( texture.version > 0 ) {
  18974. const image = texture.image;
  18975. if ( image === undefined ) {
  18976. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18977. } else if ( image.complete === false ) {
  18978. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18979. } else {
  18980. if ( texture.images ) {
  18981. const images = [];
  18982. for ( const image of texture.images ) {
  18983. images.push( image );
  18984. }
  18985. options.images = images;
  18986. } else {
  18987. options.image = image;
  18988. }
  18989. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18990. backend.createTexture( texture, options );
  18991. textureData.isDefaultTexture = false;
  18992. textureData.generation = texture.version;
  18993. }
  18994. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18995. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18996. }
  18997. } else {
  18998. // async update
  18999. backend.createDefaultTexture( texture );
  19000. textureData.isDefaultTexture = true;
  19001. textureData.generation = texture.version;
  19002. }
  19003. }
  19004. // dispose handler
  19005. if ( textureData.initialized !== true ) {
  19006. textureData.initialized = true;
  19007. textureData.generation = texture.version;
  19008. //
  19009. this.info.memory.textures ++;
  19010. // dispose
  19011. const onDispose = () => {
  19012. texture.removeEventListener( 'dispose', onDispose );
  19013. this._destroyTexture( texture );
  19014. this.info.memory.textures --;
  19015. };
  19016. texture.addEventListener( 'dispose', onDispose );
  19017. }
  19018. //
  19019. textureData.version = texture.version;
  19020. }
  19021. /**
  19022. * Computes the size of the given texture and writes the result
  19023. * into the target vector. This vector is also returned by the
  19024. * method.
  19025. *
  19026. * If no texture data are available for the compute yet, the method
  19027. * returns default size values.
  19028. *
  19029. * @param {Texture} texture - The texture to compute the size for.
  19030. * @param {Vector3} target - The target vector.
  19031. * @return {Vector3} The target vector.
  19032. */
  19033. getSize( texture, target = _size$3 ) {
  19034. let image = texture.images ? texture.images[ 0 ] : texture.image;
  19035. if ( image ) {
  19036. if ( image.image !== undefined ) image = image.image;
  19037. target.width = image.width || 1;
  19038. target.height = image.height || 1;
  19039. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  19040. } else {
  19041. target.width = target.height = target.depth = 1;
  19042. }
  19043. return target;
  19044. }
  19045. /**
  19046. * Computes the number of mipmap levels for the given texture.
  19047. *
  19048. * @param {Texture} texture - The texture.
  19049. * @param {Number} width - The texture's width.
  19050. * @param {Number} height - The texture's height.
  19051. * @return {Number} The number of mipmap levels.
  19052. */
  19053. getMipLevels( texture, width, height ) {
  19054. let mipLevelCount;
  19055. if ( texture.isCompressedTexture ) {
  19056. if ( texture.mipmaps ) {
  19057. mipLevelCount = texture.mipmaps.length;
  19058. } else {
  19059. mipLevelCount = 1;
  19060. }
  19061. } else {
  19062. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  19063. }
  19064. return mipLevelCount;
  19065. }
  19066. /**
  19067. * Returns `true` if the given texture requires mipmaps.
  19068. *
  19069. * @param {Texture} texture - The texture.
  19070. * @return {Boolean} Whether mipmaps are required or not.
  19071. */
  19072. needsMipmaps( texture ) {
  19073. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  19074. }
  19075. /**
  19076. * Returns `true` if the given texture is an environment map.
  19077. *
  19078. * @param {Texture} texture - The texture.
  19079. * @return {Boolean} Whether the given texture is an environment map or not.
  19080. */
  19081. isEnvironmentTexture( texture ) {
  19082. const mapping = texture.mapping;
  19083. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  19084. }
  19085. /**
  19086. * Frees internal resource when the given texture isn't
  19087. * required anymore.
  19088. *
  19089. * @param {Texture} texture - The texture to destroy.
  19090. */
  19091. _destroyTexture( texture ) {
  19092. this.backend.destroySampler( texture );
  19093. this.backend.destroyTexture( texture );
  19094. this.delete( texture );
  19095. }
  19096. }
  19097. /**
  19098. * A four-component version of {@link Color} which is internally
  19099. * used by the renderer to represents clear color with alpha as
  19100. * one object.
  19101. *
  19102. * @private
  19103. * @augments Color
  19104. */
  19105. class Color4 extends Color {
  19106. /**
  19107. * Constructs a new four-component color.
  19108. * You can also pass a single THREE.Color, hex or
  19109. * string argument to this constructor.
  19110. *
  19111. * @param {Number|String} [r=1] - The red value.
  19112. * @param {Number} [g=1] - The green value.
  19113. * @param {Number} [b=1] - The blue value.
  19114. * @param {Number} [a=1] - The alpha value.
  19115. */
  19116. constructor( r, g, b, a = 1 ) {
  19117. super( r, g, b );
  19118. this.a = a;
  19119. }
  19120. /**
  19121. * Overwrites the default to honor alpha.
  19122. * You can also pass a single THREE.Color, hex or
  19123. * string argument to this method.
  19124. *
  19125. * @param {Number|String} r - The red value.
  19126. * @param {Number} g - The green value.
  19127. * @param {Number} b - The blue value.
  19128. * @param {Number} [a=1] - The alpha value.
  19129. * @return {Color4} A reference to this object.
  19130. */
  19131. set( r, g, b, a = 1 ) {
  19132. this.a = a;
  19133. return super.set( r, g, b );
  19134. }
  19135. /**
  19136. * Overwrites the default to honor alpha.
  19137. *
  19138. * @param {Color4} color - The color to copy.
  19139. * @return {Color4} A reference to this object.
  19140. */
  19141. copy( color ) {
  19142. if ( color.a !== undefined ) this.a = color.a;
  19143. return super.copy( color );
  19144. }
  19145. /**
  19146. * Overwrites the default to honor alpha.
  19147. *
  19148. * @return {Color4} The cloned color.
  19149. */
  19150. clone() {
  19151. return new this.constructor( this.r, this.g, this.b, this.a );
  19152. }
  19153. }
  19154. /** @module ParameterNode **/
  19155. /**
  19156. * Special version of {@link PropertyNode} which is used for parameters.
  19157. *
  19158. * @augments PropertyNode
  19159. */
  19160. class ParameterNode extends PropertyNode {
  19161. static get type() {
  19162. return 'ParameterNode';
  19163. }
  19164. /**
  19165. * Constructs a new parameter node.
  19166. *
  19167. * @param {String} nodeType - The type of the node.
  19168. * @param {String?} [name=null] - The name of the parameter in the shader.
  19169. */
  19170. constructor( nodeType, name = null ) {
  19171. super( nodeType, name );
  19172. /**
  19173. * This flag can be used for type testing.
  19174. *
  19175. * @type {Boolean}
  19176. * @readonly
  19177. * @default true
  19178. */
  19179. this.isParameterNode = true;
  19180. }
  19181. getHash() {
  19182. return this.uuid;
  19183. }
  19184. generate() {
  19185. return this.name;
  19186. }
  19187. }
  19188. /**
  19189. * TSL function for creating a parameter node.
  19190. *
  19191. * @function
  19192. * @param {String} type - The type of the node.
  19193. * @param {String?} name - The name of the parameter in the shader.
  19194. * @returns {ParameterNode}
  19195. */
  19196. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19197. /** @module StackNode **/
  19198. /**
  19199. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19200. * They are usually needed in cases like `If`, `Else`.
  19201. *
  19202. * @augments Node
  19203. */
  19204. class StackNode extends Node {
  19205. static get type() {
  19206. return 'StackNode';
  19207. }
  19208. /**
  19209. * Constructs a new stack node.
  19210. *
  19211. * @param {StackNode?} [parent=null] - The parent stack node.
  19212. */
  19213. constructor( parent = null ) {
  19214. super();
  19215. /**
  19216. * List of nodes.
  19217. *
  19218. * @type {Array<Node>}
  19219. */
  19220. this.nodes = [];
  19221. /**
  19222. * The output node.
  19223. *
  19224. * @type {Node?}
  19225. * @default null
  19226. */
  19227. this.outputNode = null;
  19228. /**
  19229. * The parent stack node.
  19230. *
  19231. * @type {StackNode}
  19232. * @default null
  19233. */
  19234. this.parent = parent;
  19235. /**
  19236. * The current conditional node.
  19237. *
  19238. * @private
  19239. * @type {ConditionalNode}
  19240. * @default null
  19241. */
  19242. this._currentCond = null;
  19243. /**
  19244. * This flag can be used for type testing.
  19245. *
  19246. * @type {Boolean}
  19247. * @readonly
  19248. * @default true
  19249. */
  19250. this.isStackNode = true;
  19251. }
  19252. getNodeType( builder ) {
  19253. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19254. }
  19255. /**
  19256. * Adds a node to this stack.
  19257. *
  19258. * @param {Node} node - The node to add.
  19259. * @return {StackNode} A reference to this stack node.
  19260. */
  19261. add( node ) {
  19262. this.nodes.push( node );
  19263. return this;
  19264. }
  19265. /**
  19266. * Represent an `if` statement in TSL.
  19267. *
  19268. * @param {Node} boolNode - Represents the condition.
  19269. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19270. * @return {StackNode} A reference to this stack node.
  19271. */
  19272. If( boolNode, method ) {
  19273. const methodNode = new ShaderNode( method );
  19274. this._currentCond = select( boolNode, methodNode );
  19275. return this.add( this._currentCond );
  19276. }
  19277. /**
  19278. * Represent an `elseif` statement in TSL.
  19279. *
  19280. * @param {Node} boolNode - Represents the condition.
  19281. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19282. * @return {StackNode} A reference to this stack node.
  19283. */
  19284. ElseIf( boolNode, method ) {
  19285. const methodNode = new ShaderNode( method );
  19286. const ifNode = select( boolNode, methodNode );
  19287. this._currentCond.elseNode = ifNode;
  19288. this._currentCond = ifNode;
  19289. return this;
  19290. }
  19291. /**
  19292. * Represent an `else` statement in TSL.
  19293. *
  19294. * @param {Function} method - TSL code which is executed in the `else` case.
  19295. * @return {StackNode} A reference to this stack node.
  19296. */
  19297. Else( method ) {
  19298. this._currentCond.elseNode = new ShaderNode( method );
  19299. return this;
  19300. }
  19301. build( builder, ...params ) {
  19302. const previousStack = getCurrentStack();
  19303. setCurrentStack( this );
  19304. for ( const node of this.nodes ) {
  19305. node.build( builder, 'void' );
  19306. }
  19307. setCurrentStack( previousStack );
  19308. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19309. }
  19310. // Deprecated
  19311. /**
  19312. * @function
  19313. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19314. *
  19315. * @param {...any} params
  19316. * @returns {StackNode}
  19317. */
  19318. else( ...params ) { // @deprecated, r168
  19319. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19320. return this.Else( ...params );
  19321. }
  19322. /**
  19323. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19324. *
  19325. * @param {...any} params
  19326. * @returns {StackNode}
  19327. */
  19328. elseif( ...params ) { // @deprecated, r168
  19329. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19330. return this.ElseIf( ...params );
  19331. }
  19332. }
  19333. /**
  19334. * TSL function for creating a stack node.
  19335. *
  19336. * @function
  19337. * @param {StackNode?} [parent=null] - The parent stack node.
  19338. * @returns {StackNode}
  19339. */
  19340. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19341. /** @module OutputStructNode **/
  19342. /**
  19343. * This node can be used to define multiple outputs in a shader programs.
  19344. *
  19345. * @augments Node
  19346. */
  19347. class OutputStructNode extends Node {
  19348. static get type() {
  19349. return 'OutputStructNode';
  19350. }
  19351. /**
  19352. * Constructs a new output struct node. The constructor can be invoked with an
  19353. * arbitrary number of nodes representing the members.
  19354. *
  19355. * @param {...Node} members - A parameter list of nodes.
  19356. */
  19357. constructor( ...members ) {
  19358. super();
  19359. /**
  19360. * An array of nodes which defines the output.
  19361. *
  19362. * @type {Array<Node>}
  19363. */
  19364. this.members = members;
  19365. /**
  19366. * This flag can be used for type testing.
  19367. *
  19368. * @type {Boolean}
  19369. * @readonly
  19370. * @default true
  19371. */
  19372. this.isOutputStructNode = true;
  19373. }
  19374. setup( builder ) {
  19375. super.setup( builder );
  19376. const members = this.members;
  19377. const types = [];
  19378. for ( let i = 0; i < members.length; i ++ ) {
  19379. types.push( members[ i ].getNodeType( builder ) );
  19380. }
  19381. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19382. }
  19383. generate( builder, output ) {
  19384. const propertyName = builder.getOutputStructName();
  19385. const members = this.members;
  19386. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19387. for ( let i = 0; i < members.length; i ++ ) {
  19388. const snippet = members[ i ].build( builder, output );
  19389. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19390. }
  19391. return propertyName;
  19392. }
  19393. }
  19394. /**
  19395. * TSL function for creating an output struct node.
  19396. *
  19397. * @function
  19398. * @param {...Node} members - A parameter list of nodes.
  19399. * @returns {OutputStructNode}
  19400. */
  19401. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19402. /** @module MRTNode **/
  19403. /**
  19404. * Returns the MRT texture index for the given name.
  19405. *
  19406. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19407. * @param {String} name - The name of the MRT texture which index is requested.
  19408. * @return {Number} The texture index.
  19409. */
  19410. function getTextureIndex( textures, name ) {
  19411. for ( let i = 0; i < textures.length; i ++ ) {
  19412. if ( textures[ i ].name === name ) {
  19413. return i;
  19414. }
  19415. }
  19416. return -1;
  19417. }
  19418. /**
  19419. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19420. * post-processing is shown below:
  19421. * ```js
  19422. * const mrtNode = mrt( {
  19423. * output: output,
  19424. * normal: normalView
  19425. * } ) );
  19426. * ```
  19427. * The MRT output is defined as a dictionary.
  19428. *
  19429. * @augments OutputStructNode
  19430. */
  19431. class MRTNode extends OutputStructNode {
  19432. static get type() {
  19433. return 'MRTNode';
  19434. }
  19435. /**
  19436. * Constructs a new output struct node.
  19437. *
  19438. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19439. */
  19440. constructor( outputNodes ) {
  19441. super();
  19442. /**
  19443. * A dictionary representing the MRT outputs. The key
  19444. * is the name of the output, the value the node which produces
  19445. * the output result.
  19446. *
  19447. * @type {Object<String, Node>}
  19448. */
  19449. this.outputNodes = outputNodes;
  19450. /**
  19451. * This flag can be used for type testing.
  19452. *
  19453. * @type {Boolean}
  19454. * @readonly
  19455. * @default true
  19456. */
  19457. this.isMRTNode = true;
  19458. }
  19459. /**
  19460. * Returns `true` if the MRT node has an output with the given name.
  19461. *
  19462. * @param {String} name - The name of the output.
  19463. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19464. */
  19465. has( name ) {
  19466. return this.outputNodes[ name ] !== undefined;
  19467. }
  19468. /**
  19469. * Returns the output node for the given name.
  19470. *
  19471. * @param {String} name - The name of the output.
  19472. * @return {Node} The output node.
  19473. */
  19474. get( name ) {
  19475. return this.outputNodes[ name ];
  19476. }
  19477. /**
  19478. * Merges the outputs of the given MRT node with the outputs of this node.
  19479. *
  19480. * @param {MRTNode} mrtNode - The MRT to merge.
  19481. * @return {MRTNode} A new MRT node with merged outputs..
  19482. */
  19483. merge( mrtNode ) {
  19484. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19485. return mrt( outputs );
  19486. }
  19487. setup( builder ) {
  19488. const outputNodes = this.outputNodes;
  19489. const mrt = builder.renderer.getRenderTarget();
  19490. const members = [];
  19491. const textures = mrt.textures;
  19492. for ( const name in outputNodes ) {
  19493. const index = getTextureIndex( textures, name );
  19494. members[ index ] = vec4( outputNodes[ name ] );
  19495. }
  19496. this.members = members;
  19497. return super.setup( builder );
  19498. }
  19499. }
  19500. /**
  19501. * TSL function for creating a MRT node.
  19502. *
  19503. * @function
  19504. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19505. * @returns {MRTNode}
  19506. */
  19507. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19508. /** @module Hash **/
  19509. /**
  19510. * Generates a hash value in the range `[0, 1]` from the given seed.
  19511. *
  19512. * @method
  19513. * @param {Node<float>} seed - The seed.
  19514. * @return {Node<float>} The hash value.
  19515. */
  19516. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19517. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19518. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19519. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19520. const result = word.shiftRight( 22 ).bitXor( word );
  19521. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19522. } );
  19523. /** @module MathUtils **/
  19524. /**
  19525. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19526. * The corners are mapped to `0` and the center to `1`.
  19527. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19528. *
  19529. * @method
  19530. * @param {Node<float>} x - The value to remap.
  19531. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19532. * @return {Node<float>} The remapped value.
  19533. */
  19534. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19535. /**
  19536. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19537. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19538. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19539. *
  19540. * @method
  19541. * @param {Node<float>} x - The value to remap.
  19542. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19543. * @return {Node<float>} The remapped value.
  19544. */
  19545. 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 ) );
  19546. /**
  19547. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19548. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19549. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19550. *
  19551. * @method
  19552. * @param {Node<float>} x - The value to remap.
  19553. * @param {Node<float>} a - First control parameter.
  19554. * @param {Node<float>} b - Second control parameter.
  19555. * @return {Node<float>} The remapped value.
  19556. */
  19557. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19558. /**
  19559. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19560. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19561. *
  19562. * @method
  19563. * @param {Node<float>} x - The value to compute the sin for.
  19564. * @param {Node<float>} k - Controls the amount of bounces.
  19565. * @return {Node<float>} The result value.
  19566. */
  19567. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19568. // https://github.com/cabbibo/glsl-tri-noise-3d
  19569. /** @module TriNoise3D **/
  19570. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19571. return x.fract().sub( .5 ).abs();
  19572. } ).setLayout( {
  19573. name: 'tri',
  19574. type: 'float',
  19575. inputs: [
  19576. { name: 'x', type: 'float' }
  19577. ]
  19578. } );
  19579. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19580. 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. ) ) ) ) );
  19581. } ).setLayout( {
  19582. name: 'tri3',
  19583. type: 'vec3',
  19584. inputs: [
  19585. { name: 'p', type: 'vec3' }
  19586. ]
  19587. } );
  19588. /**
  19589. * Generates a noise value from the given position, speed and time parameters.
  19590. *
  19591. * @method
  19592. * @param {Node<vec3>} position - The position.
  19593. * @param {Node<float>} speed - The speed.
  19594. * @param {Node<float>} time - The time.
  19595. * @return {Node<float>} The generated noise.
  19596. */
  19597. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19598. const p = vec3( position ).toVar();
  19599. const z = float( 1.4 ).toVar();
  19600. const rz = float( 0.0 ).toVar();
  19601. const bp = vec3( p ).toVar();
  19602. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19603. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19604. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19605. bp.mulAssign( 1.8 );
  19606. z.mulAssign( 1.5 );
  19607. p.mulAssign( 1.2 );
  19608. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19609. rz.addAssign( t.div( z ) );
  19610. bp.addAssign( 0.14 );
  19611. } );
  19612. return rz;
  19613. } ).setLayout( {
  19614. name: 'triNoise3D',
  19615. type: 'float',
  19616. inputs: [
  19617. { name: 'position', type: 'vec3' },
  19618. { name: 'speed', type: 'float' },
  19619. { name: 'time', type: 'float' }
  19620. ]
  19621. } );
  19622. /** @module FunctionOverloadingNode **/
  19623. /**
  19624. * This class allows to define multiple overloaded versions
  19625. * of the same function. Depending on the parameters of the function
  19626. * call, the node picks the best-fit overloaded version.
  19627. *
  19628. * @augments Node
  19629. */
  19630. class FunctionOverloadingNode extends Node {
  19631. static get type() {
  19632. return 'FunctionOverloadingNode';
  19633. }
  19634. /**
  19635. * Constructs a new function overloading node.
  19636. *
  19637. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19638. * @param {...Node} parametersNodes - A list of parameter nodes.
  19639. */
  19640. constructor( functionNodes = [], ...parametersNodes ) {
  19641. super();
  19642. /**
  19643. * Array of `Fn` function definitions.
  19644. *
  19645. * @type {Array<Function>}
  19646. */
  19647. this.functionNodes = functionNodes;
  19648. /**
  19649. * A list of parameter nodes.
  19650. *
  19651. * @type {Array<Node>}
  19652. */
  19653. this.parametersNodes = parametersNodes;
  19654. /**
  19655. * The selected overloaded function call.
  19656. *
  19657. * @private
  19658. * @type {ShaderCallNodeInternal}
  19659. */
  19660. this._candidateFnCall = null;
  19661. /**
  19662. * This node is marked as global.
  19663. *
  19664. * @type {Boolean}
  19665. * @default true
  19666. */
  19667. this.global = true;
  19668. }
  19669. /**
  19670. * This method is overwritten since the node type is inferred from
  19671. * the function's return type.
  19672. *
  19673. * @param {NodeBuilder} builder - The current node builder.
  19674. * @return {String} The node type.
  19675. */
  19676. getNodeType() {
  19677. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19678. }
  19679. setup( builder ) {
  19680. const params = this.parametersNodes;
  19681. let candidateFnCall = this._candidateFnCall;
  19682. if ( candidateFnCall === null ) {
  19683. let candidateFn = null;
  19684. let candidateScore = -1;
  19685. for ( const functionNode of this.functionNodes ) {
  19686. const shaderNode = functionNode.shaderNode;
  19687. const layout = shaderNode.layout;
  19688. if ( layout === null ) {
  19689. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19690. }
  19691. const inputs = layout.inputs;
  19692. if ( params.length === inputs.length ) {
  19693. let score = 0;
  19694. for ( let i = 0; i < params.length; i ++ ) {
  19695. const param = params[ i ];
  19696. const input = inputs[ i ];
  19697. if ( param.getNodeType( builder ) === input.type ) {
  19698. score ++;
  19699. } else {
  19700. score = 0;
  19701. }
  19702. }
  19703. if ( score > candidateScore ) {
  19704. candidateFn = functionNode;
  19705. candidateScore = score;
  19706. }
  19707. }
  19708. }
  19709. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19710. }
  19711. return candidateFnCall;
  19712. }
  19713. }
  19714. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19715. /**
  19716. * TSL function for creating a function overloading node.
  19717. *
  19718. * @function
  19719. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19720. * @returns {FunctionOverloadingNode}
  19721. */
  19722. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19723. /** @module Timer **/
  19724. /**
  19725. * Represents the elapsed time in seconds.
  19726. *
  19727. * @type {UniformNode<float>}
  19728. */
  19729. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19730. /**
  19731. * Represents the delta time in seconds.
  19732. *
  19733. * @type {UniformNode<float>}
  19734. */
  19735. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19736. /**
  19737. * Represents the current frame ID.
  19738. *
  19739. * @type {UniformNode<uint>}
  19740. */
  19741. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19742. // Deprecated
  19743. /**
  19744. * @function
  19745. * @deprecated since r170. Use {@link time} instead.
  19746. *
  19747. * @param {Number} [timeScale=1] - The time scale.
  19748. * @returns {UniformNode<float>}
  19749. */
  19750. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19751. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19752. return time.mul( timeScale );
  19753. };
  19754. /**
  19755. * @function
  19756. * @deprecated since r170. Use {@link time} instead.
  19757. *
  19758. * @param {Number} [timeScale=1] - The time scale.
  19759. * @returns {UniformNode<float>}
  19760. */
  19761. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19762. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19763. return time.mul( timeScale );
  19764. };
  19765. /**
  19766. * @function
  19767. * @deprecated since r170. Use {@link deltaTime} instead.
  19768. *
  19769. * @param {Number} [timeScale=1] - The time scale.
  19770. * @returns {UniformNode<float>}
  19771. */
  19772. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19773. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19774. return deltaTime.mul( timeScale );
  19775. };
  19776. /** @module Oscillators **/
  19777. /**
  19778. * Generates a sine wave oscillation based on a timer.
  19779. *
  19780. * @method
  19781. * @param {Node<float>} t - The timer to generate the oscillation with.
  19782. * @return {Node<float>} The oscillation node.
  19783. */
  19784. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19785. /**
  19786. * Generates a square wave oscillation based on a timer.
  19787. *
  19788. * @method
  19789. * @param {Node<float>} t - The timer to generate the oscillation with.
  19790. * @return {Node<float>} The oscillation node.
  19791. */
  19792. const oscSquare = ( t = time ) => t.fract().round();
  19793. /**
  19794. * Generates a triangle wave oscillation based on a timer.
  19795. *
  19796. * @method
  19797. * @param {Node<float>} t - The timer to generate the oscillation with.
  19798. * @return {Node<float>} The oscillation node.
  19799. */
  19800. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19801. /**
  19802. * Generates a sawtooth wave oscillation based on a timer.
  19803. *
  19804. * @method
  19805. * @param {Node<float>} t - The timer to generate the oscillation with.
  19806. * @return {Node<float>} The oscillation node.
  19807. */
  19808. const oscSawtooth = ( t = time ) => t.fract();
  19809. /** @module UVUtils **/
  19810. /**
  19811. * Rotates the given uv coordinates around a center point
  19812. *
  19813. * @method
  19814. * @param {Node<vec2>} uv - The uv coordinates.
  19815. * @param {Node<float>} rotation - The rotation defined in radians.
  19816. * @param {Node<vec2>} center - The center of rotation
  19817. * @return {Node<vec2>} The rotated uv coordinates.
  19818. */
  19819. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19820. return rotate( uv.sub( center ), rotation ).add( center );
  19821. } );
  19822. /**
  19823. * Applies a spherical warping effect to the given uv coordinates.
  19824. *
  19825. * @method
  19826. * @param {Node<vec2>} uv - The uv coordinates.
  19827. * @param {Node<float>} strength - The strength of the effect.
  19828. * @param {Node<vec2>} center - The center point
  19829. * @return {Node<vec2>} The updated uv coordinates.
  19830. */
  19831. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19832. const delta = uv.sub( center );
  19833. const delta2 = delta.dot( delta );
  19834. const delta4 = delta2.mul( delta2 );
  19835. const deltaOffset = delta4.mul( strength );
  19836. return uv.add( delta.mul( deltaOffset ) );
  19837. } );
  19838. /** @module SpriteUtils **/
  19839. /**
  19840. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19841. * oriented always towards the camera.
  19842. *
  19843. * ```js
  19844. * material.vertexNode = billboarding();
  19845. * ```
  19846. *
  19847. * @method
  19848. * @param {Object} config - The configuration object.
  19849. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19850. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19851. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19852. * @return {Node<vec3>} The updated vertex position in clip space.
  19853. */
  19854. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19855. let worldMatrix;
  19856. if ( position !== null ) {
  19857. worldMatrix = modelWorldMatrix.toVar();
  19858. worldMatrix[ 3 ][ 0 ] = position.x;
  19859. worldMatrix[ 3 ][ 1 ] = position.y;
  19860. worldMatrix[ 3 ][ 2 ] = position.z;
  19861. } else {
  19862. worldMatrix = modelWorldMatrix;
  19863. }
  19864. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19865. if ( defined( horizontal ) ) {
  19866. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19867. modelViewMatrix[ 0 ][ 1 ] = 0;
  19868. modelViewMatrix[ 0 ][ 2 ] = 0;
  19869. }
  19870. if ( defined( vertical ) ) {
  19871. modelViewMatrix[ 1 ][ 0 ] = 0;
  19872. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19873. modelViewMatrix[ 1 ][ 2 ] = 0;
  19874. }
  19875. modelViewMatrix[ 2 ][ 0 ] = 0;
  19876. modelViewMatrix[ 2 ][ 1 ] = 0;
  19877. modelViewMatrix[ 2 ][ 2 ] = 1;
  19878. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19879. } );
  19880. /** @module ViewportUtils **/
  19881. /**
  19882. * A special version of a screen uv function that involves a depth comparison
  19883. * when computing the final uvs. The function mitigates visual errors when
  19884. * using viewport texture nodes for refraction purposes. Without this function
  19885. * objects in front of a refractive surface might appear on the refractive surface
  19886. * which is incorrect.
  19887. *
  19888. * @method
  19889. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19890. * @return {Node<vec2>} The update uv coordinates.
  19891. */
  19892. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19893. const depth = linearDepth();
  19894. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19895. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19896. return finalUV;
  19897. } );
  19898. /** @module SpriteSheetUVNode **/
  19899. /**
  19900. * Can be used to compute texture coordinates for animated sprite sheets.
  19901. *
  19902. * ```js
  19903. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19904. *
  19905. * material.colorNode = texture( spriteSheet, uvNode );
  19906. * ```
  19907. *
  19908. * @augments Node
  19909. */
  19910. class SpriteSheetUVNode extends Node {
  19911. static get type() {
  19912. return 'SpriteSheetUVNode';
  19913. }
  19914. /**
  19915. * Constructs a new sprite sheet uv node.
  19916. *
  19917. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19918. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19919. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19920. */
  19921. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19922. super( 'vec2' );
  19923. /**
  19924. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19925. *
  19926. * @type {Node<vec2>}
  19927. */
  19928. this.countNode = countNode;
  19929. /**
  19930. * The uv node.
  19931. *
  19932. * @type {Node<vec2>}
  19933. */
  19934. this.uvNode = uvNode;
  19935. /**
  19936. * The node that defines the current frame/sprite.
  19937. *
  19938. * @type {Node<float>}
  19939. */
  19940. this.frameNode = frameNode;
  19941. }
  19942. setup() {
  19943. const { frameNode, uvNode, countNode } = this;
  19944. const { width, height } = countNode;
  19945. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19946. const column = frameNum.mod( width );
  19947. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19948. const scale = countNode.reciprocal();
  19949. const uvFrameOffset = vec2( column, row );
  19950. return uvNode.add( uvFrameOffset ).mul( scale );
  19951. }
  19952. }
  19953. /**
  19954. * TSL function for creating a sprite sheet uv node.
  19955. *
  19956. * @function
  19957. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19958. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19959. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19960. * @returns {SpriteSheetUVNode}
  19961. */
  19962. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19963. /** @module TriplanarTexturesNode **/
  19964. /**
  19965. * Can be used for triplanar texture mapping.
  19966. *
  19967. * ```js
  19968. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19969. * ```
  19970. *
  19971. * @augments Node
  19972. */
  19973. class TriplanarTexturesNode extends Node {
  19974. static get type() {
  19975. return 'TriplanarTexturesNode';
  19976. }
  19977. /**
  19978. * Constructs a new triplanar textures node.
  19979. *
  19980. * @param {Node} textureXNode - First texture node.
  19981. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19982. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19983. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19984. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19985. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19986. */
  19987. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19988. super( 'vec4' );
  19989. /**
  19990. * First texture node.
  19991. *
  19992. * @type {Node}
  19993. */
  19994. this.textureXNode = textureXNode;
  19995. /**
  19996. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19997. *
  19998. * @type {Node}
  19999. * @default null
  20000. */
  20001. this.textureYNode = textureYNode;
  20002. /**
  20003. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20004. *
  20005. * @type {Node}
  20006. * @default null
  20007. */
  20008. this.textureZNode = textureZNode;
  20009. /**
  20010. * The scale node.
  20011. *
  20012. * @type {Node<float>}
  20013. * @default float(1)
  20014. */
  20015. this.scaleNode = scaleNode;
  20016. /**
  20017. * Vertex positions in local space.
  20018. *
  20019. * @type {Node<vec3>}
  20020. * @default positionLocal
  20021. */
  20022. this.positionNode = positionNode;
  20023. /**
  20024. * Normals in local space.
  20025. *
  20026. * @type {Node<vec3>}
  20027. * @default normalLocal
  20028. */
  20029. this.normalNode = normalNode;
  20030. }
  20031. setup() {
  20032. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  20033. // Ref: https://github.com/keijiro/StandardTriplanar
  20034. // Blending factor of triplanar mapping
  20035. let bf = normalNode.abs().normalize();
  20036. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  20037. // Triplanar mapping
  20038. const tx = positionNode.yz.mul( scaleNode );
  20039. const ty = positionNode.zx.mul( scaleNode );
  20040. const tz = positionNode.xy.mul( scaleNode );
  20041. // Base color
  20042. const textureX = textureXNode.value;
  20043. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  20044. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  20045. const cx = texture( textureX, tx ).mul( bf.x );
  20046. const cy = texture( textureY, ty ).mul( bf.y );
  20047. const cz = texture( textureZ, tz ).mul( bf.z );
  20048. return add( cx, cy, cz );
  20049. }
  20050. }
  20051. /**
  20052. * TSL function for creating a triplanar textures node.
  20053. *
  20054. * @function
  20055. * @param {Node} textureXNode - First texture node.
  20056. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20057. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20058. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  20059. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  20060. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  20061. * @returns {TriplanarTexturesNode}
  20062. */
  20063. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  20064. /**
  20065. * TSL function for creating a triplanar textures node.
  20066. *
  20067. * @function
  20068. * @param {Node} textureXNode - First texture node.
  20069. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20070. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20071. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  20072. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  20073. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  20074. * @returns {TriplanarTexturesNode}
  20075. */
  20076. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  20077. /** @module ReflectorNode **/
  20078. const _reflectorPlane = new Plane();
  20079. const _normal = new Vector3();
  20080. const _reflectorWorldPosition = new Vector3();
  20081. const _cameraWorldPosition = new Vector3();
  20082. const _rotationMatrix = new Matrix4();
  20083. const _lookAtPosition = new Vector3( 0, 0, -1 );
  20084. const clipPlane = new Vector4();
  20085. const _view = new Vector3();
  20086. const _target = new Vector3();
  20087. const _q = new Vector4();
  20088. const _size$2 = new Vector2();
  20089. const _defaultRT = new RenderTarget();
  20090. const _defaultUV = screenUV.flipX();
  20091. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  20092. let _inReflector = false;
  20093. /**
  20094. * This node can be used to implement mirror-like flat reflective surfaces.
  20095. *
  20096. * ```js
  20097. * const groundReflector = reflector();
  20098. * material.colorNode = groundReflector;
  20099. *
  20100. * const plane = new Mesh( geometry, material );
  20101. * plane.add( groundReflector.target );
  20102. * ```
  20103. *
  20104. * @augments module:TextureNode~TextureNode
  20105. */
  20106. class ReflectorNode extends TextureNode {
  20107. static get type() {
  20108. return 'ReflectorNode';
  20109. }
  20110. /**
  20111. * Constructs a new reflector node.
  20112. *
  20113. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20114. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20115. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20116. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20117. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20118. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20119. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20120. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20121. */
  20122. constructor( parameters = {} ) {
  20123. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20124. /**
  20125. * A reference to the internal reflector base node which holds the actual implementation.
  20126. *
  20127. * @private
  20128. * @type {ReflectorBaseNode?}
  20129. * @default null
  20130. */
  20131. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20132. /**
  20133. * A reference to the internal depth node.
  20134. *
  20135. * @private
  20136. * @type {Node?}
  20137. * @default null
  20138. */
  20139. this._depthNode = null;
  20140. this.setUpdateMatrix( false );
  20141. }
  20142. /**
  20143. * A reference to the internal reflector node.
  20144. *
  20145. * @type {ReflectorBaseNode}
  20146. */
  20147. get reflector() {
  20148. return this._reflectorBaseNode;
  20149. }
  20150. /**
  20151. * A reference to 3D object the reflector is linked to.
  20152. *
  20153. * @type {Object3D}
  20154. */
  20155. get target() {
  20156. return this._reflectorBaseNode.target;
  20157. }
  20158. /**
  20159. * Returns a node representing the mirror's depth. That can be used
  20160. * to implement more advanced reflection effects like distance attenuation.
  20161. *
  20162. * @return {Node} The depth node.
  20163. */
  20164. getDepthNode() {
  20165. if ( this._depthNode === null ) {
  20166. if ( this._reflectorBaseNode.depth !== true ) {
  20167. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20168. }
  20169. this._depthNode = nodeObject( new ReflectorNode( {
  20170. defaultTexture: _defaultRT.depthTexture,
  20171. reflector: this._reflectorBaseNode
  20172. } ) );
  20173. }
  20174. return this._depthNode;
  20175. }
  20176. setup( builder ) {
  20177. // ignore if used in post-processing
  20178. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20179. return super.setup( builder );
  20180. }
  20181. clone() {
  20182. const texture = new this.constructor( this.reflectorNode );
  20183. texture._reflectorBaseNode = this._reflectorBaseNode;
  20184. return texture;
  20185. }
  20186. }
  20187. /**
  20188. * Holds the actual implementation of the reflector.
  20189. *
  20190. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20191. * in `ReflectorNode`, see #29619.
  20192. *
  20193. * @private
  20194. * @augments Node
  20195. */
  20196. class ReflectorBaseNode extends Node {
  20197. static get type() {
  20198. return 'ReflectorBaseNode';
  20199. }
  20200. /**
  20201. * Constructs a new reflector base node.
  20202. *
  20203. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20204. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20205. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20206. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20207. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20208. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20209. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20210. */
  20211. constructor( textureNode, parameters = {} ) {
  20212. super();
  20213. const {
  20214. target = new Object3D(),
  20215. resolution = 1,
  20216. generateMipmaps = false,
  20217. bounces = true,
  20218. depth = false
  20219. } = parameters;
  20220. /**
  20221. * Represents the rendered reflections as a texture node.
  20222. *
  20223. * @type {TextureNode}
  20224. */
  20225. this.textureNode = textureNode;
  20226. /**
  20227. * The 3D object the reflector is linked to.
  20228. *
  20229. * @type {Object3D}
  20230. * @default {new Object3D()}
  20231. */
  20232. this.target = target;
  20233. /**
  20234. * The resolution scale.
  20235. *
  20236. * @type {Number}
  20237. * @default {1}
  20238. */
  20239. this.resolution = resolution;
  20240. /**
  20241. * Whether mipmaps should be generated or not.
  20242. *
  20243. * @type {Boolean}
  20244. * @default {false}
  20245. */
  20246. this.generateMipmaps = generateMipmaps;
  20247. /**
  20248. * Whether reflectors can render other reflector nodes or not.
  20249. *
  20250. * @type {Boolean}
  20251. * @default {true}
  20252. */
  20253. this.bounces = bounces;
  20254. /**
  20255. * Whether depth data should be generated or not.
  20256. *
  20257. * @type {Boolean}
  20258. * @default {false}
  20259. */
  20260. this.depth = depth;
  20261. /**
  20262. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20263. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20264. *
  20265. * @type {String}
  20266. * @default 'render'
  20267. */
  20268. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20269. /**
  20270. * Weak map for managing virtual cameras.
  20271. *
  20272. * @type {WeakMap<Camera, Camera>}
  20273. */
  20274. this.virtualCameras = new WeakMap();
  20275. /**
  20276. * Weak map for managing render targets.
  20277. *
  20278. * @type {WeakMap<Camera, RenderTarget>}
  20279. */
  20280. this.renderTargets = new WeakMap();
  20281. }
  20282. /**
  20283. * Updates the resolution of the internal render target.
  20284. *
  20285. * @private
  20286. * @param {RenderTarget} renderTarget - The render target to resize.
  20287. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20288. */
  20289. _updateResolution( renderTarget, renderer ) {
  20290. const resolution = this.resolution;
  20291. renderer.getDrawingBufferSize( _size$2 );
  20292. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20293. }
  20294. setup( builder ) {
  20295. this._updateResolution( _defaultRT, builder.renderer );
  20296. return super.setup( builder );
  20297. }
  20298. /**
  20299. * Returns a virtual camera for the given camera. The virtual camera is used to
  20300. * render the scene from the reflector's view so correct reflections can be produced.
  20301. *
  20302. * @param {Camera} camera - The scene's camera.
  20303. * @return {Camera} The corresponding virtual camera.
  20304. */
  20305. getVirtualCamera( camera ) {
  20306. let virtualCamera = this.virtualCameras.get( camera );
  20307. if ( virtualCamera === undefined ) {
  20308. virtualCamera = camera.clone();
  20309. this.virtualCameras.set( camera, virtualCamera );
  20310. }
  20311. return virtualCamera;
  20312. }
  20313. /**
  20314. * Returns a render target for the given camera. The reflections are rendered
  20315. * into this render target.
  20316. *
  20317. * @param {Camera} camera - The scene's camera.
  20318. * @return {RenderTarget} The render target.
  20319. */
  20320. getRenderTarget( camera ) {
  20321. let renderTarget = this.renderTargets.get( camera );
  20322. if ( renderTarget === undefined ) {
  20323. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20324. if ( this.generateMipmaps === true ) {
  20325. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20326. renderTarget.texture.generateMipmaps = true;
  20327. }
  20328. if ( this.depth === true ) {
  20329. renderTarget.depthTexture = new DepthTexture();
  20330. }
  20331. this.renderTargets.set( camera, renderTarget );
  20332. }
  20333. return renderTarget;
  20334. }
  20335. updateBefore( frame ) {
  20336. if ( this.bounces === false && _inReflector ) return false;
  20337. _inReflector = true;
  20338. const { scene, camera, renderer, material } = frame;
  20339. const { target } = this;
  20340. const virtualCamera = this.getVirtualCamera( camera );
  20341. const renderTarget = this.getRenderTarget( virtualCamera );
  20342. renderer.getDrawingBufferSize( _size$2 );
  20343. this._updateResolution( renderTarget, renderer );
  20344. //
  20345. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20346. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20347. _rotationMatrix.extractRotation( target.matrixWorld );
  20348. _normal.set( 0, 0, 1 );
  20349. _normal.applyMatrix4( _rotationMatrix );
  20350. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20351. // Avoid rendering when reflector is facing away
  20352. if ( _view.dot( _normal ) > 0 ) return;
  20353. _view.reflect( _normal ).negate();
  20354. _view.add( _reflectorWorldPosition );
  20355. _rotationMatrix.extractRotation( camera.matrixWorld );
  20356. _lookAtPosition.set( 0, 0, -1 );
  20357. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20358. _lookAtPosition.add( _cameraWorldPosition );
  20359. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20360. _target.reflect( _normal ).negate();
  20361. _target.add( _reflectorWorldPosition );
  20362. //
  20363. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20364. virtualCamera.position.copy( _view );
  20365. virtualCamera.up.set( 0, 1, 0 );
  20366. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20367. virtualCamera.up.reflect( _normal );
  20368. virtualCamera.lookAt( _target );
  20369. virtualCamera.near = camera.near;
  20370. virtualCamera.far = camera.far;
  20371. virtualCamera.updateMatrixWorld();
  20372. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20373. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20374. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20375. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20376. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20377. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20378. const projectionMatrix = virtualCamera.projectionMatrix;
  20379. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20380. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20381. _q.z = -1;
  20382. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20383. // Calculate the scaled plane vector
  20384. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20385. const clipBias = 0;
  20386. // Replacing the third row of the projection matrix
  20387. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20388. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20389. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20390. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20391. //
  20392. this.textureNode.value = renderTarget.texture;
  20393. if ( this.depth === true ) {
  20394. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20395. }
  20396. material.visible = false;
  20397. const currentRenderTarget = renderer.getRenderTarget();
  20398. const currentMRT = renderer.getMRT();
  20399. const currentAutoClear = renderer.autoClear;
  20400. renderer.setMRT( null );
  20401. renderer.setRenderTarget( renderTarget );
  20402. renderer.autoClear = true;
  20403. renderer.render( scene, virtualCamera );
  20404. renderer.setMRT( currentMRT );
  20405. renderer.setRenderTarget( currentRenderTarget );
  20406. renderer.autoClear = currentAutoClear;
  20407. material.visible = true;
  20408. _inReflector = false;
  20409. }
  20410. }
  20411. /**
  20412. * TSL function for creating a reflector node.
  20413. *
  20414. * @function
  20415. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20416. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20417. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20418. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20419. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20420. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20421. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20422. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20423. * @returns {ReflectorNode}
  20424. */
  20425. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20426. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  20427. /**
  20428. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20429. *
  20430. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20431. *
  20432. * @private
  20433. * @augments BufferGeometry
  20434. */
  20435. class QuadGeometry extends BufferGeometry {
  20436. /**
  20437. * Constructs a new quad geometry.
  20438. *
  20439. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20440. */
  20441. constructor( flipY = false ) {
  20442. super();
  20443. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20444. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  20445. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20446. }
  20447. }
  20448. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20449. /**
  20450. * This module is a helper for passes which need to render a full
  20451. * screen effect which is quite common in context of post processing.
  20452. *
  20453. * The intended usage is to reuse a single quad mesh for rendering
  20454. * subsequent passes by just reassigning the `material` reference.
  20455. *
  20456. * @augments Mesh
  20457. */
  20458. class QuadMesh extends Mesh {
  20459. /**
  20460. * Constructs a new quad mesh.
  20461. *
  20462. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20463. */
  20464. constructor( material = null ) {
  20465. super( _geometry, material );
  20466. /**
  20467. * The camera to render the quad mesh with.
  20468. *
  20469. * @type {OrthographicCamera}
  20470. * @readonly
  20471. */
  20472. this.camera = _camera;
  20473. /**
  20474. * This flag can be used for type testing.
  20475. *
  20476. * @type {Boolean}
  20477. * @readonly
  20478. * @default true
  20479. */
  20480. this.isQuadMesh = true;
  20481. }
  20482. /**
  20483. * Async version of `render()`.
  20484. *
  20485. * @async
  20486. * @param {Renderer} renderer - The renderer.
  20487. * @return {Promise} A Promise that resolves when the render has been finished.
  20488. */
  20489. async renderAsync( renderer ) {
  20490. return renderer.renderAsync( this, _camera );
  20491. }
  20492. /**
  20493. * Renders the quad mesh
  20494. *
  20495. * @param {Renderer} renderer - The renderer.
  20496. */
  20497. render( renderer ) {
  20498. renderer.render( this, _camera );
  20499. }
  20500. }
  20501. /** @module RTTNode **/
  20502. const _size$1 = /*@__PURE__*/ new Vector2();
  20503. /**
  20504. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20505. * This module is especially relevant in context of post processing where certain nodes require
  20506. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20507. * on this module, the node system can automatically ensure texture input if required.
  20508. *
  20509. * @augments module:TextureNode~TextureNode
  20510. */
  20511. class RTTNode extends TextureNode {
  20512. static get type() {
  20513. return 'RTTNode';
  20514. }
  20515. /**
  20516. * Constructs a new RTT node.
  20517. *
  20518. * @param {Node} node - The node to render a texture with.
  20519. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20520. * @param {Number?} [height=null] - The height of the internal render target.
  20521. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20522. */
  20523. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20524. const renderTarget = new RenderTarget( width, height, options );
  20525. super( renderTarget.texture, uv() );
  20526. /**
  20527. * The node to render a texture with.
  20528. *
  20529. * @type {Node}
  20530. */
  20531. this.node = node;
  20532. /**
  20533. * The width of the internal render target.
  20534. * If not width is applied, the render target is automatically resized.
  20535. *
  20536. * @type {Number?}
  20537. * @default null
  20538. */
  20539. this.width = width;
  20540. /**
  20541. * The height of the internal render target.
  20542. *
  20543. * @type {Number?}
  20544. * @default null
  20545. */
  20546. this.height = height;
  20547. /**
  20548. * The pixel ratio
  20549. *
  20550. * @type {Number}
  20551. * @default 1
  20552. */
  20553. this.pixelRatio = 1;
  20554. /**
  20555. * The render target
  20556. *
  20557. * @type {RenderTarget}
  20558. */
  20559. this.renderTarget = renderTarget;
  20560. /**
  20561. * Whether the texture requires an update or not.
  20562. *
  20563. * @type {Boolean}
  20564. * @default true
  20565. */
  20566. this.textureNeedsUpdate = true;
  20567. /**
  20568. * Whether the texture should automatically be updated or not.
  20569. *
  20570. * @type {Boolean}
  20571. * @default true
  20572. */
  20573. this.autoUpdate = true;
  20574. /**
  20575. * The node which is used with the quad mesh for RTT.
  20576. *
  20577. * @private
  20578. * @type {Node}
  20579. * @default null
  20580. */
  20581. this._rttNode = null;
  20582. /**
  20583. * The internal quad mesh for RTT.
  20584. *
  20585. * @private
  20586. * @type {QuadMesh}
  20587. */
  20588. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20589. /**
  20590. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20591. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20592. *
  20593. * @type {String}
  20594. * @default 'render'
  20595. */
  20596. this.updateBeforeType = NodeUpdateType.RENDER;
  20597. }
  20598. /**
  20599. * Whether the internal render target should automatically be resized or not.
  20600. *
  20601. * @type {Boolean}
  20602. * @readonly
  20603. * @default true
  20604. */
  20605. get autoSize() {
  20606. return this.width === null;
  20607. }
  20608. setup( builder ) {
  20609. this._rttNode = this.node.context( builder.getSharedContext() );
  20610. this._quadMesh.material.name = 'RTT';
  20611. this._quadMesh.material.needsUpdate = true;
  20612. return super.setup( builder );
  20613. }
  20614. /**
  20615. * Sets the size of the internal render target
  20616. *
  20617. * @param {Number} width - The width to set.
  20618. * @param {Number} height - The width to set.
  20619. */
  20620. setSize( width, height ) {
  20621. this.width = width;
  20622. this.height = height;
  20623. const effectiveWidth = width * this.pixelRatio;
  20624. const effectiveHeight = height * this.pixelRatio;
  20625. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20626. this.textureNeedsUpdate = true;
  20627. }
  20628. /**
  20629. * Sets the pixel ratio. This will also resize the render target.
  20630. *
  20631. * @param {Number} pixelRatio - The pixel ratio to set.
  20632. */
  20633. setPixelRatio( pixelRatio ) {
  20634. this.pixelRatio = pixelRatio;
  20635. this.setSize( this.width, this.height );
  20636. }
  20637. updateBefore( { renderer } ) {
  20638. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20639. this.textureNeedsUpdate = false;
  20640. //
  20641. if ( this.autoSize === true ) {
  20642. this.pixelRatio = renderer.getPixelRatio();
  20643. const size = renderer.getSize( _size$1 );
  20644. this.setSize( size.width, size.height );
  20645. }
  20646. //
  20647. this._quadMesh.material.fragmentNode = this._rttNode;
  20648. //
  20649. const currentRenderTarget = renderer.getRenderTarget();
  20650. renderer.setRenderTarget( this.renderTarget );
  20651. this._quadMesh.render( renderer );
  20652. renderer.setRenderTarget( currentRenderTarget );
  20653. }
  20654. clone() {
  20655. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20656. newNode.sampler = this.sampler;
  20657. newNode.referenceNode = this;
  20658. return newNode;
  20659. }
  20660. }
  20661. /**
  20662. * TSL function for creating a RTT node.
  20663. *
  20664. * @function
  20665. * @param {Node} node - The node to render a texture with.
  20666. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20667. * @param {Number?} [height=null] - The height of the internal render target.
  20668. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20669. * @returns {RTTNode}
  20670. */
  20671. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20672. /**
  20673. * TSL function for converting nodes to textures nodes.
  20674. *
  20675. * @function
  20676. * @param {Node} node - The node to render a texture with.
  20677. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20678. * @param {Number?} [height=null] - The height of the internal render target.
  20679. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20680. * @returns {RTTNode}
  20681. */
  20682. const convertToTexture = ( node, ...params ) => {
  20683. if ( node.isTextureNode ) return node;
  20684. if ( node.isPassNode ) return node.getTextureNode();
  20685. return rtt( node, ...params );
  20686. };
  20687. /** @module PostProcessingUtils **/
  20688. /**
  20689. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20690. * depth value and the camera's inverse projection matrix.
  20691. *
  20692. * @method
  20693. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20694. * @param {Node<float>} depth - The fragment's depth value.
  20695. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20696. * @return {Node<vec3>} The fragments position in view space.
  20697. */
  20698. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20699. let clipSpacePosition;
  20700. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20701. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20702. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20703. } else {
  20704. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20705. }
  20706. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20707. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20708. } );
  20709. /**
  20710. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20711. * and the camera's projection matrix
  20712. *
  20713. * @method
  20714. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20715. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20716. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20717. */
  20718. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20719. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20720. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20721. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20722. } );
  20723. /**
  20724. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20725. * target is available or if flat surface normals are required.
  20726. *
  20727. * @method
  20728. * @param {Node<vec2>} uv - The texture coordinate.
  20729. * @param {DepthTexture} depthTexture - The depth texture.
  20730. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20731. * @return {Node<vec3>} The computed normal vector.
  20732. */
  20733. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20734. const size = textureSize( textureLoad( depthTexture ) );
  20735. const p = ivec2( uv.mul( size ) ).toVar();
  20736. const c0 = textureLoad( depthTexture, p ).toVar();
  20737. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20738. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20739. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20740. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20741. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20742. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20743. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20744. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20745. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20746. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20747. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20748. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20749. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20750. 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 ) ) );
  20751. 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 ) ) );
  20752. return normalize( cross( dpdx, dpdy ) );
  20753. } );
  20754. /**
  20755. * This special type of instanced buffer attribute is intended for compute shaders.
  20756. * In earlier three.js versions it was only possible to update attribute data
  20757. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20758. * new material system and renderer it is now possible to use compute shaders
  20759. * to compute the data for an attribute more efficiently on the GPU.
  20760. *
  20761. * The idea is to create an instance of this class and provide it as an input
  20762. * to {@link module:StorageBufferNode}.
  20763. *
  20764. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20765. *
  20766. * @augments InstancedBufferAttribute
  20767. */
  20768. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20769. /**
  20770. * Constructs a new storage instanced buffer attribute.
  20771. *
  20772. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20773. * The subsequent parameters are then obsolete.
  20774. * @param {Number} itemSize - The item size.
  20775. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20776. */
  20777. constructor( count, itemSize, typeClass = Float32Array ) {
  20778. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20779. super( array, itemSize );
  20780. /**
  20781. * This flag can be used for type testing.
  20782. *
  20783. * @type {Boolean}
  20784. * @readonly
  20785. * @default true
  20786. */
  20787. this.isStorageInstancedBufferAttribute = true;
  20788. }
  20789. }
  20790. /**
  20791. * This special type of buffer attribute is intended for compute shaders.
  20792. * In earlier three.js versions it was only possible to update attribute data
  20793. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20794. * new material system and renderer it is now possible to use compute shaders
  20795. * to compute the data for an attribute more efficiently on the GPU.
  20796. *
  20797. * The idea is to create an instance of this class and provide it as an input
  20798. * to {@link module:StorageBufferNode}.
  20799. *
  20800. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20801. *
  20802. * @augments BufferAttribute
  20803. */
  20804. class StorageBufferAttribute extends BufferAttribute {
  20805. /**
  20806. * Constructs a new storage buffer attribute.
  20807. *
  20808. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20809. * The subsequent parameters are then obsolete.
  20810. * @param {Number} itemSize - The item size.
  20811. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20812. */
  20813. constructor( count, itemSize, typeClass = Float32Array ) {
  20814. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20815. super( array, itemSize );
  20816. /**
  20817. * This flag can be used for type testing.
  20818. *
  20819. * @type {Boolean}
  20820. * @readonly
  20821. * @default true
  20822. */
  20823. this.isStorageBufferAttribute = true;
  20824. }
  20825. }
  20826. /** @module StorageArrayElementNode **/
  20827. /**
  20828. * This class enables element access on instances of {@link StorageBufferNode}.
  20829. * In most cases, it is indirectly used when accessing elements with the
  20830. * {@link StorageBufferNode#element} method.
  20831. *
  20832. * ```js
  20833. * const position = positionStorage.element( instanceIndex );
  20834. * ```
  20835. *
  20836. * @augments ArrayElementNode
  20837. */
  20838. class StorageArrayElementNode extends ArrayElementNode {
  20839. static get type() {
  20840. return 'StorageArrayElementNode';
  20841. }
  20842. /**
  20843. * Constructs storage buffer element node.
  20844. *
  20845. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20846. * @param {Node} indexNode - The index node that defines the element access.
  20847. */
  20848. constructor( storageBufferNode, indexNode ) {
  20849. super( storageBufferNode, indexNode );
  20850. /**
  20851. * This flag can be used for type testing.
  20852. *
  20853. * @type {Boolean}
  20854. * @readonly
  20855. * @default true
  20856. */
  20857. this.isStorageArrayElementNode = true;
  20858. }
  20859. /**
  20860. * The storage buffer node.
  20861. *
  20862. * @param {Node} value
  20863. * @type {StorageBufferNode}
  20864. */
  20865. set storageBufferNode( value ) {
  20866. this.node = value;
  20867. }
  20868. get storageBufferNode() {
  20869. return this.node;
  20870. }
  20871. setup( builder ) {
  20872. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20873. if ( this.node.isPBO === true ) {
  20874. builder.setupPBO( this.node );
  20875. }
  20876. }
  20877. return super.setup( builder );
  20878. }
  20879. generate( builder, output ) {
  20880. let snippet;
  20881. const isAssignContext = builder.context.assign;
  20882. //
  20883. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20884. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20885. snippet = builder.generatePBO( this );
  20886. } else {
  20887. snippet = this.node.build( builder );
  20888. }
  20889. } else {
  20890. snippet = super.generate( builder );
  20891. }
  20892. if ( isAssignContext !== true ) {
  20893. const type = this.getNodeType( builder );
  20894. snippet = builder.format( snippet, type, output );
  20895. }
  20896. return snippet;
  20897. }
  20898. }
  20899. /**
  20900. * TSL function for creating a storage element node.
  20901. *
  20902. * @function
  20903. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20904. * @param {Node} indexNode - The index node that defines the element access.
  20905. * @returns {StorageArrayElementNode}
  20906. */
  20907. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20908. /** @module StorageBufferNode **/
  20909. /**
  20910. * This node is used in context of compute shaders and allows to define a
  20911. * storage buffer for data. A typical workflow is to create instances of
  20912. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20913. * setup up a compute shader that writes into the buffers and then convert
  20914. * the storage buffers to attribute nodes for rendering.
  20915. *
  20916. * ```js
  20917. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20918. *
  20919. * const computeInit = Fn( () => { // the compute shader
  20920. *
  20921. * const position = positionBuffer.element( instanceIndex );
  20922. *
  20923. * // compute position data
  20924. *
  20925. * position.x = 1;
  20926. * position.y = 1;
  20927. * position.z = 1;
  20928. *
  20929. * } )().compute( particleCount );
  20930. *
  20931. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20932. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20933. *
  20934. * renderer.computeAsync( computeInit );
  20935. *
  20936. * ```
  20937. *
  20938. * @augments BufferNode
  20939. */
  20940. class StorageBufferNode extends BufferNode {
  20941. static get type() {
  20942. return 'StorageBufferNode';
  20943. }
  20944. /**
  20945. * Constructs a new storage buffer node.
  20946. *
  20947. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20948. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20949. * @param {Number} [bufferCount=0] - The buffer count.
  20950. */
  20951. constructor( value, bufferType = null, bufferCount = 0 ) {
  20952. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20953. bufferType = getTypeFromLength( value.itemSize );
  20954. bufferCount = value.count;
  20955. }
  20956. super( value, bufferType, bufferCount );
  20957. /**
  20958. * This flag can be used for type testing.
  20959. *
  20960. * @type {Boolean}
  20961. * @readonly
  20962. * @default true
  20963. */
  20964. this.isStorageBufferNode = true;
  20965. /**
  20966. * The access type of the texture node.
  20967. *
  20968. * @type {String}
  20969. * @default 'readWrite'
  20970. */
  20971. this.access = NodeAccess.READ_WRITE;
  20972. /**
  20973. * Whether the node is atomic or not.
  20974. *
  20975. * @type {Boolean}
  20976. * @default false
  20977. */
  20978. this.isAtomic = false;
  20979. /**
  20980. * Whether the node represents a PBO or not.
  20981. * Only relevant for WebGL.
  20982. *
  20983. * @type {Boolean}
  20984. * @default false
  20985. */
  20986. this.isPBO = false;
  20987. /**
  20988. * A reference to the internal buffer attribute node.
  20989. *
  20990. * @type {BufferAttributeNode?}
  20991. * @default null
  20992. */
  20993. this._attribute = null;
  20994. /**
  20995. * A reference to the internal varying node.
  20996. *
  20997. * @type {VaryingNode?}
  20998. * @default null
  20999. */
  21000. this._varying = null;
  21001. /**
  21002. * `StorageBufferNode` sets this property to `true` by default.
  21003. *
  21004. * @type {Boolean}
  21005. * @default true
  21006. */
  21007. this.global = true;
  21008. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  21009. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  21010. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  21011. else value.isStorageBufferAttribute = true;
  21012. }
  21013. }
  21014. /**
  21015. * This method is overwritten since the buffer data might be shared
  21016. * and thus the hash should be shared as well.
  21017. *
  21018. * @param {NodeBuilder} builder - The current node builder.
  21019. * @return {String} The hash.
  21020. */
  21021. getHash( builder ) {
  21022. if ( this.bufferCount === 0 ) {
  21023. let bufferData = builder.globalCache.getData( this.value );
  21024. if ( bufferData === undefined ) {
  21025. bufferData = {
  21026. node: this
  21027. };
  21028. builder.globalCache.setData( this.value, bufferData );
  21029. }
  21030. return bufferData.node.uuid;
  21031. }
  21032. return this.uuid;
  21033. }
  21034. /**
  21035. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  21036. *
  21037. * @param {NodeBuilder} builder - The current node builder.
  21038. * @return {String} The input type.
  21039. */
  21040. getInputType( /*builder*/ ) {
  21041. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  21042. }
  21043. /**
  21044. * Enables element access with the given index node.
  21045. *
  21046. * @param {IndexNode} indexNode - The index node.
  21047. * @return {StorageArrayElementNode} A node representing the element access.
  21048. */
  21049. element( indexNode ) {
  21050. return storageElement( this, indexNode );
  21051. }
  21052. /**
  21053. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  21054. *
  21055. * @param {Boolean} value - The value so set.
  21056. * @return {StorageBufferNode} A reference to this node.
  21057. */
  21058. setPBO( value ) {
  21059. this.isPBO = value;
  21060. return this;
  21061. }
  21062. /**
  21063. * Returns the `isPBO` value.
  21064. *
  21065. * @return {Boolean} Whether the node represents a PBO or not.
  21066. */
  21067. getPBO() {
  21068. return this.isPBO;
  21069. }
  21070. /**
  21071. * Defines the node access.
  21072. *
  21073. * @param {String} value - The node access.
  21074. * @return {StorageBufferNode} A reference to this node.
  21075. */
  21076. setAccess( value ) {
  21077. this.access = value;
  21078. return this;
  21079. }
  21080. /**
  21081. * Convenience method for configuring a read-only node access.
  21082. *
  21083. * @return {StorageBufferNode} A reference to this node.
  21084. */
  21085. toReadOnly() {
  21086. return this.setAccess( NodeAccess.READ_ONLY );
  21087. }
  21088. /**
  21089. * Defines whether the node is atomic or not.
  21090. *
  21091. * @param {Boolean} value - The atomic flag.
  21092. * @return {StorageBufferNode} A reference to this node.
  21093. */
  21094. setAtomic( value ) {
  21095. this.isAtomic = value;
  21096. return this;
  21097. }
  21098. /**
  21099. * Convenience method for making this node atomic.
  21100. *
  21101. * @return {StorageBufferNode} A reference to this node.
  21102. */
  21103. toAtomic() {
  21104. return this.setAtomic( true );
  21105. }
  21106. /**
  21107. * Returns attribute data for this storage buffer node.
  21108. *
  21109. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  21110. */
  21111. getAttributeData() {
  21112. if ( this._attribute === null ) {
  21113. this._attribute = bufferAttribute( this.value );
  21114. this._varying = varying( this._attribute );
  21115. }
  21116. return {
  21117. attribute: this._attribute,
  21118. varying: this._varying
  21119. };
  21120. }
  21121. /**
  21122. * This method is overwritten since the node type from the availability of storage buffers
  21123. * and the attribute data.
  21124. *
  21125. * @param {NodeBuilder} builder - The current node builder.
  21126. * @return {String} The node type.
  21127. */
  21128. getNodeType( builder ) {
  21129. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21130. return super.getNodeType( builder );
  21131. }
  21132. const { attribute } = this.getAttributeData();
  21133. return attribute.getNodeType( builder );
  21134. }
  21135. /**
  21136. * Generates the code snippet of the storage buffer node.
  21137. *
  21138. * @param {NodeBuilder} builder - The current node builder.
  21139. * @return {String} The generated code snippet.
  21140. */
  21141. generate( builder ) {
  21142. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21143. return super.generate( builder );
  21144. }
  21145. const { attribute, varying } = this.getAttributeData();
  21146. const output = varying.build( builder );
  21147. builder.registerTransform( output, attribute );
  21148. return output;
  21149. }
  21150. }
  21151. /**
  21152. * TSL function for creating a storage buffer node.
  21153. *
  21154. * @function
  21155. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21156. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  21157. * @param {Number} [count=0] - The buffer count.
  21158. * @returns {StorageBufferNode}
  21159. */
  21160. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21161. /**
  21162. * @function
  21163. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21164. *
  21165. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21166. * @param {String?} type - The buffer type (e.g. `'vec3'`).
  21167. * @param {Number} count - The buffer count.
  21168. * @returns {StorageBufferNode}
  21169. */
  21170. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21171. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21172. return storage( value, type, count ).setPBO( true );
  21173. };
  21174. /** @module Arrays **/
  21175. /**
  21176. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21177. *
  21178. * @function
  21179. * @param {Number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21180. * @param {String} [type='float'] - The data type.
  21181. * @returns {StorageBufferNode}
  21182. */
  21183. const attributeArray = ( count, type = 'float' ) => {
  21184. const itemSize = getLengthFromType( type );
  21185. const typedArray = getTypedArrayFromType( type );
  21186. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21187. const node = storage( buffer, type, count );
  21188. return node;
  21189. };
  21190. /**
  21191. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21192. *
  21193. * @function
  21194. * @param {Number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21195. * @param {String} [type='float'] - The data type.
  21196. * @returns {StorageBufferNode}
  21197. */
  21198. const instancedArray = ( count, type = 'float' ) => {
  21199. const itemSize = getLengthFromType( type );
  21200. const typedArray = getTypedArrayFromType( type );
  21201. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21202. const node = storage( buffer, type, count );
  21203. return node;
  21204. };
  21205. /** @module VertexColorNode **/
  21206. /**
  21207. * An attribute node for representing vertex colors.
  21208. *
  21209. * @augments module:AttributeNode~AttributeNode
  21210. */
  21211. class VertexColorNode extends AttributeNode {
  21212. static get type() {
  21213. return 'VertexColorNode';
  21214. }
  21215. /**
  21216. * Constructs a new vertex color node.
  21217. *
  21218. * @param {Number} [index=0] - The attribute index.
  21219. */
  21220. constructor( index = 0 ) {
  21221. super( null, 'vec4' );
  21222. /**
  21223. * This flag can be used for type testing.
  21224. *
  21225. * @type {Boolean}
  21226. * @readonly
  21227. * @default true
  21228. */
  21229. this.isVertexColorNode = true;
  21230. /**
  21231. * The attribute index to enable more than one sets of vertex colors.
  21232. *
  21233. * @type {Number}
  21234. * @default 0
  21235. */
  21236. this.index = index;
  21237. }
  21238. /**
  21239. * Overwrites the default implementation by honoring the attribute index.
  21240. *
  21241. * @param {NodeBuilder} builder - The current node builder.
  21242. * @return {String} The attribute name.
  21243. */
  21244. getAttributeName( /*builder*/ ) {
  21245. const index = this.index;
  21246. return 'color' + ( index > 0 ? index : '' );
  21247. }
  21248. generate( builder ) {
  21249. const attributeName = this.getAttributeName( builder );
  21250. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21251. let result;
  21252. if ( geometryAttribute === true ) {
  21253. result = super.generate( builder );
  21254. } else {
  21255. // Vertex color fallback should be white
  21256. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21257. }
  21258. return result;
  21259. }
  21260. serialize( data ) {
  21261. super.serialize( data );
  21262. data.index = this.index;
  21263. }
  21264. deserialize( data ) {
  21265. super.deserialize( data );
  21266. this.index = data.index;
  21267. }
  21268. }
  21269. /**
  21270. * TSL function for creating a reference node.
  21271. *
  21272. * @function
  21273. * @param {Number} index - The attribute index.
  21274. * @returns {VertexColorNode}
  21275. */
  21276. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21277. /** @module PointUVNode **/
  21278. /**
  21279. * A node for representing the uv coordinates of points.
  21280. *
  21281. * Can only be used with a WebGL backend. In WebGPU, point
  21282. * primitives always have the size of one pixel and can thus
  21283. * can't be used as sprite-like objects that display textures.
  21284. *
  21285. * @augments Node
  21286. */
  21287. class PointUVNode extends Node {
  21288. static get type() {
  21289. return 'PointUVNode';
  21290. }
  21291. /**
  21292. * Constructs a new point uv node.
  21293. */
  21294. constructor() {
  21295. super( 'vec2' );
  21296. /**
  21297. * This flag can be used for type testing.
  21298. *
  21299. * @type {Boolean}
  21300. * @readonly
  21301. * @default true
  21302. */
  21303. this.isPointUVNode = true;
  21304. }
  21305. generate( /*builder*/ ) {
  21306. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21307. }
  21308. }
  21309. /**
  21310. * TSL object that represents the uv coordinates of points.
  21311. *
  21312. * @type {PointUVNode}
  21313. */
  21314. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21315. const _e1 = /*@__PURE__*/ new Euler();
  21316. const _m1 = /*@__PURE__*/ new Matrix4();
  21317. /** @module SceneNode **/
  21318. /**
  21319. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21320. * are available for easier use:
  21321. *
  21322. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21323. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21324. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21325. *
  21326. * @augments Node
  21327. */
  21328. class SceneNode extends Node {
  21329. static get type() {
  21330. return 'SceneNode';
  21331. }
  21332. /**
  21333. * Constructs a new scene node.
  21334. *
  21335. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21336. * @param {Scene?} [scene=null] - A reference to the scene.
  21337. */
  21338. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21339. super();
  21340. /**
  21341. * The scope defines the type of scene property that is accessed.
  21342. *
  21343. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21344. */
  21345. this.scope = scope;
  21346. /**
  21347. * A reference to the scene that is going to be accessed.
  21348. *
  21349. * @type {Scene?}
  21350. * @default null
  21351. */
  21352. this.scene = scene;
  21353. }
  21354. /**
  21355. * Depending on the scope, the method returns a different type of node that represents
  21356. * the respective scene property.
  21357. *
  21358. * @param {NodeBuilder} builder - The current node builder.
  21359. * @return {Node} The output node.
  21360. */
  21361. setup( builder ) {
  21362. const scope = this.scope;
  21363. const scene = this.scene !== null ? this.scene : builder.scene;
  21364. let output;
  21365. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21366. output = reference( 'backgroundBlurriness', 'float', scene );
  21367. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21368. output = reference( 'backgroundIntensity', 'float', scene );
  21369. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21370. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21371. const background = scene.background;
  21372. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21373. _e1.copy( scene.backgroundRotation );
  21374. // accommodate left-handed frame
  21375. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  21376. _m1.makeRotationFromEuler( _e1 );
  21377. } else {
  21378. _m1.identity();
  21379. }
  21380. return _m1;
  21381. } );
  21382. } else {
  21383. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21384. }
  21385. return output;
  21386. }
  21387. }
  21388. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21389. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21390. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21391. /**
  21392. * TSL object that represents the scene's background blurriness.
  21393. *
  21394. * @type {SceneNode}
  21395. */
  21396. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21397. /**
  21398. * TSL object that represents the scene's background intensity.
  21399. *
  21400. * @type {SceneNode}
  21401. */
  21402. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21403. /**
  21404. * TSL object that represents the scene's background rotation.
  21405. *
  21406. * @type {SceneNode}
  21407. */
  21408. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21409. /** @module StorageTextureNode **/
  21410. /**
  21411. * This special version of a texture node can be used to
  21412. * write data into a storage texture with a compute shader.
  21413. *
  21414. * ```js
  21415. * const storageTexture = new THREE.StorageTexture( width, height );
  21416. *
  21417. * const computeTexture = Fn( ( { storageTexture } ) => {
  21418. *
  21419. * const posX = instanceIndex.modInt( width );
  21420. * const posY = instanceIndex.div( width );
  21421. * const indexUV = uvec2( posX, posY );
  21422. *
  21423. * // generate RGB values
  21424. *
  21425. * const r = 1;
  21426. * const g = 1;
  21427. * const b = 1;
  21428. *
  21429. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21430. *
  21431. * } );
  21432. *
  21433. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21434. * renderer.computeAsync( computeNode );
  21435. * ```
  21436. *
  21437. * This node can only be used with a WebGPU backend.
  21438. *
  21439. * @augments module:TextureNode~TextureNode
  21440. */
  21441. class StorageTextureNode extends TextureNode {
  21442. static get type() {
  21443. return 'StorageTextureNode';
  21444. }
  21445. /**
  21446. * Constructs a new storage texture node.
  21447. *
  21448. * @param {StorageTexture} value - The storage texture.
  21449. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21450. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21451. */
  21452. constructor( value, uvNode, storeNode = null ) {
  21453. super( value, uvNode );
  21454. /**
  21455. * The value node that should be stored in the texture.
  21456. *
  21457. * @type {Node?}
  21458. * @default null
  21459. */
  21460. this.storeNode = storeNode;
  21461. /**
  21462. * This flag can be used for type testing.
  21463. *
  21464. * @type {Boolean}
  21465. * @readonly
  21466. * @default true
  21467. */
  21468. this.isStorageTextureNode = true;
  21469. /**
  21470. * The access type of the texture node.
  21471. *
  21472. * @type {String}
  21473. * @default 'writeOnly'
  21474. */
  21475. this.access = NodeAccess.WRITE_ONLY;
  21476. }
  21477. /**
  21478. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21479. *
  21480. * @param {NodeBuilder} builder - The current node builder.
  21481. * @return {String} The input type.
  21482. */
  21483. getInputType( /*builder*/ ) {
  21484. return 'storageTexture';
  21485. }
  21486. setup( builder ) {
  21487. super.setup( builder );
  21488. const properties = builder.getNodeProperties( this );
  21489. properties.storeNode = this.storeNode;
  21490. }
  21491. /**
  21492. * Defines the node access.
  21493. *
  21494. * @param {String} value - The node access.
  21495. * @return {StorageTextureNode} A reference to this node.
  21496. */
  21497. setAccess( value ) {
  21498. this.access = value;
  21499. return this;
  21500. }
  21501. /**
  21502. * Generates the code snippet of the stroge node. If no `storeNode`
  21503. * is defined, the texture node is generated as normal texture.
  21504. *
  21505. * @param {NodeBuilder} builder - The current node builder.
  21506. * @param {String} output - The current output.
  21507. * @return {String} The generated code snippet.
  21508. */
  21509. generate( builder, output ) {
  21510. let snippet;
  21511. if ( this.storeNode !== null ) {
  21512. snippet = this.generateStore( builder );
  21513. } else {
  21514. snippet = super.generate( builder, output );
  21515. }
  21516. return snippet;
  21517. }
  21518. /**
  21519. * Convenience method for configuring a read/write node access.
  21520. *
  21521. * @return {StorageTextureNode} A reference to this node.
  21522. */
  21523. toReadWrite() {
  21524. return this.setAccess( NodeAccess.READ_WRITE );
  21525. }
  21526. /**
  21527. * Convenience method for configuring a read-only node access.
  21528. *
  21529. * @return {StorageTextureNode} A reference to this node.
  21530. */
  21531. toReadOnly() {
  21532. return this.setAccess( NodeAccess.READ_ONLY );
  21533. }
  21534. /**
  21535. * Convenience method for configuring a write-only node access.
  21536. *
  21537. * @return {StorageTextureNode} A reference to this node.
  21538. */
  21539. toWriteOnly() {
  21540. return this.setAccess( NodeAccess.WRITE_ONLY );
  21541. }
  21542. /**
  21543. * Generates the code snippet of the storage texture node.
  21544. *
  21545. * @param {NodeBuilder} builder - The current node builder.
  21546. */
  21547. generateStore( builder ) {
  21548. const properties = builder.getNodeProperties( this );
  21549. const { uvNode, storeNode } = properties;
  21550. const textureProperty = super.generate( builder, 'property' );
  21551. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21552. const storeSnippet = storeNode.build( builder, 'vec4' );
  21553. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21554. builder.addLineFlowCode( snippet, this );
  21555. }
  21556. }
  21557. /**
  21558. * TSL function for creating a storage texture node.
  21559. *
  21560. * @function
  21561. * @param {StorageTexture} value - The storage texture.
  21562. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21563. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21564. * @returns {StorageTextureNode}
  21565. */
  21566. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21567. /**
  21568. * TODO: Explain difference to `storageTexture()`.
  21569. *
  21570. * @function
  21571. * @param {StorageTexture} value - The storage texture.
  21572. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21573. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21574. * @returns {StorageTextureNode}
  21575. */
  21576. const textureStore = ( value, uvNode, storeNode ) => {
  21577. const node = storageTexture( value, uvNode, storeNode );
  21578. if ( storeNode !== null ) node.append();
  21579. return node;
  21580. };
  21581. /** @module UserDataNode **/
  21582. /**
  21583. * A special type of reference node that allows to link values in
  21584. * `userData` fields to node objects.
  21585. * ```js
  21586. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21587. *
  21588. * const material = new THREE.SpriteNodeMaterial();
  21589. * material.rotationNode = userData( 'rotation', 'float' );
  21590. * ```
  21591. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21592. * will automatically be updated when the `rotation` user data field changes.
  21593. *
  21594. * @augments module:ReferenceNode~ReferenceNode
  21595. */
  21596. class UserDataNode extends ReferenceNode {
  21597. static get type() {
  21598. return 'UserDataNode';
  21599. }
  21600. /**
  21601. * Constructs a new user data node.
  21602. *
  21603. * @param {String} property - The property name that should be referenced by the node.
  21604. * @param {String} inputType - The node data type of the reference.
  21605. * @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.
  21606. */
  21607. constructor( property, inputType, userData = null ) {
  21608. super( property, inputType, userData );
  21609. /**
  21610. * A reference to the `userData` object. If not provided, the `userData`
  21611. * property of the 3D object that uses the node material is evaluated.
  21612. *
  21613. * @type {Object?}
  21614. * @default null
  21615. */
  21616. this.userData = userData;
  21617. }
  21618. /**
  21619. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21620. * `userData` field.
  21621. *
  21622. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21623. * @return {Object} A reference to the `userData` field.
  21624. */
  21625. updateReference( state ) {
  21626. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21627. return this.reference;
  21628. }
  21629. }
  21630. /**
  21631. * TSL function for creating a user data node.
  21632. *
  21633. * @function
  21634. * @param {String} name - The property name that should be referenced by the node.
  21635. * @param {String} inputType - The node data type of the reference.
  21636. * @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.
  21637. * @returns {UserDataNode}
  21638. */
  21639. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21640. const _objectData = new WeakMap();
  21641. /** @module VelocityNode **/
  21642. /**
  21643. * A node for representing motion or velocity vectors. Foundation
  21644. * for advanced post processing effects like motion blur or TRAA.
  21645. *
  21646. * The node keeps track of the model, view and projection matrices
  21647. * of the previous frame and uses them to compute offsets in NDC space.
  21648. * These offsets represent the final velocity.
  21649. *
  21650. * @augments TempNode
  21651. */
  21652. class VelocityNode extends TempNode {
  21653. static get type() {
  21654. return 'VelocityNode';
  21655. }
  21656. /**
  21657. * Constructs a new vertex color node.
  21658. */
  21659. constructor() {
  21660. super( 'vec2' );
  21661. /**
  21662. * The current projection matrix.
  21663. *
  21664. * @type {Matrix4?}
  21665. * @default null
  21666. */
  21667. this.projectionMatrix = null;
  21668. /**
  21669. * Overwritten since velocity nodes are updated per object.
  21670. *
  21671. * @type {String}
  21672. * @default 'object'
  21673. */
  21674. this.updateType = NodeUpdateType.OBJECT;
  21675. /**
  21676. * Overwritten since velocity nodes save data after the update.
  21677. *
  21678. * @type {String}
  21679. * @default 'object'
  21680. */
  21681. this.updateAfterType = NodeUpdateType.OBJECT;
  21682. /**
  21683. * Uniform node representing the previous model matrix in world space.
  21684. *
  21685. * @type {UniformNode<mat4>}
  21686. * @default null
  21687. */
  21688. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21689. /**
  21690. * Uniform node representing the previous projection matrix.
  21691. *
  21692. * @type {UniformNode<mat4>}
  21693. * @default null
  21694. */
  21695. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21696. /**
  21697. * Uniform node representing the previous view matrix.
  21698. *
  21699. * @type {UniformNode<mat4>}
  21700. * @default null
  21701. */
  21702. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21703. }
  21704. /**
  21705. * Sets the given projection matrix.
  21706. *
  21707. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21708. */
  21709. setProjectionMatrix( projectionMatrix ) {
  21710. this.projectionMatrix = projectionMatrix;
  21711. }
  21712. /**
  21713. * Updates velocity specific uniforms.
  21714. *
  21715. * @param {NodeFrame} frame - A reference to the current node frame.
  21716. */
  21717. update( { frameId, camera, object } ) {
  21718. const previousModelMatrix = getPreviousMatrix( object );
  21719. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21720. //
  21721. const cameraData = getData( camera );
  21722. if ( cameraData.frameId !== frameId ) {
  21723. cameraData.frameId = frameId;
  21724. if ( cameraData.previousProjectionMatrix === undefined ) {
  21725. cameraData.previousProjectionMatrix = new Matrix4();
  21726. cameraData.previousCameraViewMatrix = new Matrix4();
  21727. cameraData.currentProjectionMatrix = new Matrix4();
  21728. cameraData.currentCameraViewMatrix = new Matrix4();
  21729. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21730. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21731. } else {
  21732. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21733. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21734. }
  21735. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21736. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21737. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21738. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21739. }
  21740. }
  21741. /**
  21742. * Overwritten to updated velocity specific uniforms.
  21743. *
  21744. * @param {NodeFrame} frame - A reference to the current node frame.
  21745. */
  21746. updateAfter( { object } ) {
  21747. getPreviousMatrix( object ).copy( object.matrixWorld );
  21748. }
  21749. /**
  21750. * Implements the velocity computation based on the previous and current vertex data.
  21751. *
  21752. * @param {NodeBuilder} builder - A reference to the current node builder.
  21753. * @return {Node<vec2>} The motion vector.
  21754. */
  21755. setup( /*builder*/ ) {
  21756. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21757. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21758. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21759. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21760. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21761. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21762. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21763. return velocity;
  21764. }
  21765. }
  21766. function getData( object ) {
  21767. let objectData = _objectData.get( object );
  21768. if ( objectData === undefined ) {
  21769. objectData = {};
  21770. _objectData.set( object, objectData );
  21771. }
  21772. return objectData;
  21773. }
  21774. function getPreviousMatrix( object, index = 0 ) {
  21775. const objectData = getData( object );
  21776. let matrix = objectData[ index ];
  21777. if ( matrix === undefined ) {
  21778. objectData[ index ] = matrix = new Matrix4();
  21779. }
  21780. return matrix;
  21781. }
  21782. /**
  21783. * TSL object that represents the velocity of a render pass.
  21784. *
  21785. * @type {VelocityNode}
  21786. */
  21787. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21788. /** @module BlendModes **/
  21789. /**
  21790. * Represents a "Color Burn" blend mode.
  21791. *
  21792. * It's designed to darken the base layer's colors based on the color of the blend layer.
  21793. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  21794. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  21795. *
  21796. * @method
  21797. * @param {Node<vec3>} base - The base color.
  21798. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  21799. * @return {Node<vec3>} The result.
  21800. */
  21801. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21802. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21803. } ).setLayout( {
  21804. name: 'blendBurn',
  21805. type: 'vec3',
  21806. inputs: [
  21807. { name: 'base', type: 'vec3' },
  21808. { name: 'blend', type: 'vec3' }
  21809. ]
  21810. } );
  21811. /**
  21812. * Represents a "Color Dodge" blend mode.
  21813. *
  21814. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  21815. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  21816. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  21817. *
  21818. * @method
  21819. * @param {Node<vec3>} base - The base color.
  21820. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21821. * @return {Node<vec3>} The result.
  21822. */
  21823. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21824. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21825. } ).setLayout( {
  21826. name: 'blendDodge',
  21827. type: 'vec3',
  21828. inputs: [
  21829. { name: 'base', type: 'vec3' },
  21830. { name: 'blend', type: 'vec3' }
  21831. ]
  21832. } );
  21833. /**
  21834. * Represents a "Screen" blend mode.
  21835. *
  21836. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  21837. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  21838. * effects.
  21839. *
  21840. * @method
  21841. * @param {Node<vec3>} base - The base color.
  21842. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21843. * @return {Node<vec3>} The result.
  21844. */
  21845. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21846. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21847. } ).setLayout( {
  21848. name: 'blendScreen',
  21849. type: 'vec3',
  21850. inputs: [
  21851. { name: 'base', type: 'vec3' },
  21852. { name: 'blend', type: 'vec3' }
  21853. ]
  21854. } );
  21855. /**
  21856. * Represents a "Overlay" blend mode.
  21857. *
  21858. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  21859. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  21860. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  21861. *
  21862. * @method
  21863. * @param {Node<vec3>} base - The base color.
  21864. * @param {Node<vec3>} blend - The blend color
  21865. * @return {Node<vec3>} The result.
  21866. */
  21867. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21868. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21869. } ).setLayout( {
  21870. name: 'blendOverlay',
  21871. type: 'vec3',
  21872. inputs: [
  21873. { name: 'base', type: 'vec3' },
  21874. { name: 'blend', type: 'vec3' }
  21875. ]
  21876. } );
  21877. /**
  21878. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  21879. * It assumes both input colors have non-preumiltiplied alpha.
  21880. *
  21881. * @method
  21882. * @param {Node<vec4>} base - The base color.
  21883. * @param {Node<vec4>} blend - The blend color
  21884. * @return {Node<vec4>} The result.
  21885. */
  21886. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21887. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21888. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21889. } ).setLayout( {
  21890. name: 'blendColor',
  21891. type: 'vec4',
  21892. inputs: [
  21893. { name: 'base', type: 'vec4' },
  21894. { name: 'blend', type: 'vec4' }
  21895. ]
  21896. } );
  21897. // Deprecated
  21898. /**
  21899. * @function
  21900. * @deprecated since r171. Use {@link blendBurn} instead.
  21901. *
  21902. * @param {...any} params
  21903. * @returns {Function}
  21904. */
  21905. const burn = ( ...params ) => { // @deprecated, r171
  21906. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21907. return blendBurn( params );
  21908. };
  21909. /**
  21910. * @function
  21911. * @deprecated since r171. Use {@link blendDodge} instead.
  21912. *
  21913. * @param {...any} params
  21914. * @returns {Function}
  21915. */
  21916. const dodge = ( ...params ) => { // @deprecated, r171
  21917. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21918. return blendDodge( params );
  21919. };
  21920. /**
  21921. * @method
  21922. * @deprecated since r171. Use {@link blendScreen} instead.
  21923. *
  21924. * @param {...any} params
  21925. * @returns {Function}
  21926. */
  21927. const screen = ( ...params ) => { // @deprecated, r171
  21928. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21929. return blendScreen( params );
  21930. };
  21931. /**
  21932. * @method
  21933. * @deprecated since r171. Use {@link blendOverlay} instead.
  21934. *
  21935. * @param {...any} params
  21936. * @returns {Function}
  21937. */
  21938. const overlay = ( ...params ) => { // @deprecated, r171
  21939. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21940. return blendOverlay( params );
  21941. };
  21942. /** @module ColorAdjustment **/
  21943. /**
  21944. * Computes a grayscale value for the given RGB color value.
  21945. *
  21946. * @method
  21947. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21948. * @return {Node<vec3>} The grayscale color.
  21949. */
  21950. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21951. return luminance( color.rgb );
  21952. } );
  21953. /**
  21954. * Super-saturates or desaturates the given RGB color.
  21955. *
  21956. * @method
  21957. * @param {Node<vec3>} color - The input color.
  21958. * @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.
  21959. * @return {Node<vec3>} The saturated color.
  21960. */
  21961. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21962. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21963. } );
  21964. /**
  21965. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21966. * in a more natural and visually appealing image with enhanced color depth
  21967. * compared to {@link ColorAdjustment#saturation}.
  21968. *
  21969. * @method
  21970. * @param {Node<vec3>} color - The input color.
  21971. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21972. * @return {Node<vec3>} The updated color.
  21973. */
  21974. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21975. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21976. const mx = color.r.max( color.g.max( color.b ) );
  21977. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  21978. return mix( color.rgb, mx, amt );
  21979. } );
  21980. /**
  21981. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21982. *
  21983. * @method
  21984. * @param {Node<vec3>} color - The input color.
  21985. * @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.
  21986. * @return {Node<vec3>} The updated color.
  21987. */
  21988. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21989. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21990. const cosAngle = adjustment.cos();
  21991. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21992. } );
  21993. /**
  21994. * Computes the luminance for the given RGB color value.
  21995. *
  21996. * @method
  21997. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21998. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21999. * @return {Node<vec3>} The luminance.
  22000. */
  22001. const luminance = (
  22002. color,
  22003. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  22004. ) => dot( color, luminanceCoefficients );
  22005. /**
  22006. * Color Decision List (CDL) v1.2
  22007. *
  22008. * Compact representation of color grading information, defined by slope, offset, power, and
  22009. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  22010. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  22011. *
  22012. * @method
  22013. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  22014. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  22015. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  22016. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  22017. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  22018. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  22019. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  22020. *
  22021. * References:
  22022. * - ASC CDL v1.2
  22023. * - {@link https://blender.stackexchange.com/a/55239/43930}
  22024. * - {@link https://docs.acescentral.com/specifications/acescc/}
  22025. */
  22026. const cdl = /*@__PURE__*/ Fn( ( [
  22027. color,
  22028. slope = vec3( 1 ),
  22029. offset = vec3( 0 ),
  22030. power = vec3( 1 ),
  22031. saturation = float( 1 ),
  22032. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  22033. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  22034. ] ) => {
  22035. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  22036. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  22037. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  22038. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  22039. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  22040. const pv = v.pow( power ).toVar();
  22041. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  22042. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  22043. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  22044. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  22045. return vec4( v.rgb, color.a );
  22046. } );
  22047. /** @module PosterizeNode **/
  22048. /**
  22049. * Represents a posterize effect which reduces the number of colors
  22050. * in an image, resulting in a more blocky and stylized appearance.
  22051. *
  22052. * @augments TempNode
  22053. */
  22054. class PosterizeNode extends TempNode {
  22055. static get type() {
  22056. return 'PosterizeNode';
  22057. }
  22058. /**
  22059. * Constructs a new posterize node.
  22060. *
  22061. * @param {Node} sourceNode - The input color.
  22062. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22063. */
  22064. constructor( sourceNode, stepsNode ) {
  22065. super();
  22066. /**
  22067. * The input color.
  22068. *
  22069. * @type {Node}
  22070. */
  22071. this.sourceNode = sourceNode;
  22072. /**
  22073. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22074. *
  22075. * @type {Node}
  22076. */
  22077. this.stepsNode = stepsNode;
  22078. }
  22079. setup() {
  22080. const { sourceNode, stepsNode } = this;
  22081. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  22082. }
  22083. }
  22084. /**
  22085. * TSL function for creating a posterize node.
  22086. *
  22087. * @function
  22088. * @param {Node} sourceNode - The input color.
  22089. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22090. * @returns {PosterizeNode}
  22091. */
  22092. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  22093. /** @module PassNode **/
  22094. const _size = /*@__PURE__*/ new Vector2();
  22095. /**
  22096. * Represents the texture of a pass node.
  22097. *
  22098. * @augments module:TextureNode~TextureNode
  22099. */
  22100. class PassTextureNode extends TextureNode {
  22101. static get type() {
  22102. return 'PassTextureNode';
  22103. }
  22104. /**
  22105. * Constructs a new pass texture node.
  22106. *
  22107. * @param {PassNode} passNode - The pass node.
  22108. * @param {Texture} texture - The output texture.
  22109. */
  22110. constructor( passNode, texture ) {
  22111. super( texture );
  22112. /**
  22113. * A reference to the pass node.
  22114. *
  22115. * @type {PassNode}
  22116. */
  22117. this.passNode = passNode;
  22118. this.setUpdateMatrix( false );
  22119. }
  22120. setup( builder ) {
  22121. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22122. return super.setup( builder );
  22123. }
  22124. clone() {
  22125. return new this.constructor( this.passNode, this.value );
  22126. }
  22127. }
  22128. /**
  22129. * An extension of `PassTextureNode` which allows to manage more than one
  22130. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22131. *
  22132. * @augments module:PassTextureNode~PassTextureNode
  22133. */
  22134. class PassMultipleTextureNode extends PassTextureNode {
  22135. static get type() {
  22136. return 'PassMultipleTextureNode';
  22137. }
  22138. /**
  22139. * Constructs a new pass texture node.
  22140. *
  22141. * @param {PassNode} passNode - The pass node.
  22142. * @param {String} textureName - The output texture name.
  22143. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22144. */
  22145. constructor( passNode, textureName, previousTexture = false ) {
  22146. // null is passed to the super call since this class does not
  22147. // use an external texture for rendering pass data into. Instead
  22148. // the texture is managed by the pass node itself
  22149. super( passNode, null );
  22150. /**
  22151. * The output texture name.
  22152. *
  22153. * @type {String}
  22154. */
  22155. this.textureName = textureName;
  22156. /**
  22157. * Whether previous frame data should be used or not.
  22158. *
  22159. * @type {Boolean}
  22160. */
  22161. this.previousTexture = previousTexture;
  22162. }
  22163. /**
  22164. * Updates the texture reference of this node.
  22165. */
  22166. updateTexture() {
  22167. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22168. }
  22169. setup( builder ) {
  22170. this.updateTexture();
  22171. return super.setup( builder );
  22172. }
  22173. clone() {
  22174. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22175. }
  22176. }
  22177. /**
  22178. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22179. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22180. * via MRT for further processing.
  22181. *
  22182. * ```js
  22183. * const postProcessing = new PostProcessing( renderer );
  22184. *
  22185. * const scenePass = pass( scene, camera );
  22186. *
  22187. * postProcessing.outputNode = scenePass;
  22188. * ```
  22189. *
  22190. * @augments TempNode
  22191. */
  22192. class PassNode extends TempNode {
  22193. static get type() {
  22194. return 'PassNode';
  22195. }
  22196. /**
  22197. * Constructs a new pass node.
  22198. *
  22199. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22200. * @param {Scene} scene - A reference to the scene.
  22201. * @param {Camera} camera - A reference to the camera.
  22202. * @param {Object} options - Options for the internal render target.
  22203. */
  22204. constructor( scope, scene, camera, options = {} ) {
  22205. super( 'vec4' );
  22206. /**
  22207. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22208. *
  22209. * @type {('color'|'depth')}
  22210. */
  22211. this.scope = scope;
  22212. /**
  22213. * A reference to the scene.
  22214. *
  22215. * @type {Scene}
  22216. */
  22217. this.scene = scene;
  22218. /**
  22219. * A reference to the camera.
  22220. *
  22221. * @type {Camera}
  22222. */
  22223. this.camera = camera;
  22224. /**
  22225. * Options for the internal render target.
  22226. *
  22227. * @type {Object}
  22228. */
  22229. this.options = options;
  22230. /**
  22231. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22232. *
  22233. * @private
  22234. * @type {Number}
  22235. * @default 1
  22236. */
  22237. this._pixelRatio = 1;
  22238. /**
  22239. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22240. * @private
  22241. * @type {Number}
  22242. * @default 1
  22243. */
  22244. this._width = 1;
  22245. /**
  22246. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22247. * @private
  22248. * @type {Number}
  22249. * @default 1
  22250. */
  22251. this._height = 1;
  22252. const depthTexture = new DepthTexture();
  22253. depthTexture.isRenderTargetTexture = true;
  22254. //depthTexture.type = FloatType;
  22255. depthTexture.name = 'depth';
  22256. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22257. renderTarget.texture.name = 'output';
  22258. renderTarget.depthTexture = depthTexture;
  22259. /**
  22260. * The pass's render target.
  22261. *
  22262. * @type {RenderTarget}
  22263. */
  22264. this.renderTarget = renderTarget;
  22265. /**
  22266. * A dictionary holding the internal result textures.
  22267. *
  22268. * @private
  22269. * @type {Object<String, Texture>}
  22270. */
  22271. this._textures = {
  22272. output: renderTarget.texture,
  22273. depth: depthTexture
  22274. };
  22275. /**
  22276. * A dictionary holding the internal texture nodes.
  22277. *
  22278. * @private
  22279. * @type {Object<String, TextureNode>}
  22280. */
  22281. this._textureNodes = {};
  22282. /**
  22283. * A dictionary holding the internal depth nodes.
  22284. *
  22285. * @private
  22286. * @type {Object}
  22287. */
  22288. this._linearDepthNodes = {};
  22289. /**
  22290. * A dictionary holding the internal viewZ nodes.
  22291. *
  22292. * @private
  22293. * @type {Object}
  22294. */
  22295. this._viewZNodes = {};
  22296. /**
  22297. * A dictionary holding the texture data of the previous frame.
  22298. * Used for computing velocity/motion vectors.
  22299. *
  22300. * @private
  22301. * @type {Object<String, Texture>}
  22302. */
  22303. this._previousTextures = {};
  22304. /**
  22305. * A dictionary holding the texture nodes of the previous frame.
  22306. * Used for computing velocity/motion vectors.
  22307. *
  22308. * @private
  22309. * @type {Object<String, TextureNode>}
  22310. */
  22311. this._previousTextureNodes = {};
  22312. /**
  22313. * The `near` property of the camera as a uniform.
  22314. *
  22315. * @private
  22316. * @type {UniformNode}
  22317. */
  22318. this._cameraNear = uniform( 0 );
  22319. /**
  22320. * The `far` property of the camera as a uniform.
  22321. *
  22322. * @private
  22323. * @type {UniformNode}
  22324. */
  22325. this._cameraFar = uniform( 0 );
  22326. /**
  22327. * A MRT node configuring the MRT settings.
  22328. *
  22329. * @private
  22330. * @type {MRTNode?}
  22331. * @default null
  22332. */
  22333. this._mrt = null;
  22334. /**
  22335. * This flag can be used for type testing.
  22336. *
  22337. * @type {Boolean}
  22338. * @readonly
  22339. * @default true
  22340. */
  22341. this.isPassNode = true;
  22342. /**
  22343. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22344. * scene once per frame in its {@link PassNode#updateBefore} method.
  22345. *
  22346. * @type {String}
  22347. * @default 'frame'
  22348. */
  22349. this.updateBeforeType = NodeUpdateType.FRAME;
  22350. }
  22351. /**
  22352. * Sets the given MRT node to setup MRT for this pass.
  22353. *
  22354. * @param {MRTNode} mrt - The MRT object.
  22355. * @return {PassNode} A reference to this pass.
  22356. */
  22357. setMRT( mrt ) {
  22358. this._mrt = mrt;
  22359. return this;
  22360. }
  22361. /**
  22362. * Returns the current MRT node.
  22363. *
  22364. * @return {MRTNode} The current MRT node.
  22365. */
  22366. getMRT() {
  22367. return this._mrt;
  22368. }
  22369. /**
  22370. * The method is overwritten so it always returns `true`.
  22371. *
  22372. * @return {Boolean} Whether this node is global or not.
  22373. */
  22374. isGlobal() {
  22375. return true;
  22376. }
  22377. /**
  22378. * Returns the texture for the given output name.
  22379. *
  22380. * @param {String} name - The output name to get the texture for.
  22381. * @return {Texture} The texture.
  22382. */
  22383. getTexture( name ) {
  22384. let texture = this._textures[ name ];
  22385. if ( texture === undefined ) {
  22386. const refTexture = this.renderTarget.texture;
  22387. texture = refTexture.clone();
  22388. texture.name = name;
  22389. this._textures[ name ] = texture;
  22390. this.renderTarget.textures.push( texture );
  22391. }
  22392. return texture;
  22393. }
  22394. /**
  22395. * Returns the texture holding the data of the previous frame for the given output name.
  22396. *
  22397. * @param {String} name - The output name to get the texture for.
  22398. * @return {Texture} The texture holding the data of the previous frame.
  22399. */
  22400. getPreviousTexture( name ) {
  22401. let texture = this._previousTextures[ name ];
  22402. if ( texture === undefined ) {
  22403. texture = this.getTexture( name ).clone();
  22404. this._previousTextures[ name ] = texture;
  22405. }
  22406. return texture;
  22407. }
  22408. /**
  22409. * Switches current and previous textures for the given output name.
  22410. *
  22411. * @param {String} name - The output name.
  22412. */
  22413. toggleTexture( name ) {
  22414. const prevTexture = this._previousTextures[ name ];
  22415. if ( prevTexture !== undefined ) {
  22416. const texture = this._textures[ name ];
  22417. const index = this.renderTarget.textures.indexOf( texture );
  22418. this.renderTarget.textures[ index ] = prevTexture;
  22419. this._textures[ name ] = prevTexture;
  22420. this._previousTextures[ name ] = texture;
  22421. this._textureNodes[ name ].updateTexture();
  22422. this._previousTextureNodes[ name ].updateTexture();
  22423. }
  22424. }
  22425. /**
  22426. * Returns the texture node for the given output name.
  22427. *
  22428. * @param {String} [name='output'] - The output name to get the texture node for.
  22429. * @return {TextureNode} The texture node.
  22430. */
  22431. getTextureNode( name = 'output' ) {
  22432. let textureNode = this._textureNodes[ name ];
  22433. if ( textureNode === undefined ) {
  22434. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22435. textureNode.updateTexture();
  22436. this._textureNodes[ name ] = textureNode;
  22437. }
  22438. return textureNode;
  22439. }
  22440. /**
  22441. * Returns the previous texture node for the given output name.
  22442. *
  22443. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22444. * @return {TextureNode} The previous texture node.
  22445. */
  22446. getPreviousTextureNode( name = 'output' ) {
  22447. let textureNode = this._previousTextureNodes[ name ];
  22448. if ( textureNode === undefined ) {
  22449. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22450. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22451. textureNode.updateTexture();
  22452. this._previousTextureNodes[ name ] = textureNode;
  22453. }
  22454. return textureNode;
  22455. }
  22456. /**
  22457. * Returns a viewZ node of this pass.
  22458. *
  22459. * @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.
  22460. * @return {Node} The viewZ node.
  22461. */
  22462. getViewZNode( name = 'depth' ) {
  22463. let viewZNode = this._viewZNodes[ name ];
  22464. if ( viewZNode === undefined ) {
  22465. const cameraNear = this._cameraNear;
  22466. const cameraFar = this._cameraFar;
  22467. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22468. }
  22469. return viewZNode;
  22470. }
  22471. /**
  22472. * Returns a linear depth node of this pass.
  22473. *
  22474. * @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.
  22475. * @return {Node} The linear depth node.
  22476. */
  22477. getLinearDepthNode( name = 'depth' ) {
  22478. let linearDepthNode = this._linearDepthNodes[ name ];
  22479. if ( linearDepthNode === undefined ) {
  22480. const cameraNear = this._cameraNear;
  22481. const cameraFar = this._cameraFar;
  22482. const viewZNode = this.getViewZNode( name );
  22483. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22484. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22485. }
  22486. return linearDepthNode;
  22487. }
  22488. setup( { renderer } ) {
  22489. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22490. // Disable MSAA for WebGL backend for now
  22491. if ( renderer.backend.isWebGLBackend === true ) {
  22492. this.renderTarget.samples = 0;
  22493. }
  22494. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22495. }
  22496. updateBefore( frame ) {
  22497. const { renderer } = frame;
  22498. const { scene, camera } = this;
  22499. this._pixelRatio = renderer.getPixelRatio();
  22500. const size = renderer.getSize( _size );
  22501. this.setSize( size.width, size.height );
  22502. const currentRenderTarget = renderer.getRenderTarget();
  22503. const currentMRT = renderer.getMRT();
  22504. this._cameraNear.value = camera.near;
  22505. this._cameraFar.value = camera.far;
  22506. for ( const name in this._previousTextures ) {
  22507. this.toggleTexture( name );
  22508. }
  22509. renderer.setRenderTarget( this.renderTarget );
  22510. renderer.setMRT( this._mrt );
  22511. renderer.render( scene, camera );
  22512. renderer.setRenderTarget( currentRenderTarget );
  22513. renderer.setMRT( currentMRT );
  22514. }
  22515. /**
  22516. * Sets the size of the pass's render target. Honors the pixel ratio.
  22517. *
  22518. * @param {Number} width - The width to set.
  22519. * @param {Number} height - The height to set.
  22520. */
  22521. setSize( width, height ) {
  22522. this._width = width;
  22523. this._height = height;
  22524. const effectiveWidth = this._width * this._pixelRatio;
  22525. const effectiveHeight = this._height * this._pixelRatio;
  22526. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22527. }
  22528. /**
  22529. * Sets the pixel ratio the pass's render target and updates the size.
  22530. *
  22531. * @param {Number} pixelRatio - The pixel ratio to set.
  22532. */
  22533. setPixelRatio( pixelRatio ) {
  22534. this._pixelRatio = pixelRatio;
  22535. this.setSize( this._width, this._height );
  22536. }
  22537. /**
  22538. * Frees internal resources. Should be called when the node is no longer in use.
  22539. */
  22540. dispose() {
  22541. this.renderTarget.dispose();
  22542. }
  22543. }
  22544. PassNode.COLOR = 'color';
  22545. PassNode.DEPTH = 'depth';
  22546. /**
  22547. * TSL function for creating a pass node.
  22548. *
  22549. * @function
  22550. * @param {Scene} scene - A reference to the scene.
  22551. * @param {Camera} camera - A reference to the camera.
  22552. * @param {Object} options - Options for the internal render target.
  22553. * @returns {PassNode}
  22554. */
  22555. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22556. /**
  22557. * TSL function for creating a pass texture node.
  22558. *
  22559. * @function
  22560. * @param {PassNode} pass - The pass node.
  22561. * @param {Texture} texture - The output texture.
  22562. * @returns {PassTextureNode}
  22563. */
  22564. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22565. /**
  22566. * TSL function for creating a depth pass node.
  22567. *
  22568. * @function
  22569. * @param {Scene} scene - A reference to the scene.
  22570. * @param {Camera} camera - A reference to the camera.
  22571. * @param {Object} options - Options for the internal render target.
  22572. * @returns {PassNode}
  22573. */
  22574. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22575. /** @module ToonOutlinePassNode **/
  22576. /**
  22577. * Represents a render pass for producing a toon outline effect on compatible objects.
  22578. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22579. * will receive the outline.
  22580. *
  22581. * ```js
  22582. * const postProcessing = new PostProcessing( renderer );
  22583. *
  22584. * const scenePass = toonOutlinePass( scene, camera );
  22585. *
  22586. * postProcessing.outputNode = scenePass;
  22587. * ```
  22588. * @augments PassNode
  22589. */
  22590. class ToonOutlinePassNode extends PassNode {
  22591. static get type() {
  22592. return 'ToonOutlinePassNode';
  22593. }
  22594. /**
  22595. * Constructs a new outline pass node.
  22596. *
  22597. * @param {Scene} scene - A reference to the scene.
  22598. * @param {Camera} camera - A reference to the camera.
  22599. * @param {Node} colorNode - Defines the outline's color.
  22600. * @param {Node} thicknessNode - Defines the outline's thickness.
  22601. * @param {Node} alphaNode - Defines the outline's alpha.
  22602. */
  22603. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22604. super( PassNode.COLOR, scene, camera );
  22605. /**
  22606. * Defines the outline's color.
  22607. *
  22608. * @type {Node}
  22609. */
  22610. this.colorNode = colorNode;
  22611. /**
  22612. * Defines the outline's thickness.
  22613. *
  22614. * @type {Node}
  22615. */
  22616. this.thicknessNode = thicknessNode;
  22617. /**
  22618. * Defines the outline's alpha.
  22619. *
  22620. * @type {Node}
  22621. */
  22622. this.alphaNode = alphaNode;
  22623. /**
  22624. * An internal material cache.
  22625. *
  22626. * @private
  22627. * @type {WeakMap<Material, NodeMaterial>}
  22628. */
  22629. this._materialCache = new WeakMap();
  22630. }
  22631. updateBefore( frame ) {
  22632. const { renderer } = frame;
  22633. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22634. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22635. // only render outline for supported materials
  22636. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22637. if ( material.wireframe === false ) {
  22638. const outlineMaterial = this._getOutlineMaterial( material );
  22639. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22640. }
  22641. }
  22642. // default
  22643. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22644. } );
  22645. super.updateBefore( frame );
  22646. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22647. }
  22648. /**
  22649. * Creates the material used for outline rendering.
  22650. *
  22651. * @private
  22652. * @return {NodeMaterial} The outline material.
  22653. */
  22654. _createMaterial() {
  22655. const material = new NodeMaterial();
  22656. material.isMeshToonOutlineMaterial = true;
  22657. material.name = 'Toon_Outline';
  22658. material.side = BackSide;
  22659. // vertex node
  22660. const outlineNormal = normalLocal.negate();
  22661. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22662. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22663. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22664. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22665. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22666. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22667. // color node
  22668. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22669. return material;
  22670. }
  22671. /**
  22672. * For the given toon material, this method returns a corresponding
  22673. * outline material.
  22674. *
  22675. * @private
  22676. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22677. * @return {NodeMaterial} The outline material.
  22678. */
  22679. _getOutlineMaterial( originalMaterial ) {
  22680. let outlineMaterial = this._materialCache.get( originalMaterial );
  22681. if ( outlineMaterial === undefined ) {
  22682. outlineMaterial = this._createMaterial();
  22683. this._materialCache.set( originalMaterial, outlineMaterial );
  22684. }
  22685. return outlineMaterial;
  22686. }
  22687. }
  22688. /**
  22689. * TSL function for creating a toon outline pass node.
  22690. *
  22691. * @function
  22692. * @param {Scene} scene - A reference to the scene.
  22693. * @param {Camera} camera - A reference to the camera.
  22694. * @param {Color} color - Defines the outline's color.
  22695. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22696. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22697. * @returns {ToonOutlinePassNode}
  22698. */
  22699. 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 ) ) );
  22700. /** @module ToneMappingFunctions **/
  22701. /**
  22702. * Linear tone mapping, exposure only.
  22703. *
  22704. * @method
  22705. * @param {Node<vec3>} color - The color that should be tone mapped.
  22706. * @param {Node<float>} exposure - The exposure.
  22707. * @return {Node<vec3>} The tone mapped color.
  22708. */
  22709. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22710. return color.mul( exposure ).clamp();
  22711. } ).setLayout( {
  22712. name: 'linearToneMapping',
  22713. type: 'vec3',
  22714. inputs: [
  22715. { name: 'color', type: 'vec3' },
  22716. { name: 'exposure', type: 'float' }
  22717. ]
  22718. } );
  22719. /**
  22720. * Reinhard tone mapping.
  22721. *
  22722. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22723. *
  22724. * @method
  22725. * @param {Node<vec3>} color - The color that should be tone mapped.
  22726. * @param {Node<float>} exposure - The exposure.
  22727. * @return {Node<vec3>} The tone mapped color.
  22728. */
  22729. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22730. color = color.mul( exposure );
  22731. return color.div( color.add( 1.0 ) ).clamp();
  22732. } ).setLayout( {
  22733. name: 'reinhardToneMapping',
  22734. type: 'vec3',
  22735. inputs: [
  22736. { name: 'color', type: 'vec3' },
  22737. { name: 'exposure', type: 'float' }
  22738. ]
  22739. } );
  22740. /**
  22741. * Cineon tone mapping.
  22742. *
  22743. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22744. *
  22745. * @method
  22746. * @param {Node<vec3>} color - The color that should be tone mapped.
  22747. * @param {Node<float>} exposure - The exposure.
  22748. * @return {Node<vec3>} The tone mapped color.
  22749. */
  22750. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22751. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22752. color = color.mul( exposure );
  22753. color = color.sub( 0.004 ).max( 0.0 );
  22754. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22755. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22756. return a.div( b ).pow( 2.2 );
  22757. } ).setLayout( {
  22758. name: 'cineonToneMapping',
  22759. type: 'vec3',
  22760. inputs: [
  22761. { name: 'color', type: 'vec3' },
  22762. { name: 'exposure', type: 'float' }
  22763. ]
  22764. } );
  22765. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22766. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22767. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22768. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22769. return a.div( b );
  22770. } );
  22771. /**
  22772. * ACESFilmic tone mapping.
  22773. *
  22774. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22775. *
  22776. * @method
  22777. * @param {Node<vec3>} color - The color that should be tone mapped.
  22778. * @param {Node<float>} exposure - The exposure.
  22779. * @return {Node<vec3>} The tone mapped color.
  22780. */
  22781. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22782. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22783. const ACESInputMat = mat3(
  22784. 0.59719, 0.35458, 0.04823,
  22785. 0.07600, 0.90834, 0.01566,
  22786. 0.02840, 0.13383, 0.83777
  22787. );
  22788. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22789. const ACESOutputMat = mat3(
  22790. 1.60475, -0.53108, -0.07367,
  22791. -0.10208, 1.10813, -605e-5,
  22792. -327e-5, -0.07276, 1.07602
  22793. );
  22794. color = color.mul( exposure ).div( 0.6 );
  22795. color = ACESInputMat.mul( color );
  22796. // Apply RRT and ODT
  22797. color = RRTAndODTFit( color );
  22798. color = ACESOutputMat.mul( color );
  22799. // Clamp to [0, 1]
  22800. return color.clamp();
  22801. } ).setLayout( {
  22802. name: 'acesFilmicToneMapping',
  22803. type: 'vec3',
  22804. inputs: [
  22805. { name: 'color', type: 'vec3' },
  22806. { name: 'exposure', type: 'float' }
  22807. ]
  22808. } );
  22809. 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 ) );
  22810. 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 ) );
  22811. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22812. const x = vec3( x_immutable ).toVar();
  22813. const x2 = vec3( x.mul( x ) ).toVar();
  22814. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22815. 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 ) ) ) );
  22816. } );
  22817. /**
  22818. * AgX tone mapping.
  22819. *
  22820. * @method
  22821. * @param {Node<vec3>} color - The color that should be tone mapped.
  22822. * @param {Node<float>} exposure - The exposure.
  22823. * @return {Node<vec3>} The tone mapped color.
  22824. */
  22825. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22826. const colortone = vec3( color ).toVar();
  22827. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22828. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  22829. const AgxMinEv = float( -12.47393 );
  22830. const AgxMaxEv = float( 4.026069 );
  22831. colortone.mulAssign( exposure );
  22832. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22833. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22834. colortone.assign( max$1( colortone, 1e-10 ) );
  22835. colortone.assign( log2( colortone ) );
  22836. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22837. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22838. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22839. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22840. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22841. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22842. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22843. return colortone;
  22844. } ).setLayout( {
  22845. name: 'agxToneMapping',
  22846. type: 'vec3',
  22847. inputs: [
  22848. { name: 'color', type: 'vec3' },
  22849. { name: 'exposure', type: 'float' }
  22850. ]
  22851. } );
  22852. /**
  22853. * Neutral tone mapping.
  22854. *
  22855. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22856. *
  22857. * @method
  22858. * @param {Node<vec3>} color - The color that should be tone mapped.
  22859. * @param {Node<float>} exposure - The exposure.
  22860. * @return {Node<vec3>} The tone mapped color.
  22861. */
  22862. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22863. const StartCompression = float( 0.8 - 0.04 );
  22864. const Desaturation = float( 0.15 );
  22865. color = color.mul( exposure );
  22866. const x = min$1( color.r, min$1( color.g, color.b ) );
  22867. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22868. color.subAssign( offset );
  22869. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22870. If( peak.lessThan( StartCompression ), () => {
  22871. return color;
  22872. } );
  22873. const d = sub( 1, StartCompression );
  22874. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22875. color.mulAssign( newPeak.div( peak ) );
  22876. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22877. return mix( color, vec3( newPeak ), g );
  22878. } ).setLayout( {
  22879. name: 'neutralToneMapping',
  22880. type: 'vec3',
  22881. inputs: [
  22882. { name: 'color', type: 'vec3' },
  22883. { name: 'exposure', type: 'float' }
  22884. ]
  22885. } );
  22886. /** @module CodeNode **/
  22887. /**
  22888. * This class represents native code sections. It is the base
  22889. * class for modules like {@link FunctionNode} which allows to implement
  22890. * functions with native shader languages.
  22891. *
  22892. * @augments Node
  22893. */
  22894. class CodeNode extends Node {
  22895. static get type() {
  22896. return 'CodeNode';
  22897. }
  22898. /**
  22899. * Constructs a new code node.
  22900. *
  22901. * @param {String} [code=''] - The native code.
  22902. * @param {Array<Node>} [includes=[]] - An array of includes.
  22903. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22904. */
  22905. constructor( code = '', includes = [], language = '' ) {
  22906. super( 'code' );
  22907. /**
  22908. * This flag can be used for type testing.
  22909. *
  22910. * @type {Boolean}
  22911. * @readonly
  22912. * @default true
  22913. */
  22914. this.isCodeNode = true;
  22915. /**
  22916. * The native code.
  22917. *
  22918. * @type {String}
  22919. * @default ''
  22920. */
  22921. this.code = code;
  22922. /**
  22923. * An array of includes
  22924. *
  22925. * @type {Array<Node>}
  22926. * @default []
  22927. */
  22928. this.includes = includes;
  22929. /**
  22930. * The used language.
  22931. *
  22932. * @type {('js'|'wgsl'|'glsl')}
  22933. * @default ''
  22934. */
  22935. this.language = language;
  22936. }
  22937. /**
  22938. * The method is overwritten so it always returns `true`.
  22939. *
  22940. * @return {Boolean} Whether this node is global or not.
  22941. */
  22942. isGlobal() {
  22943. return true;
  22944. }
  22945. /**
  22946. * Sets the includes of this code node.
  22947. *
  22948. * @param {Array<Node>} includes - The includes to set.
  22949. * @return {CodeNode} A reference to this node.
  22950. */
  22951. setIncludes( includes ) {
  22952. this.includes = includes;
  22953. return this;
  22954. }
  22955. /**
  22956. * Returns the includes of this code node.
  22957. *
  22958. * @param {NodeBuilder} builder - The current node builder.
  22959. * @return {Array<Node>} The includes.
  22960. */
  22961. getIncludes( /*builder*/ ) {
  22962. return this.includes;
  22963. }
  22964. generate( builder ) {
  22965. const includes = this.getIncludes( builder );
  22966. for ( const include of includes ) {
  22967. include.build( builder );
  22968. }
  22969. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22970. nodeCode.code = this.code;
  22971. return nodeCode.code;
  22972. }
  22973. serialize( data ) {
  22974. super.serialize( data );
  22975. data.code = this.code;
  22976. data.language = this.language;
  22977. }
  22978. deserialize( data ) {
  22979. super.deserialize( data );
  22980. this.code = data.code;
  22981. this.language = data.language;
  22982. }
  22983. }
  22984. /**
  22985. * TSL function for creating a code node.
  22986. *
  22987. * @function
  22988. * @param {String} [code=''] - The native code.
  22989. * @param {Array<Node>} [includes=[]] - An array of includes.
  22990. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22991. * @returns {CodeNode}
  22992. */
  22993. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22994. /**
  22995. * TSL function for creating a JS code node.
  22996. *
  22997. * @function
  22998. * @param {String} src - The native code.
  22999. * @param {Array<Node>} includes - An array of includes.
  23000. * @returns {CodeNode}
  23001. */
  23002. const js = ( src, includes ) => code( src, includes, 'js' );
  23003. /**
  23004. * TSL function for creating a WGSL code node.
  23005. *
  23006. * @function
  23007. * @param {String} src - The native code.
  23008. * @param {Array<Node>} includes - An array of includes.
  23009. * @returns {CodeNode}
  23010. */
  23011. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23012. /**
  23013. * TSL function for creating a GLSL code node.
  23014. *
  23015. * @function
  23016. * @param {String} src - The native code.
  23017. * @param {Array<Node>} includes - An array of includes.
  23018. * @returns {CodeNode}
  23019. */
  23020. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23021. /**
  23022. * This class represents a native shader function. It can be used to implement
  23023. * certain aspects of a node material with native shader code. There are two predefined
  23024. * TSL functions for easier usage.
  23025. *
  23026. * - `wgslFn`: Creates a WGSL function node.
  23027. * - `glslFn`: Creates a GLSL function node.
  23028. *
  23029. * A basic example with one include looks like so:
  23030. *
  23031. * ```js
  23032. * const desaturateWGSLFn = wgslFn( `
  23033. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  23034. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  23035. * return vec3<f32>( dot( lum, color ) );
  23036. * }`
  23037. *);
  23038. * const someWGSLFn = wgslFn( `
  23039. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  23040. * return desaturate( color );
  23041. * }
  23042. * `, [ desaturateWGSLFn ] );
  23043. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  23044. *```
  23045. * @augments CodeNode
  23046. */
  23047. class FunctionNode extends CodeNode {
  23048. static get type() {
  23049. return 'FunctionNode';
  23050. }
  23051. /**
  23052. * Constructs a new function node.
  23053. *
  23054. * @param {String} [code=''] - The native code.
  23055. * @param {Array<Node>} [includes=[]] - An array of includes.
  23056. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23057. */
  23058. constructor( code = '', includes = [], language = '' ) {
  23059. super( code, includes, language );
  23060. }
  23061. getNodeType( builder ) {
  23062. return this.getNodeFunction( builder ).type;
  23063. }
  23064. /**
  23065. * Returns the inputs of this function node.
  23066. *
  23067. * @param {NodeBuilder} builder - The current node builder.
  23068. * @return {Array<NodeFunctionInput>} The inputs.
  23069. */
  23070. getInputs( builder ) {
  23071. return this.getNodeFunction( builder ).inputs;
  23072. }
  23073. /**
  23074. * Returns the node function for this function node.
  23075. *
  23076. * @param {NodeBuilder} builder - The current node builder.
  23077. * @return {NodeFunction} The node function.
  23078. */
  23079. getNodeFunction( builder ) {
  23080. const nodeData = builder.getDataFromNode( this );
  23081. let nodeFunction = nodeData.nodeFunction;
  23082. if ( nodeFunction === undefined ) {
  23083. nodeFunction = builder.parser.parseFunction( this.code );
  23084. nodeData.nodeFunction = nodeFunction;
  23085. }
  23086. return nodeFunction;
  23087. }
  23088. generate( builder, output ) {
  23089. super.generate( builder );
  23090. const nodeFunction = this.getNodeFunction( builder );
  23091. const name = nodeFunction.name;
  23092. const type = nodeFunction.type;
  23093. const nodeCode = builder.getCodeFromNode( this, type );
  23094. if ( name !== '' ) {
  23095. // use a custom property name
  23096. nodeCode.name = name;
  23097. }
  23098. const propertyName = builder.getPropertyName( nodeCode );
  23099. const code = this.getNodeFunction( builder ).getCode( propertyName );
  23100. nodeCode.code = code + '\n';
  23101. if ( output === 'property' ) {
  23102. return propertyName;
  23103. } else {
  23104. return builder.format( `${ propertyName }()`, type, output );
  23105. }
  23106. }
  23107. }
  23108. const nativeFn = ( code, includes = [], language = '' ) => {
  23109. for ( let i = 0; i < includes.length; i ++ ) {
  23110. const include = includes[ i ];
  23111. // TSL Function: glslFn, wgslFn
  23112. if ( typeof include === 'function' ) {
  23113. includes[ i ] = include.functionNode;
  23114. }
  23115. }
  23116. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23117. const fn = ( ...params ) => functionNode.call( ...params );
  23118. fn.functionNode = functionNode;
  23119. return fn;
  23120. };
  23121. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23122. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23123. /** @module ScriptableValueNode **/
  23124. /**
  23125. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23126. *
  23127. * @augments Node
  23128. */
  23129. class ScriptableValueNode extends Node {
  23130. static get type() {
  23131. return 'ScriptableValueNode';
  23132. }
  23133. /**
  23134. * Constructs a new scriptable node.
  23135. *
  23136. * @param {Any} [value=null] - The value.
  23137. */
  23138. constructor( value = null ) {
  23139. super();
  23140. /**
  23141. * A reference to the value.
  23142. *
  23143. * @private
  23144. * @default null
  23145. */
  23146. this._value = value;
  23147. /**
  23148. * Depending on the type of `_value`, this property might cache parsed data.
  23149. *
  23150. * @private
  23151. * @default null
  23152. */
  23153. this._cache = null;
  23154. /**
  23155. * If this node represents an input, this property represents the input type.
  23156. *
  23157. * @type {String?}
  23158. * @default null
  23159. */
  23160. this.inputType = null;
  23161. /**
  23162. * If this node represents an output, this property represents the output type.
  23163. *
  23164. * @type {String?}
  23165. * @default null
  23166. */
  23167. this.outputType = null;
  23168. /**
  23169. * An event dispatcher for managing events.
  23170. *
  23171. * @type {EventDispatcher}
  23172. */
  23173. this.events = new EventDispatcher();
  23174. /**
  23175. * This flag can be used for type testing.
  23176. *
  23177. * @type {Boolean}
  23178. * @readonly
  23179. * @default true
  23180. */
  23181. this.isScriptableValueNode = true;
  23182. }
  23183. /**
  23184. * Whether this node represents an output or not.
  23185. *
  23186. * @type {Boolean}
  23187. * @readonly
  23188. * @default true
  23189. */
  23190. get isScriptableOutputNode() {
  23191. return this.outputType !== null;
  23192. }
  23193. set value( val ) {
  23194. if ( this._value === val ) return;
  23195. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23196. URL.revokeObjectURL( this._cache );
  23197. this._cache = null;
  23198. }
  23199. this._value = val;
  23200. this.events.dispatchEvent( { type: 'change' } );
  23201. this.refresh();
  23202. }
  23203. /**
  23204. * The node's value.
  23205. *
  23206. * @type {Any}
  23207. */
  23208. get value() {
  23209. return this._value;
  23210. }
  23211. /**
  23212. * Dispatches the `refresh` event.
  23213. */
  23214. refresh() {
  23215. this.events.dispatchEvent( { type: 'refresh' } );
  23216. }
  23217. /**
  23218. * The `value` property usually represents a node or even binary data in form of array buffers.
  23219. * In this case, this method tries to return the actual value behind the complex type.
  23220. *
  23221. * @return {Any} The value.
  23222. */
  23223. getValue() {
  23224. const value = this.value;
  23225. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23226. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23227. } else if ( value && value.value !== null && value.value !== undefined && (
  23228. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23229. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23230. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23231. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23232. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23233. ( this.inputType === 'Color' && value.value.isColor ) ||
  23234. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23235. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23236. ) ) {
  23237. return value.value;
  23238. }
  23239. return this._cache || value;
  23240. }
  23241. /**
  23242. * Overwritten since the node type is inferred from the value.
  23243. *
  23244. * @param {NodeBuilder} builder - The current node builder.
  23245. * @return {String} The node type.
  23246. */
  23247. getNodeType( builder ) {
  23248. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23249. }
  23250. setup() {
  23251. return this.value && this.value.isNode ? this.value : float();
  23252. }
  23253. serialize( data ) {
  23254. super.serialize( data );
  23255. if ( this.value !== null ) {
  23256. if ( this.inputType === 'ArrayBuffer' ) {
  23257. data.value = arrayBufferToBase64( this.value );
  23258. } else {
  23259. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23260. }
  23261. } else {
  23262. data.value = null;
  23263. }
  23264. data.inputType = this.inputType;
  23265. data.outputType = this.outputType;
  23266. }
  23267. deserialize( data ) {
  23268. super.deserialize( data );
  23269. let value = null;
  23270. if ( data.value !== null ) {
  23271. if ( data.inputType === 'ArrayBuffer' ) {
  23272. value = base64ToArrayBuffer( data.value );
  23273. } else if ( data.inputType === 'Texture' ) {
  23274. value = data.meta.textures[ data.value ];
  23275. } else {
  23276. value = data.meta.nodes[ data.value ] || null;
  23277. }
  23278. }
  23279. this.value = value;
  23280. this.inputType = data.inputType;
  23281. this.outputType = data.outputType;
  23282. }
  23283. }
  23284. /**
  23285. * TSL function for creating a scriptable value node.
  23286. *
  23287. * @function
  23288. * @param {Any} [value=null] - The value.
  23289. * @returns {ScriptableValueNode}
  23290. */
  23291. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23292. /** @module ScriptableNode **/
  23293. /**
  23294. * A Map-like data structure for managing resources of scriptable nodes.
  23295. *
  23296. * @augments Map
  23297. */
  23298. class Resources extends Map {
  23299. get( key, callback = null, ...params ) {
  23300. if ( this.has( key ) ) return super.get( key );
  23301. if ( callback !== null ) {
  23302. const value = callback( ...params );
  23303. this.set( key, value );
  23304. return value;
  23305. }
  23306. }
  23307. }
  23308. class Parameters {
  23309. constructor( scriptableNode ) {
  23310. this.scriptableNode = scriptableNode;
  23311. }
  23312. get parameters() {
  23313. return this.scriptableNode.parameters;
  23314. }
  23315. get layout() {
  23316. return this.scriptableNode.getLayout();
  23317. }
  23318. getInputLayout( id ) {
  23319. return this.scriptableNode.getInputLayout( id );
  23320. }
  23321. get( name ) {
  23322. const param = this.parameters[ name ];
  23323. const value = param ? param.getValue() : null;
  23324. return value;
  23325. }
  23326. }
  23327. /**
  23328. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23329. *
  23330. * @type {Resources}
  23331. */
  23332. const ScriptableNodeResources = new Resources();
  23333. /**
  23334. * This type of node allows to implement nodes with custom scripts. The script
  23335. * section is represented as an instance of `CodeNode` written with JavaScript.
  23336. * The script itself must adhere to a specific structure.
  23337. *
  23338. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23339. * - layout: The layout object defines the script's interface (inputs and outputs).
  23340. *
  23341. * ```js
  23342. * ScriptableNodeResources.set( 'TSL', TSL );
  23343. *
  23344. * const scriptableNode = scriptable( js( `
  23345. * layout = {
  23346. * outputType: 'node',
  23347. * elements: [
  23348. * { name: 'source', inputType: 'node' },
  23349. * ]
  23350. * };
  23351. *
  23352. * const { mul, oscSine } = TSL;
  23353. *
  23354. * function main() {
  23355. * const source = parameters.get( 'source' ) || float();
  23356. * return mul( source, oscSine() ) );
  23357. * }
  23358. *
  23359. * ` ) );
  23360. *
  23361. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23362. *
  23363. * const material = new THREE.MeshBasicNodeMaterial();
  23364. * material.colorNode = scriptableNode;
  23365. * ```
  23366. *
  23367. * @augments Node
  23368. */
  23369. class ScriptableNode extends Node {
  23370. static get type() {
  23371. return 'ScriptableNode';
  23372. }
  23373. /**
  23374. * Constructs a new scriptable node.
  23375. *
  23376. * @param {CodeNode?} [codeNode=null] - The code node.
  23377. * @param {Object} [parameters={}] - The parameters definition.
  23378. */
  23379. constructor( codeNode = null, parameters = {} ) {
  23380. super();
  23381. /**
  23382. * The code node.
  23383. *
  23384. * @type {CodeNode?}
  23385. * @default null
  23386. */
  23387. this.codeNode = codeNode;
  23388. /**
  23389. * The parameters definition.
  23390. *
  23391. * @type {Object}
  23392. * @default {}
  23393. */
  23394. this.parameters = parameters;
  23395. this._local = new Resources();
  23396. this._output = scriptableValue();
  23397. this._outputs = {};
  23398. this._source = this.source;
  23399. this._method = null;
  23400. this._object = null;
  23401. this._value = null;
  23402. this._needsOutputUpdate = true;
  23403. this.onRefresh = this.onRefresh.bind( this );
  23404. /**
  23405. * This flag can be used for type testing.
  23406. *
  23407. * @type {Boolean}
  23408. * @readonly
  23409. * @default true
  23410. */
  23411. this.isScriptableNode = true;
  23412. }
  23413. /**
  23414. * The source code of the scriptable node.
  23415. *
  23416. * @type {String}
  23417. */
  23418. get source() {
  23419. return this.codeNode ? this.codeNode.code : '';
  23420. }
  23421. /**
  23422. * Sets the reference of a local script variable.
  23423. *
  23424. * @param {String} name - The variable name.
  23425. * @param {Object} value - The reference to set.
  23426. * @return {Resources} The resource map
  23427. */
  23428. setLocal( name, value ) {
  23429. return this._local.set( name, value );
  23430. }
  23431. /**
  23432. * Gets the value of a local script variable.
  23433. *
  23434. * @param {String} name - The variable name.
  23435. * @return {Object} The value.
  23436. */
  23437. getLocal( name ) {
  23438. return this._local.get( name );
  23439. }
  23440. /**
  23441. * Event listener for the `refresh` event.
  23442. */
  23443. onRefresh() {
  23444. this._refresh();
  23445. }
  23446. /**
  23447. * Returns an input from the layout with the given id/name.
  23448. *
  23449. * @param {String} id - The id/name of the input.
  23450. * @return {Object} The element entry.
  23451. */
  23452. getInputLayout( id ) {
  23453. for ( const element of this.getLayout() ) {
  23454. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23455. return element;
  23456. }
  23457. }
  23458. }
  23459. /**
  23460. * Returns an output from the layout with the given id/name.
  23461. *
  23462. * @param {String} id - The id/name of the output.
  23463. * @return {Object} The element entry.
  23464. */
  23465. getOutputLayout( id ) {
  23466. for ( const element of this.getLayout() ) {
  23467. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23468. return element;
  23469. }
  23470. }
  23471. }
  23472. /**
  23473. * Defines a script output for the given name and value.
  23474. *
  23475. * @param {String} name - The name of the output.
  23476. * @param {Node} value - The node value.
  23477. * @return {ScriptableNode} A reference to this node.
  23478. */
  23479. setOutput( name, value ) {
  23480. const outputs = this._outputs;
  23481. if ( outputs[ name ] === undefined ) {
  23482. outputs[ name ] = scriptableValue( value );
  23483. } else {
  23484. outputs[ name ].value = value;
  23485. }
  23486. return this;
  23487. }
  23488. /**
  23489. * Returns a script output for the given name.
  23490. *
  23491. * @param {String} name - The name of the output.
  23492. * @return {ScriptableValueNode} The node value.
  23493. */
  23494. getOutput( name ) {
  23495. return this._outputs[ name ];
  23496. }
  23497. /**
  23498. * Returns a parameter for the given name
  23499. *
  23500. * @param {String} name - The name of the parameter.
  23501. * @return {ScriptableValueNode} The node value.
  23502. */
  23503. getParameter( name ) {
  23504. return this.parameters[ name ];
  23505. }
  23506. /**
  23507. * Sets a value for the given parameter name.
  23508. *
  23509. * @param {String} name - The parameter name.
  23510. * @param {Any} value - The parameter value.
  23511. * @return {ScriptableNode} A reference to this node.
  23512. */
  23513. setParameter( name, value ) {
  23514. const parameters = this.parameters;
  23515. if ( value && value.isScriptableNode ) {
  23516. this.deleteParameter( name );
  23517. parameters[ name ] = value;
  23518. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23519. } else if ( value && value.isScriptableValueNode ) {
  23520. this.deleteParameter( name );
  23521. parameters[ name ] = value;
  23522. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23523. } else if ( parameters[ name ] === undefined ) {
  23524. parameters[ name ] = scriptableValue( value );
  23525. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23526. } else {
  23527. parameters[ name ].value = value;
  23528. }
  23529. return this;
  23530. }
  23531. /**
  23532. * Returns the value of this node which is the value of
  23533. * the default output.
  23534. *
  23535. * @return {Node} The value.
  23536. */
  23537. getValue() {
  23538. return this.getDefaultOutput().getValue();
  23539. }
  23540. /**
  23541. * Deletes a parameter from the script.
  23542. *
  23543. * @param {String} name - The parameter to remove.
  23544. * @return {ScriptableNode} A reference to this node.
  23545. */
  23546. deleteParameter( name ) {
  23547. let valueNode = this.parameters[ name ];
  23548. if ( valueNode ) {
  23549. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23550. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23551. }
  23552. return this;
  23553. }
  23554. /**
  23555. * Deletes all parameters from the script.
  23556. *
  23557. * @return {ScriptableNode} A reference to this node.
  23558. */
  23559. clearParameters() {
  23560. for ( const name of Object.keys( this.parameters ) ) {
  23561. this.deleteParameter( name );
  23562. }
  23563. this.needsUpdate = true;
  23564. return this;
  23565. }
  23566. /**
  23567. * Calls a function from the script.
  23568. *
  23569. * @param {String} name - The function name.
  23570. * @param {...Any} params - A list of parameters.
  23571. * @return {Any} The result of the function call.
  23572. */
  23573. call( name, ...params ) {
  23574. const object = this.getObject();
  23575. const method = object[ name ];
  23576. if ( typeof method === 'function' ) {
  23577. return method( ...params );
  23578. }
  23579. }
  23580. /**
  23581. * Asynchronously calls a function from the script.
  23582. *
  23583. * @param {String} name - The function name.
  23584. * @param {...Any} params - A list of parameters.
  23585. * @return {Promise<Any>} The result of the function call.
  23586. */
  23587. async callAsync( name, ...params ) {
  23588. const object = this.getObject();
  23589. const method = object[ name ];
  23590. if ( typeof method === 'function' ) {
  23591. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23592. }
  23593. }
  23594. /**
  23595. * Overwritten since the node types is inferred from the script's output.
  23596. *
  23597. * @param {NodeBuilder} builder - The current node builder
  23598. * @return {String} The node type.
  23599. */
  23600. getNodeType( builder ) {
  23601. return this.getDefaultOutputNode().getNodeType( builder );
  23602. }
  23603. /**
  23604. * Refreshes the script node.
  23605. *
  23606. * @param {String?} [output=null] - An optional output.
  23607. */
  23608. refresh( output = null ) {
  23609. if ( output !== null ) {
  23610. this.getOutput( output ).refresh();
  23611. } else {
  23612. this._refresh();
  23613. }
  23614. }
  23615. /**
  23616. * Returns an object representation of the script.
  23617. *
  23618. * @return {Object} The result object.
  23619. */
  23620. getObject() {
  23621. if ( this.needsUpdate ) this.dispose();
  23622. if ( this._object !== null ) return this._object;
  23623. //
  23624. const refresh = () => this.refresh();
  23625. const setOutput = ( id, value ) => this.setOutput( id, value );
  23626. const parameters = new Parameters( this );
  23627. const THREE = ScriptableNodeResources.get( 'THREE' );
  23628. const TSL = ScriptableNodeResources.get( 'TSL' );
  23629. const method = this.getMethod();
  23630. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23631. this._object = method( ...params );
  23632. const layout = this._object.layout;
  23633. if ( layout ) {
  23634. if ( layout.cache === false ) {
  23635. this._local.clear();
  23636. }
  23637. // default output
  23638. this._output.outputType = layout.outputType || null;
  23639. if ( Array.isArray( layout.elements ) ) {
  23640. for ( const element of layout.elements ) {
  23641. const id = element.id || element.name;
  23642. if ( element.inputType ) {
  23643. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23644. this.getParameter( id ).inputType = element.inputType;
  23645. }
  23646. if ( element.outputType ) {
  23647. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23648. this.getOutput( id ).outputType = element.outputType;
  23649. }
  23650. }
  23651. }
  23652. }
  23653. return this._object;
  23654. }
  23655. deserialize( data ) {
  23656. super.deserialize( data );
  23657. for ( const name in this.parameters ) {
  23658. let valueNode = this.parameters[ name ];
  23659. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23660. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23661. }
  23662. }
  23663. /**
  23664. * Returns the layout of the script.
  23665. *
  23666. * @return {Object} The script's layout.
  23667. */
  23668. getLayout() {
  23669. return this.getObject().layout;
  23670. }
  23671. /**
  23672. * Returns default node output of the script.
  23673. *
  23674. * @return {Node} The default node output.
  23675. */
  23676. getDefaultOutputNode() {
  23677. const output = this.getDefaultOutput().value;
  23678. if ( output && output.isNode ) {
  23679. return output;
  23680. }
  23681. return float();
  23682. }
  23683. /**
  23684. * Returns default output of the script.
  23685. *
  23686. * @return {ScriptableValueNode} The default output.
  23687. */
  23688. getDefaultOutput() {
  23689. return this._exec()._output;
  23690. }
  23691. /**
  23692. * Returns a function created from the node's script.
  23693. *
  23694. * @return {Function} The function representing the node's code.
  23695. */
  23696. getMethod() {
  23697. if ( this.needsUpdate ) this.dispose();
  23698. if ( this._method !== null ) return this._method;
  23699. //
  23700. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23701. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23702. const properties = interfaceProps.join( ', ' );
  23703. const declarations = 'var ' + properties + '; var output = {};\n';
  23704. const returns = '\nreturn { ...output, ' + properties + ' };';
  23705. const code = declarations + this.codeNode.code + returns;
  23706. //
  23707. this._method = new Function( ...parametersProps, code );
  23708. return this._method;
  23709. }
  23710. /**
  23711. * Frees all internal resources.
  23712. */
  23713. dispose() {
  23714. if ( this._method === null ) return;
  23715. if ( this._object && typeof this._object.dispose === 'function' ) {
  23716. this._object.dispose();
  23717. }
  23718. this._method = null;
  23719. this._object = null;
  23720. this._source = null;
  23721. this._value = null;
  23722. this._needsOutputUpdate = true;
  23723. this._output.value = null;
  23724. this._outputs = {};
  23725. }
  23726. setup() {
  23727. return this.getDefaultOutputNode();
  23728. }
  23729. getCacheKey( force ) {
  23730. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23731. for ( const param in this.parameters ) {
  23732. values.push( this.parameters[ param ].getCacheKey( force ) );
  23733. }
  23734. return hashArray( values );
  23735. }
  23736. set needsUpdate( value ) {
  23737. if ( value === true ) this.dispose();
  23738. }
  23739. get needsUpdate() {
  23740. return this.source !== this._source;
  23741. }
  23742. /**
  23743. * Executes the `main` function of the script.
  23744. *
  23745. * @private
  23746. * @return {ScriptableNode} A reference to this node.
  23747. */
  23748. _exec() {
  23749. if ( this.codeNode === null ) return this;
  23750. if ( this._needsOutputUpdate === true ) {
  23751. this._value = this.call( 'main' );
  23752. this._needsOutputUpdate = false;
  23753. }
  23754. this._output.value = this._value;
  23755. return this;
  23756. }
  23757. /**
  23758. * Executes the refresh.
  23759. *
  23760. * @private
  23761. */
  23762. _refresh() {
  23763. this.needsUpdate = true;
  23764. this._exec();
  23765. this._output.refresh();
  23766. }
  23767. }
  23768. /**
  23769. * TSL function for creating a scriptable node.
  23770. *
  23771. * @function
  23772. * @param {CodeNode?} [codeNode=null] - The code node.
  23773. * @param {Object} [parameters={}] - The parameters definition.
  23774. * @returns {ScriptableNode}
  23775. */
  23776. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23777. /** @module Fog **/
  23778. /**
  23779. * Returns a node that represents the `z` coordinate in view space
  23780. * for the current fragment. It's a different representation of the
  23781. * default depth value.
  23782. *
  23783. * This value can be part of a computation that defines how the fog
  23784. * density increases when moving away from the camera.
  23785. *
  23786. * @param {NodeBuilder} builder - The current node builder.
  23787. * @return {Node} The viewZ node.
  23788. */
  23789. function getViewZNode( builder ) {
  23790. let viewZ;
  23791. const getViewZ = builder.context.getViewZ;
  23792. if ( getViewZ !== undefined ) {
  23793. viewZ = getViewZ( this );
  23794. }
  23795. return ( viewZ || positionView.z ).negate();
  23796. }
  23797. /**
  23798. * Constructs a new range factor node.
  23799. *
  23800. * @function
  23801. * @param {Node} near - Defines the near value.
  23802. * @param {Node} far - Defines the far value.
  23803. */
  23804. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23805. const viewZ = getViewZNode( builder );
  23806. return smoothstep( near, far, viewZ );
  23807. } );
  23808. /**
  23809. * Represents an exponential squared fog. This type of fog gives
  23810. * a clear view near the camera and a faster than exponentially
  23811. * densening fog farther from the camera.
  23812. *
  23813. * @function
  23814. * @param {Node} density - Defines the fog density.
  23815. */
  23816. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23817. const viewZ = getViewZNode( builder );
  23818. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23819. } );
  23820. /**
  23821. * This class can be used to configure a fog for the scene.
  23822. * Nodes of this type are assigned to `Scene.fogNode`.
  23823. *
  23824. * @function
  23825. * @param {Node} color - Defines the color of the fog.
  23826. * @param {Node} factor - Defines how the fog is factored in the scene.
  23827. */
  23828. const fog = Fn( ( [ color, factor ] ) => {
  23829. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23830. } );
  23831. // Deprecated
  23832. /**
  23833. * @function
  23834. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  23835. *
  23836. * @param {Node} color
  23837. * @param {Node} near
  23838. * @param {Node} far
  23839. * @returns {Function}
  23840. */
  23841. function rangeFog( color, near, far ) { // @deprecated, r171
  23842. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23843. return fog( color, rangeFogFactor( near, far ) );
  23844. }
  23845. /**
  23846. * @function
  23847. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  23848. *
  23849. * @param {Node} color
  23850. * @param {Node} density
  23851. * @returns {Function}
  23852. */
  23853. function densityFog( color, density ) { // @deprecated, r171
  23854. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23855. return fog( color, densityFogFactor( density ) );
  23856. }
  23857. /** @module RangeNode **/
  23858. let min = null;
  23859. let max = null;
  23860. /**
  23861. * `RangeNode` generates random instanced attribute data in a defined range.
  23862. * An exemplary use case for this utility node is to generate random per-instance
  23863. * colors:
  23864. * ```js
  23865. * const material = new MeshBasicNodeMaterial();
  23866. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23867. * const mesh = new InstancedMesh( geometry, material, count );
  23868. * ```
  23869. * @augments Node
  23870. */
  23871. class RangeNode extends Node {
  23872. static get type() {
  23873. return 'RangeNode';
  23874. }
  23875. /**
  23876. * Constructs a new range node.
  23877. *
  23878. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23879. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23880. */
  23881. constructor( minNode = float(), maxNode = float() ) {
  23882. super();
  23883. /**
  23884. * A node defining the lower bound of the range.
  23885. *
  23886. * @type {Node<any>}
  23887. * @default float()
  23888. */
  23889. this.minNode = minNode;
  23890. /**
  23891. * A node defining the upper bound of the range.
  23892. *
  23893. * @type {Node<any>}
  23894. * @default float()
  23895. */
  23896. this.maxNode = maxNode;
  23897. }
  23898. /**
  23899. * Returns the vector length which is computed based on the range definition.
  23900. *
  23901. * @param {NodeBuilder} builder - The current node builder.
  23902. * @return {Number} The vector length.
  23903. */
  23904. getVectorLength( builder ) {
  23905. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23906. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23907. return minLength > maxLength ? minLength : maxLength;
  23908. }
  23909. /**
  23910. * This method is overwritten since the node type is inferred from range definition.
  23911. *
  23912. * @param {NodeBuilder} builder - The current node builder.
  23913. * @return {String} The node type.
  23914. */
  23915. getNodeType( builder ) {
  23916. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23917. }
  23918. setup( builder ) {
  23919. const object = builder.object;
  23920. let output = null;
  23921. if ( object.count > 1 ) {
  23922. const minValue = this.minNode.value;
  23923. const maxValue = this.maxNode.value;
  23924. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23925. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23926. min = min || new Vector4();
  23927. max = max || new Vector4();
  23928. min.setScalar( 0 );
  23929. max.setScalar( 0 );
  23930. if ( minLength === 1 ) min.setScalar( minValue );
  23931. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23932. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23933. if ( maxLength === 1 ) max.setScalar( maxValue );
  23934. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23935. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23936. const stride = 4;
  23937. const length = stride * object.count;
  23938. const array = new Float32Array( length );
  23939. for ( let i = 0; i < length; i ++ ) {
  23940. const index = i % stride;
  23941. const minElementValue = min.getComponent( index );
  23942. const maxElementValue = max.getComponent( index );
  23943. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23944. }
  23945. const nodeType = this.getNodeType( builder );
  23946. if ( object.count <= 4096 ) {
  23947. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23948. } else {
  23949. // TODO: Improve anonymous buffer attribute creation removing this part
  23950. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23951. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23952. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23953. }
  23954. } else {
  23955. output = float( 0 );
  23956. }
  23957. return output;
  23958. }
  23959. }
  23960. /**
  23961. * TSL function for creating a range node.
  23962. *
  23963. * @function
  23964. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23965. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23966. * @returns {RangeNode}
  23967. */
  23968. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23969. /** @module ComputeBuiltinNode **/
  23970. /**
  23971. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23972. * about the currently running dispatch and/or the device it is running on.
  23973. *
  23974. * This node can only be used with a WebGPU backend.
  23975. *
  23976. * @augments Node
  23977. */
  23978. class ComputeBuiltinNode extends Node {
  23979. static get type() {
  23980. return 'ComputeBuiltinNode';
  23981. }
  23982. /**
  23983. * Constructs a new compute builtin node.
  23984. *
  23985. * @param {String} builtinName - The built-in name.
  23986. * @param {String} nodeType - The node type.
  23987. */
  23988. constructor( builtinName, nodeType ) {
  23989. super( nodeType );
  23990. /**
  23991. * The built-in name.
  23992. *
  23993. * @private
  23994. * @type {String}
  23995. */
  23996. this._builtinName = builtinName;
  23997. }
  23998. /**
  23999. * This method is overwritten since hash is derived from the built-in name.
  24000. *
  24001. * @param {NodeBuilder} builder - The current node builder.
  24002. * @return {String} The hash.
  24003. */
  24004. getHash( builder ) {
  24005. return this.getBuiltinName( builder );
  24006. }
  24007. /**
  24008. * This method is overwritten since the node type is simply derived from `nodeType`..
  24009. *
  24010. * @param {NodeBuilder} builder - The current node builder.
  24011. * @return {String} The node type.
  24012. */
  24013. getNodeType( /*builder*/ ) {
  24014. return this.nodeType;
  24015. }
  24016. /**
  24017. * Sets the builtin name.
  24018. *
  24019. * @param {String} builtinName - The built-in name.
  24020. * @return {ComputeBuiltinNode} A reference to this node.
  24021. */
  24022. setBuiltinName( builtinName ) {
  24023. this._builtinName = builtinName;
  24024. return this;
  24025. }
  24026. /**
  24027. * Returns the builtin name.
  24028. *
  24029. * @param {NodeBuilder} builder - The current node builder.
  24030. * @return {String} The builtin name.
  24031. */
  24032. getBuiltinName( /*builder*/ ) {
  24033. return this._builtinName;
  24034. }
  24035. /**
  24036. * Whether the current node builder has the builtin or not.
  24037. *
  24038. * @param {NodeBuilder} builder - The current node builder.
  24039. */
  24040. hasBuiltin( builder ) {
  24041. builder.hasBuiltin( this._builtinName );
  24042. }
  24043. generate( builder, output ) {
  24044. const builtinName = this.getBuiltinName( builder );
  24045. const nodeType = this.getNodeType( builder );
  24046. if ( builder.shaderStage === 'compute' ) {
  24047. return builder.format( builtinName, nodeType, output );
  24048. } else {
  24049. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  24050. return builder.generateConst( nodeType );
  24051. }
  24052. }
  24053. serialize( data ) {
  24054. super.serialize( data );
  24055. data.global = this.global;
  24056. data._builtinName = this._builtinName;
  24057. }
  24058. deserialize( data ) {
  24059. super.deserialize( data );
  24060. this.global = data.global;
  24061. this._builtinName = data._builtinName;
  24062. }
  24063. }
  24064. /**
  24065. * TSL function for creating a compute builtin node.
  24066. *
  24067. * @function
  24068. * @param {String} name - The built-in name.
  24069. * @param {String} nodeType - The node type.
  24070. * @returns {ComputeBuiltinNode}
  24071. */
  24072. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  24073. /**
  24074. * TSL function for creating a `numWorkgroups` builtin node.
  24075. * Represents the number of workgroups dispatched by the compute shader.
  24076. * ```js
  24077. * // Run 512 invocations/threads with a workgroup size of 128.
  24078. * const computeFn = Fn(() => {
  24079. *
  24080. * // numWorkgroups.x = 4
  24081. * storageBuffer.element(0).assign(numWorkgroups.x)
  24082. *
  24083. * })().compute(512, [128]);
  24084. *
  24085. * // Run 512 invocations/threads with the default workgroup size of 64.
  24086. * const computeFn = Fn(() => {
  24087. *
  24088. * // numWorkgroups.x = 8
  24089. * storageBuffer.element(0).assign(numWorkgroups.x)
  24090. *
  24091. * })().compute(512);
  24092. * ```
  24093. *
  24094. * @function
  24095. * @returns {ComputeBuiltinNode<uvec3>}
  24096. */
  24097. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  24098. /**
  24099. * TSL function for creating a `workgroupId` builtin node.
  24100. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  24101. * ```js
  24102. * // Execute 12 compute threads with a workgroup size of 3.
  24103. * const computeFn = Fn( () => {
  24104. *
  24105. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  24106. *
  24107. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  24108. *
  24109. * } ).Else( () => {
  24110. *
  24111. * storageBuffer.element( instanceIndex ).assign( 0 );
  24112. *
  24113. * } );
  24114. *
  24115. * } )().compute( 12, [ 3 ] );
  24116. *
  24117. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24118. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24119. * ```
  24120. *
  24121. * @function
  24122. * @returns {ComputeBuiltinNode<uvec3>}
  24123. */
  24124. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24125. /**
  24126. * TSL function for creating a `globalId` builtin node. A non-linearized 3-dimensional
  24127. * representation of the current invocation's position within a 3D global grid.
  24128. *
  24129. * @function
  24130. * @returns {ComputeBuiltinNode<uvec3>}
  24131. */
  24132. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24133. /**
  24134. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  24135. * representation of the current invocation's position within a 3D workgroup grid.
  24136. *
  24137. * @function
  24138. * @returns {ComputeBuiltinNode<uvec3>}
  24139. */
  24140. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24141. /**
  24142. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  24143. * that exposes the size of the current invocation's subgroup.
  24144. *
  24145. * @function
  24146. * @returns {ComputeBuiltinNode<uint>}
  24147. */
  24148. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24149. /** @module BarrierNode **/
  24150. /**
  24151. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24152. *
  24153. * This node can only be used with a WebGPU backend.
  24154. *
  24155. * @augments Node
  24156. */
  24157. class BarrierNode extends Node {
  24158. /**
  24159. * Constructs a new barrier node.
  24160. *
  24161. * @param {String} scope - The scope defines the behavior of the node.
  24162. */
  24163. constructor( scope ) {
  24164. super();
  24165. this.scope = scope;
  24166. }
  24167. generate( builder ) {
  24168. const { scope } = this;
  24169. const { renderer } = builder;
  24170. if ( renderer.backend.isWebGLBackend === true ) {
  24171. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24172. } else {
  24173. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24174. }
  24175. }
  24176. }
  24177. /**
  24178. * TSL function for creating a barrier node.
  24179. *
  24180. * @function
  24181. * @param {String} scope - The scope defines the behavior of the node..
  24182. * @returns {BarrierNode}
  24183. */
  24184. const barrier = nodeProxy( BarrierNode );
  24185. /**
  24186. * TSL function for creating a workgroup barrier. All compute shader
  24187. * invocations must wait for each invocation within a workgroup to
  24188. * complete before the barrier can be surpassed.
  24189. *
  24190. * @function
  24191. * @returns {BarrierNode}
  24192. */
  24193. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24194. /**
  24195. * TSL function for creating a storage barrier. All invocations must
  24196. * wait for each access to variables within the 'storage' address space
  24197. * to complete before the barrier can be passed.
  24198. *
  24199. * @function
  24200. * @returns {BarrierNode}
  24201. */
  24202. const storageBarrier = () => barrier( 'storage' ).append();
  24203. /**
  24204. * TSL function for creating a texture barrier. All invocations must
  24205. * wait for each access to variables within the 'texture' address space
  24206. * to complete before the barrier can be passed.
  24207. *
  24208. * @function
  24209. * @returns {BarrierNode}
  24210. */
  24211. const textureBarrier = () => barrier( 'texture' ).append();
  24212. /** @module WorkgroupInfoNode **/
  24213. /**
  24214. * Represents an element of a 'workgroup' scoped buffer.
  24215. *
  24216. * @augments ArrayElementNode
  24217. */
  24218. class WorkgroupInfoElementNode extends ArrayElementNode {
  24219. /**
  24220. * Constructs a new workgroup info element node.
  24221. *
  24222. * @param {Node} workgroupInfoNode - The workgroup info node.
  24223. * @param {Node} indexNode - The index node that defines the element access.
  24224. */
  24225. constructor( workgroupInfoNode, indexNode ) {
  24226. super( workgroupInfoNode, indexNode );
  24227. /**
  24228. * This flag can be used for type testing.
  24229. *
  24230. * @type {Boolean}
  24231. * @readonly
  24232. * @default true
  24233. */
  24234. this.isWorkgroupInfoElementNode = true;
  24235. }
  24236. generate( builder, output ) {
  24237. let snippet;
  24238. const isAssignContext = builder.context.assign;
  24239. snippet = super.generate( builder );
  24240. if ( isAssignContext !== true ) {
  24241. const type = this.getNodeType( builder );
  24242. snippet = builder.format( snippet, type, output );
  24243. }
  24244. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24245. return snippet;
  24246. }
  24247. }
  24248. /**
  24249. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24250. * context of a compute shader. Typically, workgroup scoped buffers are
  24251. * created to hold data that is transferred from a global storage scope into
  24252. * a local workgroup scope. For invocations within a workgroup, data
  24253. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24254. * than similar access operations on globally accessible storage buffers.
  24255. *
  24256. * This node can only be used with a WebGPU backend.
  24257. *
  24258. * @augments Node
  24259. */
  24260. class WorkgroupInfoNode extends Node {
  24261. /**
  24262. * Constructs a new buffer scoped to type scope.
  24263. *
  24264. * @param {String} scope - TODO.
  24265. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  24266. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  24267. */
  24268. constructor( scope, bufferType, bufferCount = 0 ) {
  24269. super( bufferType );
  24270. /**
  24271. * The buffer type.
  24272. *
  24273. * @type {String}
  24274. */
  24275. this.bufferType = bufferType;
  24276. /**
  24277. * The buffer count.
  24278. *
  24279. * @type {Number}
  24280. * @default 0
  24281. */
  24282. this.bufferCount = bufferCount;
  24283. /**
  24284. * This flag can be used for type testing.
  24285. *
  24286. * @type {Boolean}
  24287. * @readonly
  24288. * @default true
  24289. */
  24290. this.isWorkgroupInfoNode = true;
  24291. /**
  24292. * The data type of the array buffer.
  24293. *
  24294. * @type {String}
  24295. */
  24296. this.elementType = bufferType;
  24297. /**
  24298. * TODO.
  24299. *
  24300. * @type {String}
  24301. */
  24302. this.scope = scope;
  24303. }
  24304. /**
  24305. * Sets the name/label of this node.
  24306. *
  24307. * @param {String} name - The name to set.
  24308. * @return {WorkgroupInfoNode} A reference to this node.
  24309. */
  24310. label( name ) {
  24311. this.name = name;
  24312. return this;
  24313. }
  24314. /**
  24315. * Sets the scope of this node.
  24316. *
  24317. * @param {String} scope - The scope to set.
  24318. * @return {WorkgroupInfoNode} A reference to this node.
  24319. */
  24320. setScope( scope ) {
  24321. this.scope = scope;
  24322. return this;
  24323. }
  24324. /**
  24325. * The data type of the array buffer.
  24326. *
  24327. * @return {String} The element type.
  24328. */
  24329. getElementType() {
  24330. return this.elementType;
  24331. }
  24332. /**
  24333. * Overwrites the default implementation since the input type
  24334. * is inferred from the scope.
  24335. *
  24336. * @param {NodeBuilder} builder - The current node builder.
  24337. * @return {String} The input type.
  24338. */
  24339. getInputType( /*builder*/ ) {
  24340. return `${this.scope}Array`;
  24341. }
  24342. /**
  24343. * This method can be used to access elements via an index node.
  24344. *
  24345. * @param {IndexNode} indexNode - indexNode.
  24346. * @return {WorkgroupInfoElementNode} A reference to an element.
  24347. */
  24348. element( indexNode ) {
  24349. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24350. }
  24351. generate( builder ) {
  24352. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24353. }
  24354. }
  24355. /**
  24356. * TSL function for creating a workgroup info node.
  24357. * Creates a new 'workgroup' scoped array buffer.
  24358. *
  24359. * @function
  24360. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  24361. * @param {Number} [count=0] - The number of elements in the buffer.
  24362. * @returns {WorkgroupInfoNode}
  24363. */
  24364. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24365. /** @module AtomicFunctionNode **/
  24366. /**
  24367. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24368. * within a shader. In an atomic function, any modification to an atomic variable will
  24369. * occur as an indivisible step with a defined order relative to other modifications.
  24370. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24371. * atomic operations will not interfere with each other.
  24372. *
  24373. * This node can only be used with a WebGPU backend.
  24374. *
  24375. * @augments TempNode
  24376. */
  24377. class AtomicFunctionNode extends TempNode {
  24378. static get type() {
  24379. return 'AtomicFunctionNode';
  24380. }
  24381. /**
  24382. * Constructs a new atomic function node.
  24383. *
  24384. * @param {String} method - The signature of the atomic function to construct.
  24385. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24386. * @param {Node} valueNode - The value that mutates the atomic variable.
  24387. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24388. */
  24389. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24390. super( 'uint' );
  24391. /**
  24392. * The signature of the atomic function to construct.
  24393. *
  24394. * @type {String}
  24395. */
  24396. this.method = method;
  24397. /**
  24398. * An atomic variable or element of an atomic buffer.
  24399. *
  24400. * @type {Node}
  24401. */
  24402. this.pointerNode = pointerNode;
  24403. /**
  24404. * A value that modifies the atomic variable.
  24405. *
  24406. * @type {Node}
  24407. */
  24408. this.valueNode = valueNode;
  24409. /**
  24410. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24411. *
  24412. * @type {Node?}
  24413. * @default null
  24414. */
  24415. this.storeNode = storeNode;
  24416. }
  24417. /**
  24418. * Overwrites the default implementation to return the type of
  24419. * the pointer node.
  24420. *
  24421. * @param {NodeBuilder} builder - The current node builder.
  24422. * @return {String} The input type.
  24423. */
  24424. getInputType( builder ) {
  24425. return this.pointerNode.getNodeType( builder );
  24426. }
  24427. /**
  24428. * Overwritten since the node type is inferred from the input type.
  24429. *
  24430. * @param {NodeBuilder} builder - The current node builder.
  24431. * @return {String} The node type.
  24432. */
  24433. getNodeType( builder ) {
  24434. return this.getInputType( builder );
  24435. }
  24436. generate( builder ) {
  24437. const method = this.method;
  24438. const type = this.getNodeType( builder );
  24439. const inputType = this.getInputType( builder );
  24440. const a = this.pointerNode;
  24441. const b = this.valueNode;
  24442. const params = [];
  24443. params.push( `&${ a.build( builder, inputType ) }` );
  24444. if ( b !== null ) {
  24445. params.push( b.build( builder, inputType ) );
  24446. }
  24447. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24448. if ( this.storeNode !== null ) {
  24449. const varSnippet = this.storeNode.build( builder, inputType );
  24450. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24451. } else {
  24452. builder.addLineFlowCode( methodSnippet, this );
  24453. }
  24454. }
  24455. }
  24456. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24457. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24458. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24459. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24460. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24461. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24462. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24463. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24464. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24465. /**
  24466. * TSL function for creating an atomic function node.
  24467. *
  24468. * @function
  24469. * @param {String} method - The signature of the atomic function to construct.
  24470. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24471. * @param {Node} valueNode - The value that mutates the atomic variable.
  24472. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24473. * @returns {AtomicFunctionNode}
  24474. */
  24475. const atomicNode = nodeProxy( AtomicFunctionNode );
  24476. /**
  24477. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24478. *
  24479. * @function
  24480. * @param {String} method - The signature of the atomic function to construct.
  24481. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24482. * @param {Node} valueNode - The value that mutates the atomic variable.
  24483. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24484. * @returns {AtomicFunctionNode}
  24485. */
  24486. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24487. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24488. node.append();
  24489. return node;
  24490. };
  24491. /**
  24492. * Loads the value stored in the atomic variable.
  24493. *
  24494. * @function
  24495. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24496. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24497. * @returns {AtomicFunctionNode}
  24498. */
  24499. const atomicLoad = ( pointerNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null, storeNode );
  24500. /**
  24501. * Stores a value in the atomic variable.
  24502. *
  24503. * @function
  24504. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24505. * @param {Node} valueNode - The value that mutates the atomic variable.
  24506. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24507. * @returns {AtomicFunctionNode}
  24508. */
  24509. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24510. /**
  24511. * Increments the value stored in the atomic variable.
  24512. *
  24513. * @function
  24514. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24515. * @param {Node} valueNode - The value that mutates the atomic variable.
  24516. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24517. * @returns {AtomicFunctionNode}
  24518. */
  24519. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24520. /**
  24521. * Decrements the value stored in the atomic variable.
  24522. *
  24523. * @function
  24524. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24525. * @param {Node} valueNode - The value that mutates the atomic variable.
  24526. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24527. * @returns {AtomicFunctionNode}
  24528. */
  24529. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24530. /**
  24531. * Stores in an atomic variable the maximum between its current value and a parameter.
  24532. *
  24533. * @function
  24534. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24535. * @param {Node} valueNode - The value that mutates the atomic variable.
  24536. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24537. * @returns {AtomicFunctionNode}
  24538. */
  24539. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24540. /**
  24541. * Stores in an atomic variable the minimum between its current value and a parameter.
  24542. *
  24543. * @function
  24544. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24545. * @param {Node} valueNode - The value that mutates the atomic variable.
  24546. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24547. * @returns {AtomicFunctionNode}
  24548. */
  24549. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24550. /**
  24551. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24552. *
  24553. * @function
  24554. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24555. * @param {Node} valueNode - The value that mutates the atomic variable.
  24556. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24557. * @returns {AtomicFunctionNode}
  24558. */
  24559. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24560. /**
  24561. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24562. *
  24563. * @function
  24564. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24565. * @param {Node} valueNode - The value that mutates the atomic variable.
  24566. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24567. * @returns {AtomicFunctionNode}
  24568. */
  24569. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24570. /**
  24571. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24572. *
  24573. * @function
  24574. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24575. * @param {Node} valueNode - The value that mutates the atomic variable.
  24576. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24577. * @returns {AtomicFunctionNode}
  24578. */
  24579. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24580. /** @module Lights **/
  24581. let uniformsLib;
  24582. function getLightData( light ) {
  24583. uniformsLib = uniformsLib || new WeakMap();
  24584. let uniforms = uniformsLib.get( light );
  24585. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24586. return uniforms;
  24587. }
  24588. /**
  24589. * TSL function for getting a shadow matrix uniform node for the given light.
  24590. *
  24591. * @function
  24592. * @param {Light} light -The light source.
  24593. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24594. */
  24595. function lightShadowMatrix( light ) {
  24596. const data = getLightData( light );
  24597. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24598. if ( light.castShadow !== true ) {
  24599. light.shadow.updateMatrices( light );
  24600. }
  24601. return light.shadow.matrix;
  24602. } ) );
  24603. }
  24604. /**
  24605. * TSL function for getting projected uv coordinates for the given light.
  24606. * Relevant when using maps with spot lights.
  24607. *
  24608. * @function
  24609. * @param {Light} light -The light source.
  24610. * @returns {Node<vec3>} The projected uvs.
  24611. */
  24612. function lightProjectionUV( light ) {
  24613. const data = getLightData( light );
  24614. if ( data.projectionUV === undefined ) {
  24615. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24616. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24617. }
  24618. return data.projectionUV;
  24619. }
  24620. /**
  24621. * TSL function for getting the position in world space for the given light.
  24622. *
  24623. * @function
  24624. * @param {Light} light -The light source.
  24625. * @returns {UniformNode<vec3>} The light's position in world space.
  24626. */
  24627. function lightPosition( light ) {
  24628. const data = getLightData( light );
  24629. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24630. }
  24631. /**
  24632. * TSL function for getting the light target position in world space for the given light.
  24633. *
  24634. * @function
  24635. * @param {Light} light -The light source.
  24636. * @returns {UniformNode<vec3>} The light target position in world space.
  24637. */
  24638. function lightTargetPosition( light ) {
  24639. const data = getLightData( light );
  24640. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24641. }
  24642. /**
  24643. * TSL function for getting the position in view space for the given light.
  24644. *
  24645. * @function
  24646. * @param {Light} light -The light source.
  24647. * @returns {UniformNode<vec3>} The light's position in view space.
  24648. */
  24649. function lightViewPosition( light ) {
  24650. const data = getLightData( light );
  24651. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24652. self.value = self.value || new Vector3();
  24653. self.value.setFromMatrixPosition( light.matrixWorld );
  24654. self.value.applyMatrix4( camera.matrixWorldInverse );
  24655. } ) );
  24656. }
  24657. /**
  24658. * TSL function for getting the light target direction for the given light.
  24659. *
  24660. * @function
  24661. * @param {Light} light -The light source.
  24662. * @returns {Node<vec3>} The light's target direction.
  24663. */
  24664. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24665. /** @module LightsNode **/
  24666. const sortLights = ( lights ) => {
  24667. return lights.sort( ( a, b ) => a.id - b.id );
  24668. };
  24669. const getLightNodeById = ( id, lightNodes ) => {
  24670. for ( const lightNode of lightNodes ) {
  24671. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24672. return lightNode;
  24673. }
  24674. }
  24675. return null;
  24676. };
  24677. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24678. /**
  24679. * This node represents the scene's lighting and manages the lighting model's life cycle
  24680. * for the current build 3D object. It is responsible for computing the total outgoing
  24681. * light in a given lighting context.
  24682. *
  24683. * @augments Node
  24684. */
  24685. class LightsNode extends Node {
  24686. static get type() {
  24687. return 'LightsNode';
  24688. }
  24689. /**
  24690. * Constructs a new lights node.
  24691. */
  24692. constructor() {
  24693. super( 'vec3' );
  24694. /**
  24695. * A node representing the total diffuse light.
  24696. *
  24697. * @type {Node<vec3>}
  24698. */
  24699. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24700. /**
  24701. * A node representing the total specular light.
  24702. *
  24703. * @type {Node<vec3>}
  24704. */
  24705. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24706. /**
  24707. * A node representing the outgoing light.
  24708. *
  24709. * @type {Node<vec3>}
  24710. */
  24711. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24712. /**
  24713. * An array representing the lights in the scene.
  24714. *
  24715. * @private
  24716. * @type {Array<Light>}
  24717. */
  24718. this._lights = [];
  24719. /**
  24720. * For each light in the scene, this node will create a
  24721. * corresponding light node.
  24722. *
  24723. * @private
  24724. * @type {Array<LightingNode>?}
  24725. * @default null
  24726. */
  24727. this._lightNodes = null;
  24728. /**
  24729. * A hash for identifying the current light nodes setup.
  24730. *
  24731. * @private
  24732. * @type {String?}
  24733. * @default null
  24734. */
  24735. this._lightNodesHash = null;
  24736. /**
  24737. * `LightsNode` sets this property to `true` by default.
  24738. *
  24739. * @type {Boolean}
  24740. * @default true
  24741. */
  24742. this.global = true;
  24743. }
  24744. /**
  24745. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24746. * light IDs into the cache key.
  24747. *
  24748. * @return {Number} The custom cache key.
  24749. */
  24750. customCacheKey() {
  24751. const lightIDs = [];
  24752. const lights = this._lights;
  24753. for ( let i = 0; i < lights.length; i ++ ) {
  24754. lightIDs.push( lights[ i ].id );
  24755. }
  24756. return hashArray( lightIDs );
  24757. }
  24758. /**
  24759. * Computes a hash value for identifying the current light nodes setup.
  24760. *
  24761. * @param {NodeBuilder} builder - A reference to the current node builder.
  24762. * @return {String} The computed hash.
  24763. */
  24764. getHash( builder ) {
  24765. if ( this._lightNodesHash === null ) {
  24766. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24767. const hash = [];
  24768. for ( const lightNode of this._lightNodes ) {
  24769. hash.push( lightNode.getSelf().getHash() );
  24770. }
  24771. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24772. }
  24773. return this._lightNodesHash;
  24774. }
  24775. analyze( builder ) {
  24776. const properties = builder.getDataFromNode( this );
  24777. for ( const node of properties.nodes ) {
  24778. node.build( builder );
  24779. }
  24780. }
  24781. /**
  24782. * Creates lighting nodes for each scene light. This makes it possible to further
  24783. * process lights in the node system.
  24784. *
  24785. * @param {NodeBuilder} builder - A reference to the current node builder.
  24786. */
  24787. setupLightsNode( builder ) {
  24788. const lightNodes = [];
  24789. const previousLightNodes = this._lightNodes;
  24790. const lights = sortLights( this._lights );
  24791. const nodeLibrary = builder.renderer.library;
  24792. for ( const light of lights ) {
  24793. if ( light.isNode ) {
  24794. lightNodes.push( nodeObject( light ) );
  24795. } else {
  24796. let lightNode = null;
  24797. if ( previousLightNodes !== null ) {
  24798. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24799. }
  24800. if ( lightNode === null ) {
  24801. // find the corresponding node type for a given light
  24802. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24803. if ( lightNodeClass === null ) {
  24804. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24805. continue;
  24806. }
  24807. let lightNode = null;
  24808. if ( ! _lightsNodeRef.has( light ) ) {
  24809. lightNode = nodeObject( new lightNodeClass( light ) );
  24810. _lightsNodeRef.set( light, lightNode );
  24811. } else {
  24812. lightNode = _lightsNodeRef.get( light );
  24813. }
  24814. lightNodes.push( lightNode );
  24815. }
  24816. }
  24817. }
  24818. this._lightNodes = lightNodes;
  24819. }
  24820. /**
  24821. * Setups the internal lights by building all respective
  24822. * light nodes.
  24823. *
  24824. * @param {NodeBuilder} builder - A reference to the current node builder.
  24825. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24826. */
  24827. setupLights( builder, lightNodes ) {
  24828. for ( const lightNode of lightNodes ) {
  24829. lightNode.build( builder );
  24830. }
  24831. }
  24832. /**
  24833. * The implementation makes sure that for each light in the scene
  24834. * there is a corresponding light node. By building the light nodes
  24835. * and evaluating the lighting model the outgoing light is computed.
  24836. *
  24837. * @param {NodeBuilder} builder - A reference to the current node builder.
  24838. * @return {Node<vec3>} A node representing the outgoing light.
  24839. */
  24840. setup( builder ) {
  24841. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24842. const context = builder.context;
  24843. const lightingModel = context.lightingModel;
  24844. let outgoingLightNode = this.outgoingLightNode;
  24845. if ( lightingModel ) {
  24846. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24847. context.outgoingLight = outgoingLightNode;
  24848. const stack = builder.addStack();
  24849. //
  24850. const properties = builder.getDataFromNode( this );
  24851. properties.nodes = stack.nodes;
  24852. //
  24853. lightingModel.start( context, stack, builder );
  24854. // lights
  24855. this.setupLights( builder, _lightNodes );
  24856. //
  24857. lightingModel.indirect( context, stack, builder );
  24858. //
  24859. const { backdrop, backdropAlpha } = context;
  24860. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24861. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24862. if ( backdrop !== null ) {
  24863. if ( backdropAlpha !== null ) {
  24864. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24865. } else {
  24866. totalDiffuse = vec3( backdrop );
  24867. }
  24868. context.material.transparent = true;
  24869. }
  24870. totalDiffuseNode.assign( totalDiffuse );
  24871. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24872. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24873. //
  24874. lightingModel.finish( context, stack, builder );
  24875. //
  24876. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24877. }
  24878. return outgoingLightNode;
  24879. }
  24880. /**
  24881. * Configures this node with an array of lights.
  24882. *
  24883. * @param {Array<Light>} lights - An array of lights.
  24884. * @return {LightsNode} A reference to this node.
  24885. */
  24886. setLights( lights ) {
  24887. this._lights = lights;
  24888. this._lightNodes = null;
  24889. this._lightNodesHash = null;
  24890. return this;
  24891. }
  24892. /**
  24893. * Returns an array of the scene's lights.
  24894. *
  24895. * @return {Array<Light>} The scene's lights.
  24896. */
  24897. getLights() {
  24898. return this._lights;
  24899. }
  24900. /**
  24901. * Whether the scene has lights or not.
  24902. *
  24903. * @type {Boolean}
  24904. */
  24905. get hasLights() {
  24906. return this._lights.length > 0;
  24907. }
  24908. }
  24909. /**
  24910. * TSL function for creating an instance of `LightsNode` and configuring
  24911. * it with the given array of lights.
  24912. *
  24913. * @function
  24914. * @param {Array<Light>} lights - An array of lights.
  24915. * @return {LightsNode} The created lights node.
  24916. */
  24917. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24918. /** @module ShadowBaseNode **/
  24919. /**
  24920. * Base class for all shadow nodes.
  24921. *
  24922. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24923. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24924. * their requirements.
  24925. *
  24926. * @augments Node
  24927. */
  24928. class ShadowBaseNode extends Node {
  24929. static get type() {
  24930. return 'ShadowBaseNode';
  24931. }
  24932. /**
  24933. * Constructs a new shadow base node.
  24934. *
  24935. * @param {Light} light - The shadow casting light.
  24936. */
  24937. constructor( light ) {
  24938. super();
  24939. /**
  24940. * The shadow casting light.
  24941. *
  24942. * @type {Light}
  24943. */
  24944. this.light = light;
  24945. /**
  24946. * Overwritten since shadows are updated by default per render.
  24947. *
  24948. * @type {String}
  24949. * @default 'render'
  24950. */
  24951. this.updateBeforeType = NodeUpdateType.RENDER;
  24952. /**
  24953. * This flag can be used for type testing.
  24954. *
  24955. * @type {Boolean}
  24956. * @readonly
  24957. * @default true
  24958. */
  24959. this.isShadowBaseNode = true;
  24960. }
  24961. /**
  24962. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24963. *
  24964. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24965. */
  24966. setupShadowPosition( { material } ) {
  24967. // Use assign inside an Fn()
  24968. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24969. }
  24970. /**
  24971. * Can be called when the shadow isn't required anymore. That can happen when
  24972. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24973. * to `false`.
  24974. */
  24975. dispose() {
  24976. this.updateBeforeType = NodeUpdateType.NONE;
  24977. }
  24978. }
  24979. /**
  24980. * TSL object that represents the vertex position in world space during the shadow pass.
  24981. *
  24982. * @type {Node<vec3>}
  24983. */
  24984. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24985. /** @module RendererUtils **/
  24986. /**
  24987. * Saves the state of the given renderer and stores it into the given state object.
  24988. *
  24989. * If not state object is provided, the function creates one.
  24990. *
  24991. * @function
  24992. * @param {Renderer} renderer - The renderer.
  24993. * @param {Object} [state={}] - The state.
  24994. * @return {Object} The state.
  24995. */
  24996. function saveRendererState( renderer, state = {} ) {
  24997. state.toneMapping = renderer.toneMapping;
  24998. state.toneMappingExposure = renderer.toneMappingExposure;
  24999. state.outputColorSpace = renderer.outputColorSpace;
  25000. state.renderTarget = renderer.getRenderTarget();
  25001. state.activeCubeFace = renderer.getActiveCubeFace();
  25002. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  25003. state.renderObjectFunction = renderer.getRenderObjectFunction();
  25004. state.pixelRatio = renderer.getPixelRatio();
  25005. state.mrt = renderer.getMRT();
  25006. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25007. state.clearAlpha = renderer.getClearAlpha();
  25008. state.autoClear = renderer.autoClear;
  25009. state.scissorTest = renderer.getScissorTest();
  25010. return state;
  25011. }
  25012. /**
  25013. * Saves the state of the given renderer and stores it into the given state object.
  25014. * Besides, the function also resets the state of the renderer to its default values.
  25015. *
  25016. * If not state object is provided, the function creates one.
  25017. *
  25018. * @function
  25019. * @param {Renderer} renderer - The renderer.
  25020. * @param {Object} [state={}] - The state.
  25021. * @return {Object} The state.
  25022. */
  25023. function resetRendererState( renderer, state ) {
  25024. state = saveRendererState( renderer, state );
  25025. renderer.setMRT( null );
  25026. renderer.setRenderObjectFunction( null );
  25027. renderer.setClearColor( 0x000000, 1 );
  25028. renderer.autoClear = true;
  25029. return state;
  25030. }
  25031. /**
  25032. * Restores the state of the given renderer from the given state object.
  25033. *
  25034. * @function
  25035. * @param {Renderer} renderer - The renderer.
  25036. * @param {Object} state - The state to restore.
  25037. */
  25038. function restoreRendererState( renderer, state ) {
  25039. renderer.toneMapping = state.toneMapping;
  25040. renderer.toneMappingExposure = state.toneMappingExposure;
  25041. renderer.outputColorSpace = state.outputColorSpace;
  25042. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25043. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25044. renderer.setPixelRatio( state.pixelRatio );
  25045. renderer.setMRT( state.mrt );
  25046. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25047. renderer.autoClear = state.autoClear;
  25048. renderer.setScissorTest( state.scissorTest );
  25049. }
  25050. /**
  25051. * Saves the state of the given scene and stores it into the given state object.
  25052. *
  25053. * If not state object is provided, the function creates one.
  25054. *
  25055. * @function
  25056. * @param {Scene} scene - The scene.
  25057. * @param {Object} [state={}] - The state.
  25058. * @return {Object} The state.
  25059. */
  25060. function saveSceneState( scene, state = {} ) {
  25061. state.background = scene.background;
  25062. state.backgroundNode = scene.backgroundNode;
  25063. state.overrideMaterial = scene.overrideMaterial;
  25064. return state;
  25065. }
  25066. /**
  25067. * Saves the state of the given scene and stores it into the given state object.
  25068. * Besides, the function also resets the state of the scene to its default values.
  25069. *
  25070. * If not state object is provided, the function creates one.
  25071. *
  25072. * @function
  25073. * @param {Scene} scene - The scene.
  25074. * @param {Object} [state={}] - The state.
  25075. * @return {Object} The state.
  25076. */
  25077. function resetSceneState( scene, state ) {
  25078. state = saveSceneState( scene, state );
  25079. scene.background = null;
  25080. scene.backgroundNode = null;
  25081. scene.overrideMaterial = null;
  25082. return state;
  25083. }
  25084. /**
  25085. * Restores the state of the given scene from the given state object.
  25086. *
  25087. * @function
  25088. * @param {Scene} scene - The scene.
  25089. * @param {Object} state - The state to restore.
  25090. */
  25091. function restoreSceneState( scene, state ) {
  25092. scene.background = state.background;
  25093. scene.backgroundNode = state.backgroundNode;
  25094. scene.overrideMaterial = state.overrideMaterial;
  25095. }
  25096. /**
  25097. * Saves the state of the given renderer and scene and stores it into the given state object.
  25098. *
  25099. * If not state object is provided, the function creates one.
  25100. *
  25101. * @function
  25102. * @param {Renderer} renderer - The renderer.
  25103. * @param {Scene} scene - The scene.
  25104. * @param {Object} [state={}] - The state.
  25105. * @return {Object} The state.
  25106. */
  25107. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25108. state = saveRendererState( renderer, state );
  25109. state = saveSceneState( scene, state );
  25110. return state;
  25111. }
  25112. /**
  25113. * Saves the state of the given renderer and scene and stores it into the given state object.
  25114. * Besides, the function also resets the state of the renderer and scene to its default values.
  25115. *
  25116. * If not state object is provided, the function creates one.
  25117. *
  25118. * @function
  25119. * @param {Renderer} renderer - The renderer.
  25120. * @param {Scene} scene - The scene.
  25121. * @param {Object} [state={}] - The state.
  25122. * @return {Object} The state.
  25123. */
  25124. function resetRendererAndSceneState( renderer, scene, state ) {
  25125. state = resetRendererState( renderer, state );
  25126. state = resetSceneState( scene, state );
  25127. return state;
  25128. }
  25129. /**
  25130. * Restores the state of the given renderer and scene from the given state object.
  25131. *
  25132. * @function
  25133. * @param {Renderer} renderer - The renderer.
  25134. * @param {Scene} scene - The scene.
  25135. * @param {Object} state - The state to restore.
  25136. */
  25137. function restoreRendererAndSceneState( renderer, scene, state ) {
  25138. restoreRendererState( renderer, state );
  25139. restoreSceneState( scene, state );
  25140. }
  25141. var RendererUtils = /*#__PURE__*/Object.freeze({
  25142. __proto__: null,
  25143. resetRendererAndSceneState: resetRendererAndSceneState,
  25144. resetRendererState: resetRendererState,
  25145. resetSceneState: resetSceneState,
  25146. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25147. restoreRendererState: restoreRendererState,
  25148. restoreSceneState: restoreSceneState,
  25149. saveRendererAndSceneState: saveRendererAndSceneState,
  25150. saveRendererState: saveRendererState,
  25151. saveSceneState: saveSceneState
  25152. });
  25153. /** @module ShadowNode **/
  25154. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25155. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25156. let dist = positionWorld.sub( position ).length();
  25157. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25158. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25159. return dist;
  25160. } );
  25161. const linearShadowDistance = ( light ) => {
  25162. const camera = light.shadow.camera;
  25163. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25164. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25165. const referencePosition = objectPosition( light );
  25166. return linearDistance( referencePosition, nearDistance, farDistance );
  25167. };
  25168. const getShadowMaterial = ( light ) => {
  25169. let material = shadowMaterialLib.get( light );
  25170. if ( material === undefined ) {
  25171. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25172. material = new NodeMaterial();
  25173. material.colorNode = vec4( 0, 0, 0, 1 );
  25174. material.depthNode = depthNode;
  25175. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25176. material.name = 'ShadowMaterial';
  25177. material.fog = false;
  25178. shadowMaterialLib.set( light, material );
  25179. }
  25180. return material;
  25181. };
  25182. /**
  25183. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25184. * with a binary `[0,1]` result.
  25185. *
  25186. * @method
  25187. * @param {Object} inputs - The input parameter object.
  25188. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25189. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25190. * @return {Node<float>} The filtering result.
  25191. */
  25192. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25193. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25194. } );
  25195. /**
  25196. * A shadow filtering function performing PCF filtering.
  25197. *
  25198. * @method
  25199. * @param {Object} inputs - The input parameter object.
  25200. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25201. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25202. * @param {LightShadow} inputs.shadow - The light shadow.
  25203. * @return {Node<float>} The filtering result.
  25204. */
  25205. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25206. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25207. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25208. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25209. const texelSize = vec2( 1 ).div( mapSize );
  25210. const dx0 = texelSize.x.negate().mul( radius );
  25211. const dy0 = texelSize.y.negate().mul( radius );
  25212. const dx1 = texelSize.x.mul( radius );
  25213. const dy1 = texelSize.y.mul( radius );
  25214. const dx2 = dx0.div( 2 );
  25215. const dy2 = dy0.div( 2 );
  25216. const dx3 = dx1.div( 2 );
  25217. const dy3 = dy1.div( 2 );
  25218. return add(
  25219. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25220. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25221. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25222. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25223. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25224. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25225. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25226. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25227. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25228. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25229. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25230. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25231. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25232. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25233. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25234. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25235. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25236. ).mul( 1 / 17 );
  25237. } );
  25238. /**
  25239. * A shadow filtering function performing PCF soft filtering.
  25240. *
  25241. * @method
  25242. * @param {Object} inputs - The input parameter object.
  25243. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25244. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25245. * @param {LightShadow} inputs.shadow - The light shadow.
  25246. * @return {Node<float>} The filtering result.
  25247. */
  25248. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25249. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25250. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25251. const texelSize = vec2( 1 ).div( mapSize );
  25252. const dx = texelSize.x;
  25253. const dy = texelSize.y;
  25254. const uv = shadowCoord.xy;
  25255. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25256. uv.subAssign( f.mul( texelSize ) );
  25257. return add(
  25258. depthCompare( uv, shadowCoord.z ),
  25259. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25260. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25261. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25262. mix(
  25263. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25264. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25265. f.x
  25266. ),
  25267. mix(
  25268. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25269. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25270. f.x
  25271. ),
  25272. mix(
  25273. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25274. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25275. f.y
  25276. ),
  25277. mix(
  25278. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25279. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25280. f.y
  25281. ),
  25282. mix(
  25283. mix(
  25284. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25285. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25286. f.x
  25287. ),
  25288. mix(
  25289. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25290. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25291. f.x
  25292. ),
  25293. f.y
  25294. )
  25295. ).mul( 1 / 9 );
  25296. } );
  25297. /**
  25298. * A shadow filtering function performing VSM filtering.
  25299. *
  25300. * @method
  25301. * @param {Object} inputs - The input parameter object.
  25302. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25303. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25304. * @return {Node<float>} The filtering result.
  25305. */
  25306. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25307. const occlusion = float( 1 ).toVar();
  25308. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25309. const hardShadow = step( shadowCoord.z, distribution.x );
  25310. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25311. const distance = shadowCoord.z.sub( distribution.x );
  25312. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25313. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25314. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25315. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25316. } );
  25317. return occlusion;
  25318. } );
  25319. /**
  25320. * Represents the shader code for the first VSM render pass.
  25321. *
  25322. * @method
  25323. * @param {Object} inputs - The input parameter object.
  25324. * @param {Node<float>} inputs.samples - The number of samples
  25325. * @param {Node<float>} inputs.radius - The radius.
  25326. * @param {Node<float>} inputs.size - The size.
  25327. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25328. * @return {Node<vec2>} The VSM output.
  25329. */
  25330. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25331. const mean = float( 0 ).toVar();
  25332. const squaredMean = float( 0 ).toVar();
  25333. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25334. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25335. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25336. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25337. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25338. mean.addAssign( depth );
  25339. squaredMean.addAssign( depth.mul( depth ) );
  25340. } );
  25341. mean.divAssign( samples );
  25342. squaredMean.divAssign( samples );
  25343. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25344. return vec2( mean, std_dev );
  25345. } );
  25346. /**
  25347. * Represents the shader code for the second VSM render pass.
  25348. *
  25349. * @method
  25350. * @param {Object} inputs - The input parameter object.
  25351. * @param {Node<float>} inputs.samples - The number of samples
  25352. * @param {Node<float>} inputs.radius - The radius.
  25353. * @param {Node<float>} inputs.size - The size.
  25354. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25355. * @return {Node<vec2>} The VSM output.
  25356. */
  25357. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25358. const mean = float( 0 ).toVar();
  25359. const squaredMean = float( 0 ).toVar();
  25360. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25361. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25362. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25363. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25364. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25365. mean.addAssign( distribution.x );
  25366. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25367. } );
  25368. mean.divAssign( samples );
  25369. squaredMean.divAssign( samples );
  25370. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25371. return vec2( mean, std_dev );
  25372. } );
  25373. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25374. //
  25375. let _rendererState;
  25376. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25377. /**
  25378. * Represents the default shadow implementation for lighting nodes.
  25379. *
  25380. * @augments module:ShadowBaseNode~ShadowBaseNode
  25381. */
  25382. class ShadowNode extends ShadowBaseNode {
  25383. static get type() {
  25384. return 'ShadowNode';
  25385. }
  25386. /**
  25387. * Constructs a new shadow node.
  25388. *
  25389. * @param {Light} light - The shadow casting light.
  25390. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  25391. */
  25392. constructor( light, shadow = null ) {
  25393. super( light );
  25394. /**
  25395. * The light shadow which defines the properties light's
  25396. * shadow.
  25397. *
  25398. * @type {LightShadow?}
  25399. * @default null
  25400. */
  25401. this.shadow = shadow || light.shadow;
  25402. /**
  25403. * A reference to the shadow map which is a render target.
  25404. *
  25405. * @type {RenderTarget?}
  25406. * @default null
  25407. */
  25408. this.shadowMap = null;
  25409. /**
  25410. * Only relevant for VSM shadows. Render target for the
  25411. * first VSM render pass.
  25412. *
  25413. * @type {RenderTarget?}
  25414. * @default null
  25415. */
  25416. this.vsmShadowMapVertical = null;
  25417. /**
  25418. * Only relevant for VSM shadows. Render target for the
  25419. * second VSM render pass.
  25420. *
  25421. * @type {RenderTarget?}
  25422. * @default null
  25423. */
  25424. this.vsmShadowMapHorizontal = null;
  25425. /**
  25426. * Only relevant for VSM shadows. Node material which
  25427. * is used to render the first VSM pass.
  25428. *
  25429. * @type {NodeMaterial?}
  25430. * @default null
  25431. */
  25432. this.vsmMaterialVertical = null;
  25433. /**
  25434. * Only relevant for VSM shadows. Node material which
  25435. * is used to render the second VSM pass.
  25436. *
  25437. * @type {NodeMaterial?}
  25438. * @default null
  25439. */
  25440. this.vsmMaterialHorizontal = null;
  25441. /**
  25442. * A reference to the output node which defines the
  25443. * final result of this shadow node.
  25444. *
  25445. * @type {Node?}
  25446. * @private
  25447. * @default null
  25448. */
  25449. this._node = null;
  25450. /**
  25451. * This flag can be used for type testing.
  25452. *
  25453. * @type {Boolean}
  25454. * @readonly
  25455. * @default true
  25456. */
  25457. this.isShadowNode = true;
  25458. }
  25459. /**
  25460. * Setups the shadow filtering.
  25461. *
  25462. * @param {NodeBuilder} builder - A reference to the current node builder.
  25463. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25464. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25465. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25466. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25467. * @param {LightShadow} inputs.shadow - The light shadow.
  25468. * @return {Node<float>} The result node of the shadow filtering.
  25469. */
  25470. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25471. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25472. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25473. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25474. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25475. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25476. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25477. return frustumTest.select( shadowNode, float( 1 ) );
  25478. }
  25479. /**
  25480. * Setups the shadow coordinates.
  25481. *
  25482. * @param {NodeBuilder} builder - A reference to the current node builder.
  25483. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25484. * @return {Node<vec3>} The shadow coordinates.
  25485. */
  25486. setupShadowCoord( builder, shadowPosition ) {
  25487. const { shadow } = this;
  25488. const { renderer } = builder;
  25489. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25490. let shadowCoord = shadowPosition;
  25491. let coordZ;
  25492. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25493. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25494. coordZ = shadowCoord.z;
  25495. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25496. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25497. }
  25498. } else {
  25499. const w = shadowCoord.w;
  25500. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25501. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25502. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25503. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25504. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25505. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25506. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25507. }
  25508. shadowCoord = vec3(
  25509. shadowCoord.x,
  25510. shadowCoord.y.oneMinus(), // follow webgpu standards
  25511. coordZ.add( bias )
  25512. );
  25513. return shadowCoord;
  25514. }
  25515. /**
  25516. * Returns the shadow filtering function for the given shadow type.
  25517. *
  25518. * @param {Number} type - The shadow type.
  25519. * @return {Function} The filtering function.
  25520. */
  25521. getShadowFilterFn( type ) {
  25522. return _shadowFilterLib[ type ];
  25523. }
  25524. /**
  25525. * Setups the shadow output node.
  25526. *
  25527. * @param {NodeBuilder} builder - A reference to the current node builder.
  25528. * @return {Node<vec3>} The shadow output node.
  25529. */
  25530. setupShadow( builder ) {
  25531. const { renderer } = builder;
  25532. const { light, shadow } = this;
  25533. const shadowMapType = renderer.shadowMap.type;
  25534. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25535. depthTexture.compareFunction = LessCompare;
  25536. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25537. shadowMap.depthTexture = depthTexture;
  25538. shadow.camera.updateProjectionMatrix();
  25539. // VSM
  25540. if ( shadowMapType === VSMShadowMap ) {
  25541. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25542. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25543. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25544. const shadowPassVertical = texture( depthTexture );
  25545. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25546. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25547. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25548. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25549. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25550. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25551. material.name = 'VSMVertical';
  25552. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25553. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25554. material.name = 'VSMHorizontal';
  25555. }
  25556. //
  25557. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25558. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25559. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25560. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25561. //
  25562. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25563. if ( filterFn === null ) {
  25564. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25565. }
  25566. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25567. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25568. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25569. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25570. this.shadowMap = shadowMap;
  25571. this.shadow.map = shadowMap;
  25572. return shadowOutput;
  25573. }
  25574. /**
  25575. * The implementation performs the setup of the output node. An output is only
  25576. * produces if shadow mapping is globally enabled in the renderer.
  25577. *
  25578. * @param {NodeBuilder} builder - A reference to the current node builder.
  25579. * @return {ShaderCallNodeInternal} The output node.
  25580. */
  25581. setup( builder ) {
  25582. if ( builder.renderer.shadowMap.enabled === false ) return;
  25583. return Fn( () => {
  25584. let node = this._node;
  25585. this.setupShadowPosition( builder );
  25586. if ( node === null ) {
  25587. this._node = node = this.setupShadow( builder );
  25588. }
  25589. if ( builder.material.shadowNode ) { // @deprecated, r171
  25590. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25591. }
  25592. if ( builder.material.receivedShadowNode ) {
  25593. node = builder.material.receivedShadowNode( node );
  25594. }
  25595. return node;
  25596. } )();
  25597. }
  25598. /**
  25599. * Renders the shadow. The logic of this function could be included
  25600. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25601. * nodes might require a custom shadow map rendering. By having a
  25602. * dedicated method, it's easier to overwrite the default behavior.
  25603. *
  25604. * @param {NodeFrame} frame - A reference to the current node frame.
  25605. */
  25606. renderShadow( frame ) {
  25607. const { shadow, shadowMap, light } = this;
  25608. const { renderer, scene } = frame;
  25609. shadow.updateMatrices( light );
  25610. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25611. renderer.render( scene, shadow.camera );
  25612. }
  25613. /**
  25614. * Updates the shadow.
  25615. *
  25616. * @param {NodeFrame} frame - A reference to the current node frame.
  25617. */
  25618. updateShadow( frame ) {
  25619. const { shadowMap, light, shadow } = this;
  25620. const { renderer, scene, camera } = frame;
  25621. const shadowType = renderer.shadowMap.type;
  25622. const depthVersion = shadowMap.depthTexture.version;
  25623. this._depthVersionCached = depthVersion;
  25624. shadow.camera.layers.mask = camera.layers.mask;
  25625. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25626. const currentMRT = renderer.getMRT();
  25627. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25628. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25629. scene.overrideMaterial = getShadowMaterial( light );
  25630. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25631. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25632. if ( useVelocity ) {
  25633. getDataFromObject( object ).useVelocity = true;
  25634. }
  25635. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25636. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25637. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25638. }
  25639. } );
  25640. renderer.setRenderTarget( shadowMap );
  25641. this.renderShadow( frame );
  25642. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25643. // vsm blur pass
  25644. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25645. this.vsmPass( renderer );
  25646. }
  25647. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25648. }
  25649. /**
  25650. * For VSM additional render passes are required.
  25651. *
  25652. * @param {Renderer} renderer - A reference to the current renderer.
  25653. */
  25654. vsmPass( renderer ) {
  25655. const { shadow } = this;
  25656. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25657. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25658. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25659. _quadMesh.material = this.vsmMaterialVertical;
  25660. _quadMesh.render( renderer );
  25661. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25662. _quadMesh.material = this.vsmMaterialHorizontal;
  25663. _quadMesh.render( renderer );
  25664. }
  25665. /**
  25666. * Frees the internal resources of this shadow node.
  25667. */
  25668. dispose() {
  25669. this.shadowMap.dispose();
  25670. this.shadowMap = null;
  25671. if ( this.vsmShadowMapVertical !== null ) {
  25672. this.vsmShadowMapVertical.dispose();
  25673. this.vsmShadowMapVertical = null;
  25674. this.vsmMaterialVertical.dispose();
  25675. this.vsmMaterialVertical = null;
  25676. }
  25677. if ( this.vsmShadowMapHorizontal !== null ) {
  25678. this.vsmShadowMapHorizontal.dispose();
  25679. this.vsmShadowMapHorizontal = null;
  25680. this.vsmMaterialHorizontal.dispose();
  25681. this.vsmMaterialHorizontal = null;
  25682. }
  25683. super.dispose();
  25684. }
  25685. /**
  25686. * The implementation performs the update of the shadow map if necessary.
  25687. *
  25688. * @param {NodeFrame} frame - A reference to the current node frame.
  25689. */
  25690. updateBefore( frame ) {
  25691. const { shadow } = this;
  25692. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25693. if ( needsUpdate ) {
  25694. this.updateShadow( frame );
  25695. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25696. shadow.needsUpdate = false;
  25697. }
  25698. }
  25699. }
  25700. }
  25701. /**
  25702. * TSL function for creating an instance of `ShadowNode`.
  25703. *
  25704. * @function
  25705. * @param {Light} light - The shadow casting light.
  25706. * @param {LightShadow} shadow - The light shadow.
  25707. * @return {ShadowNode} The created shadow node.
  25708. */
  25709. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25710. /**
  25711. * Base class for analytic light nodes.
  25712. *
  25713. * @augments LightingNode
  25714. */
  25715. class AnalyticLightNode extends LightingNode {
  25716. static get type() {
  25717. return 'AnalyticLightNode';
  25718. }
  25719. /**
  25720. * Constructs a new analytic light node.
  25721. *
  25722. * @param {Light?} [light=null] - The light source.
  25723. */
  25724. constructor( light = null ) {
  25725. super();
  25726. /**
  25727. * The light source.
  25728. *
  25729. * @type {Light?}
  25730. * @default null
  25731. */
  25732. this.light = light;
  25733. /**
  25734. * The light's color value.
  25735. *
  25736. * @type {Color}
  25737. */
  25738. this.color = new Color();
  25739. /**
  25740. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25741. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25742. *
  25743. * @type {Node}
  25744. */
  25745. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25746. /**
  25747. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25748. * The final color node is represented by a different node when using shadows.
  25749. *
  25750. * @type {Node?}
  25751. * @default null
  25752. */
  25753. this.baseColorNode = null;
  25754. /**
  25755. * Represents the light's shadow.
  25756. *
  25757. * @type {ShadowNode?}
  25758. * @default null
  25759. */
  25760. this.shadowNode = null;
  25761. /**
  25762. * Represents the light's shadow color.
  25763. *
  25764. * @type {Node?}
  25765. * @default null
  25766. */
  25767. this.shadowColorNode = null;
  25768. /**
  25769. * This flag can be used for type testing.
  25770. *
  25771. * @type {Boolean}
  25772. * @readonly
  25773. * @default true
  25774. */
  25775. this.isAnalyticLightNode = true;
  25776. /**
  25777. * Overwritten since analytic light nodes are updated
  25778. * once per frame.
  25779. *
  25780. * @type {String}
  25781. * @default 'frame'
  25782. */
  25783. this.updateType = NodeUpdateType.FRAME;
  25784. }
  25785. /**
  25786. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25787. * `light.id` and `light.castShadow` into the cache key.
  25788. *
  25789. * @return {Number} The custom cache key.
  25790. */
  25791. customCacheKey() {
  25792. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25793. }
  25794. getHash() {
  25795. return this.light.uuid;
  25796. }
  25797. /**
  25798. * Setups the shadow node for this light. The method exists so concrete light classes
  25799. * can setup different types of shadow nodes.
  25800. *
  25801. * @return {ShadowNode} The created shadow node.
  25802. */
  25803. setupShadowNode() {
  25804. return shadow( this.light );
  25805. }
  25806. /**
  25807. * Setups the shadow for this light. This method is only executed if the light
  25808. * cast shadows and the current build object receives shadows. It incorporates
  25809. * shadows into the lighting computation.
  25810. *
  25811. * @param {NodeBuilder} builder - The current node builder.
  25812. */
  25813. setupShadow( builder ) {
  25814. const { renderer } = builder;
  25815. if ( renderer.shadowMap.enabled === false ) return;
  25816. let shadowColorNode = this.shadowColorNode;
  25817. if ( shadowColorNode === null ) {
  25818. const customShadowNode = this.light.shadow.shadowNode;
  25819. let shadowNode;
  25820. if ( customShadowNode !== undefined ) {
  25821. shadowNode = nodeObject( customShadowNode );
  25822. } else {
  25823. shadowNode = this.setupShadowNode( builder );
  25824. }
  25825. this.shadowNode = shadowNode;
  25826. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25827. this.baseColorNode = this.colorNode;
  25828. }
  25829. //
  25830. this.colorNode = shadowColorNode;
  25831. }
  25832. /**
  25833. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25834. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25835. * invocate the respective interface methods.
  25836. *
  25837. * @param {NodeBuilder} builder - The current node builder.
  25838. */
  25839. setup( builder ) {
  25840. this.colorNode = this.baseColorNode || this.colorNode;
  25841. if ( this.light.castShadow ) {
  25842. if ( builder.object.receiveShadow ) {
  25843. this.setupShadow( builder );
  25844. }
  25845. } else if ( this.shadowNode !== null ) {
  25846. this.shadowNode.dispose();
  25847. this.shadowNode = null;
  25848. this.shadowColorNode = null;
  25849. }
  25850. }
  25851. /**
  25852. * The update method is used to update light uniforms per frame.
  25853. * Potentially overwritten in concrete light nodes to update light
  25854. * specific uniforms.
  25855. *
  25856. * @param {NodeFrame} frame - A reference to the current node frame.
  25857. */
  25858. update( /*frame*/ ) {
  25859. const { light } = this;
  25860. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25861. }
  25862. }
  25863. /** @module LightUtils **/
  25864. /**
  25865. * Represents a `discard` shader operation in TSL.
  25866. *
  25867. * @method
  25868. * @param {Object} inputs - The input parameter object.
  25869. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25870. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25871. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25872. * @return {Node<float>} The distance falloff.
  25873. */
  25874. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25875. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25876. // based upon Frostbite 3 Moving to Physically-based Rendering
  25877. // page 32, equation 26: E[window1]
  25878. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25879. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25880. return cutoffDistance.greaterThan( 0 ).select(
  25881. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25882. distanceFalloff
  25883. );
  25884. } ); // validated
  25885. /** @module PointShadowNode **/
  25886. const _clearColor$2 = /*@__PURE__*/ new Color();
  25887. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25888. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25889. // 2D texture:
  25890. //
  25891. // xzXZ
  25892. // y Y
  25893. //
  25894. // Y - Positive y direction
  25895. // y - Negative y direction
  25896. // X - Positive x direction
  25897. // x - Negative x direction
  25898. // Z - Positive z direction
  25899. // z - Negative z direction
  25900. //
  25901. // Source and test bed:
  25902. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25903. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25904. const v = pos.toVar();
  25905. // Number of texels to avoid at the edge of each square
  25906. const absV = abs( v );
  25907. // Intersect unit cube
  25908. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25909. absV.mulAssign( scaleToCube );
  25910. // Apply scale to avoid seams
  25911. // two texels less per square (one texel will do for NEAREST)
  25912. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25913. // Unwrap
  25914. // space: -1 ... 1 range for each square
  25915. //
  25916. // #X## dim := ( 4 , 2 )
  25917. // # # center := ( 1 , 1 )
  25918. const planar = vec2( v.xy ).toVar();
  25919. const almostATexel = texelSizeY.mul( 1.5 );
  25920. const almostOne = almostATexel.oneMinus();
  25921. If( absV.z.greaterThanEqual( almostOne ), () => {
  25922. If( v.z.greaterThan( 0.0 ), () => {
  25923. planar.x.assign( sub( 4.0, v.x ) );
  25924. } );
  25925. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25926. const signX = sign( v.x );
  25927. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25928. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25929. const signY = sign( v.y );
  25930. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25931. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25932. } );
  25933. // Transform to UV space
  25934. // scale := 0.5 / dim
  25935. // translate := ( center + 0.5 ) / dim
  25936. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25937. } ).setLayout( {
  25938. name: 'cubeToUV',
  25939. type: 'vec2',
  25940. inputs: [
  25941. { name: 'pos', type: 'vec3' },
  25942. { name: 'texelSizeY', type: 'float' }
  25943. ]
  25944. } );
  25945. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25946. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25947. } );
  25948. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25949. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25950. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  25951. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25952. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25953. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25954. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25955. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25956. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25957. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25958. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25959. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25960. .mul( 1.0 / 9.0 );
  25961. } );
  25962. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25963. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25964. // the vector from the light to the world-space position of the fragment.
  25965. const lightToPosition = shadowCoord.xyz.toVar();
  25966. const lightToPositionLength = lightToPosition.length();
  25967. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25968. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25969. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25970. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25971. const result = float( 1.0 ).toVar();
  25972. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25973. // dp = normalized distance from light to fragment position
  25974. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25975. dp.addAssign( bias );
  25976. // bd3D = base direction 3D
  25977. const bd3D = lightToPosition.normalize();
  25978. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25979. // percentage-closer filtering
  25980. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25981. } );
  25982. return result;
  25983. } );
  25984. const _viewport = /*@__PURE__*/ new Vector4();
  25985. const _viewportSize = /*@__PURE__*/ new Vector2();
  25986. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25987. /**
  25988. * Represents the shadow implementation for point light nodes.
  25989. *
  25990. * @augments module:ShadowNode~ShadowNode
  25991. */
  25992. class PointShadowNode extends ShadowNode {
  25993. static get type() {
  25994. return 'PointShadowNode';
  25995. }
  25996. /**
  25997. * Constructs a new point shadow node.
  25998. *
  25999. * @param {PointLight} light - The shadow casting point light.
  26000. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  26001. */
  26002. constructor( light, shadow = null ) {
  26003. super( light, shadow );
  26004. }
  26005. /**
  26006. * Overwrites the default implementation to return point light shadow specific
  26007. * filtering functions.
  26008. *
  26009. * @param {Number} type - The shadow type.
  26010. * @return {Function} The filtering function.
  26011. */
  26012. getShadowFilterFn( type ) {
  26013. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  26014. }
  26015. /**
  26016. * Overwrites the default implementation so the unaltered shadow position is used.
  26017. *
  26018. * @param {NodeBuilder} builder - A reference to the current node builder.
  26019. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26020. * @return {Node<vec3>} The shadow coordinates.
  26021. */
  26022. setupShadowCoord( builder, shadowPosition ) {
  26023. return shadowPosition;
  26024. }
  26025. /**
  26026. * Overwrites the default implementation to only use point light specific
  26027. * shadow filter functions.
  26028. *
  26029. * @param {NodeBuilder} builder - A reference to the current node builder.
  26030. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26031. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26032. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  26033. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26034. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26035. * @param {LightShadow} inputs.shadow - The light shadow.
  26036. * @return {Node<float>} The result node of the shadow filtering.
  26037. */
  26038. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  26039. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  26040. }
  26041. /**
  26042. * Overwrites the default implementation with point light specific
  26043. * rendering code.
  26044. *
  26045. * @param {NodeFrame} frame - A reference to the current node frame.
  26046. */
  26047. renderShadow( frame ) {
  26048. const { shadow, shadowMap, light } = this;
  26049. const { renderer, scene } = frame;
  26050. const shadowFrameExtents = shadow.getFrameExtents();
  26051. _shadowMapSize.copy( shadow.mapSize );
  26052. _shadowMapSize.multiply( shadowFrameExtents );
  26053. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  26054. _viewportSize.copy( shadow.mapSize );
  26055. //
  26056. const previousAutoClear = renderer.autoClear;
  26057. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  26058. const previousClearAlpha = renderer.getClearAlpha();
  26059. renderer.autoClear = false;
  26060. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  26061. renderer.clear();
  26062. const viewportCount = shadow.getViewportCount();
  26063. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  26064. const viewport = shadow.getViewport( vp );
  26065. const x = _viewportSize.x * viewport.x;
  26066. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  26067. _viewport.set(
  26068. x,
  26069. y,
  26070. _viewportSize.x * viewport.z,
  26071. _viewportSize.y * viewport.w
  26072. );
  26073. shadowMap.viewport.copy( _viewport );
  26074. shadow.updateMatrices( light, vp );
  26075. renderer.render( scene, shadow.camera );
  26076. }
  26077. //
  26078. renderer.autoClear = previousAutoClear;
  26079. renderer.setClearColor( previousClearColor, previousClearAlpha );
  26080. }
  26081. }
  26082. /**
  26083. * TSL function for creating an instance of `PointShadowNode`.
  26084. *
  26085. * @function
  26086. * @param {PointLight} light - The shadow casting point light.
  26087. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  26088. * @return {PointShadowNode} The created point shadow node.
  26089. */
  26090. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  26091. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  26092. const lightingModel = builder.context.lightingModel;
  26093. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  26094. const lightDirection = lVector.normalize();
  26095. const lightDistance = lVector.length();
  26096. const lightAttenuation = getDistanceAttenuation( {
  26097. lightDistance,
  26098. cutoffDistance,
  26099. decayExponent
  26100. } );
  26101. const lightColor = color.mul( lightAttenuation );
  26102. const reflectedLight = builder.context.reflectedLight;
  26103. lightingModel.direct( {
  26104. lightDirection,
  26105. lightColor,
  26106. reflectedLight
  26107. }, builder.stack, builder );
  26108. } );
  26109. /**
  26110. * Module for representing point lights as nodes.
  26111. *
  26112. * @augments AnalyticLightNode
  26113. */
  26114. class PointLightNode extends AnalyticLightNode {
  26115. static get type() {
  26116. return 'PointLightNode';
  26117. }
  26118. /**
  26119. * Constructs a new point light node.
  26120. *
  26121. * @param {PointLight?} [light=null] - The point light source.
  26122. */
  26123. constructor( light = null ) {
  26124. super( light );
  26125. /**
  26126. * Uniform node representing the cutoff distance.
  26127. *
  26128. * @type {UniformNode<float>}
  26129. */
  26130. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26131. /**
  26132. * Uniform node representing the decay exponent.
  26133. *
  26134. * @type {UniformNode<float>}
  26135. */
  26136. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26137. }
  26138. /**
  26139. * Overwritten to updated point light specific uniforms.
  26140. *
  26141. * @param {NodeFrame} frame - A reference to the current node frame.
  26142. */
  26143. update( frame ) {
  26144. const { light } = this;
  26145. super.update( frame );
  26146. this.cutoffDistanceNode.value = light.distance;
  26147. this.decayExponentNode.value = light.decay;
  26148. }
  26149. /**
  26150. * Overwritten to setup point light specific shadow.
  26151. *
  26152. * @return {PointShadowNode}
  26153. */
  26154. setupShadowNode() {
  26155. return pointShadow( this.light );
  26156. }
  26157. setup( builder ) {
  26158. super.setup( builder );
  26159. directPointLight( {
  26160. color: this.colorNode,
  26161. lightViewPosition: lightViewPosition( this.light ),
  26162. cutoffDistance: this.cutoffDistanceNode,
  26163. decayExponent: this.decayExponentNode
  26164. } ).append();
  26165. }
  26166. }
  26167. /** @module Procedural **/
  26168. /**
  26169. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26170. *
  26171. * @method
  26172. * @param {Node<vec2>} coord - The uv coordinates.
  26173. * @return {Node<float>} The result data.
  26174. */
  26175. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26176. const uv = coord.mul( 2.0 );
  26177. const cx = uv.x.floor();
  26178. const cy = uv.y.floor();
  26179. const result = cx.add( cy ).mod( 2.0 );
  26180. return result.sign();
  26181. } );
  26182. /** @module Shapes **/
  26183. /**
  26184. * Generates a circle based on the uv coordinates.
  26185. *
  26186. * @method
  26187. * @param {Node<vec2>} coord - The uv to generate the circle.
  26188. * @return {Node<float>} The circle shape.
  26189. */
  26190. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26191. const alpha = float( 1 ).toVar();
  26192. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26193. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26194. const dlen = float( len2.fwidth() ).toVar();
  26195. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26196. } else {
  26197. len2.greaterThan( 1.0 ).discard();
  26198. }
  26199. return alpha;
  26200. } );
  26201. // Three.js Transpiler
  26202. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26203. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26204. const f = float( f_immutable ).toVar();
  26205. const t = float( t_immutable ).toVar();
  26206. const b = bool( b_immutable ).toVar();
  26207. return select( b, t, f );
  26208. } ).setLayout( {
  26209. name: 'mx_select',
  26210. type: 'float',
  26211. inputs: [
  26212. { name: 'b', type: 'bool' },
  26213. { name: 't', type: 'float' },
  26214. { name: 'f', type: 'float' }
  26215. ]
  26216. } );
  26217. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26218. const b = bool( b_immutable ).toVar();
  26219. const val = float( val_immutable ).toVar();
  26220. return select( b, val.negate(), val );
  26221. } ).setLayout( {
  26222. name: 'mx_negate_if',
  26223. type: 'float',
  26224. inputs: [
  26225. { name: 'val', type: 'float' },
  26226. { name: 'b', type: 'bool' }
  26227. ]
  26228. } );
  26229. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26230. const x = float( x_immutable ).toVar();
  26231. return int( floor( x ) );
  26232. } ).setLayout( {
  26233. name: 'mx_floor',
  26234. type: 'int',
  26235. inputs: [
  26236. { name: 'x', type: 'float' }
  26237. ]
  26238. } );
  26239. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26240. const x = float( x_immutable ).toVar();
  26241. i.assign( mx_floor( x ) );
  26242. return x.sub( float( i ) );
  26243. } );
  26244. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26245. const t = float( t_immutable ).toVar();
  26246. const s = float( s_immutable ).toVar();
  26247. const v3 = float( v3_immutable ).toVar();
  26248. const v2 = float( v2_immutable ).toVar();
  26249. const v1 = float( v1_immutable ).toVar();
  26250. const v0 = float( v0_immutable ).toVar();
  26251. const s1 = float( sub( 1.0, s ) ).toVar();
  26252. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26253. } ).setLayout( {
  26254. name: 'mx_bilerp_0',
  26255. type: 'float',
  26256. inputs: [
  26257. { name: 'v0', type: 'float' },
  26258. { name: 'v1', type: 'float' },
  26259. { name: 'v2', type: 'float' },
  26260. { name: 'v3', type: 'float' },
  26261. { name: 's', type: 'float' },
  26262. { name: 't', type: 'float' }
  26263. ]
  26264. } );
  26265. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26266. const t = float( t_immutable ).toVar();
  26267. const s = float( s_immutable ).toVar();
  26268. const v3 = vec3( v3_immutable ).toVar();
  26269. const v2 = vec3( v2_immutable ).toVar();
  26270. const v1 = vec3( v1_immutable ).toVar();
  26271. const v0 = vec3( v0_immutable ).toVar();
  26272. const s1 = float( sub( 1.0, s ) ).toVar();
  26273. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26274. } ).setLayout( {
  26275. name: 'mx_bilerp_1',
  26276. type: 'vec3',
  26277. inputs: [
  26278. { name: 'v0', type: 'vec3' },
  26279. { name: 'v1', type: 'vec3' },
  26280. { name: 'v2', type: 'vec3' },
  26281. { name: 'v3', type: 'vec3' },
  26282. { name: 's', type: 'float' },
  26283. { name: 't', type: 'float' }
  26284. ]
  26285. } );
  26286. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26287. 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 ] ) => {
  26288. const r = float( r_immutable ).toVar();
  26289. const t = float( t_immutable ).toVar();
  26290. const s = float( s_immutable ).toVar();
  26291. const v7 = float( v7_immutable ).toVar();
  26292. const v6 = float( v6_immutable ).toVar();
  26293. const v5 = float( v5_immutable ).toVar();
  26294. const v4 = float( v4_immutable ).toVar();
  26295. const v3 = float( v3_immutable ).toVar();
  26296. const v2 = float( v2_immutable ).toVar();
  26297. const v1 = float( v1_immutable ).toVar();
  26298. const v0 = float( v0_immutable ).toVar();
  26299. const s1 = float( sub( 1.0, s ) ).toVar();
  26300. const t1 = float( sub( 1.0, t ) ).toVar();
  26301. const r1 = float( sub( 1.0, r ) ).toVar();
  26302. 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 ) ) ) ) ) );
  26303. } ).setLayout( {
  26304. name: 'mx_trilerp_0',
  26305. type: 'float',
  26306. inputs: [
  26307. { name: 'v0', type: 'float' },
  26308. { name: 'v1', type: 'float' },
  26309. { name: 'v2', type: 'float' },
  26310. { name: 'v3', type: 'float' },
  26311. { name: 'v4', type: 'float' },
  26312. { name: 'v5', type: 'float' },
  26313. { name: 'v6', type: 'float' },
  26314. { name: 'v7', type: 'float' },
  26315. { name: 's', type: 'float' },
  26316. { name: 't', type: 'float' },
  26317. { name: 'r', type: 'float' }
  26318. ]
  26319. } );
  26320. 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 ] ) => {
  26321. const r = float( r_immutable ).toVar();
  26322. const t = float( t_immutable ).toVar();
  26323. const s = float( s_immutable ).toVar();
  26324. const v7 = vec3( v7_immutable ).toVar();
  26325. const v6 = vec3( v6_immutable ).toVar();
  26326. const v5 = vec3( v5_immutable ).toVar();
  26327. const v4 = vec3( v4_immutable ).toVar();
  26328. const v3 = vec3( v3_immutable ).toVar();
  26329. const v2 = vec3( v2_immutable ).toVar();
  26330. const v1 = vec3( v1_immutable ).toVar();
  26331. const v0 = vec3( v0_immutable ).toVar();
  26332. const s1 = float( sub( 1.0, s ) ).toVar();
  26333. const t1 = float( sub( 1.0, t ) ).toVar();
  26334. const r1 = float( sub( 1.0, r ) ).toVar();
  26335. 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 ) ) ) ) ) );
  26336. } ).setLayout( {
  26337. name: 'mx_trilerp_1',
  26338. type: 'vec3',
  26339. inputs: [
  26340. { name: 'v0', type: 'vec3' },
  26341. { name: 'v1', type: 'vec3' },
  26342. { name: 'v2', type: 'vec3' },
  26343. { name: 'v3', type: 'vec3' },
  26344. { name: 'v4', type: 'vec3' },
  26345. { name: 'v5', type: 'vec3' },
  26346. { name: 'v6', type: 'vec3' },
  26347. { name: 'v7', type: 'vec3' },
  26348. { name: 's', type: 'float' },
  26349. { name: 't', type: 'float' },
  26350. { name: 'r', type: 'float' }
  26351. ]
  26352. } );
  26353. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26354. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26355. const y = float( y_immutable ).toVar();
  26356. const x = float( x_immutable ).toVar();
  26357. const hash = uint( hash_immutable ).toVar();
  26358. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26359. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26360. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26361. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26362. } ).setLayout( {
  26363. name: 'mx_gradient_float_0',
  26364. type: 'float',
  26365. inputs: [
  26366. { name: 'hash', type: 'uint' },
  26367. { name: 'x', type: 'float' },
  26368. { name: 'y', type: 'float' }
  26369. ]
  26370. } );
  26371. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26372. const z = float( z_immutable ).toVar();
  26373. const y = float( y_immutable ).toVar();
  26374. const x = float( x_immutable ).toVar();
  26375. const hash = uint( hash_immutable ).toVar();
  26376. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26377. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26378. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26379. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26380. } ).setLayout( {
  26381. name: 'mx_gradient_float_1',
  26382. type: 'float',
  26383. inputs: [
  26384. { name: 'hash', type: 'uint' },
  26385. { name: 'x', type: 'float' },
  26386. { name: 'y', type: 'float' },
  26387. { name: 'z', type: 'float' }
  26388. ]
  26389. } );
  26390. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26391. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26392. const y = float( y_immutable ).toVar();
  26393. const x = float( x_immutable ).toVar();
  26394. const hash = uvec3( hash_immutable ).toVar();
  26395. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26396. } ).setLayout( {
  26397. name: 'mx_gradient_vec3_0',
  26398. type: 'vec3',
  26399. inputs: [
  26400. { name: 'hash', type: 'uvec3' },
  26401. { name: 'x', type: 'float' },
  26402. { name: 'y', type: 'float' }
  26403. ]
  26404. } );
  26405. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26406. const z = float( z_immutable ).toVar();
  26407. const y = float( y_immutable ).toVar();
  26408. const x = float( x_immutable ).toVar();
  26409. const hash = uvec3( hash_immutable ).toVar();
  26410. 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 ) );
  26411. } ).setLayout( {
  26412. name: 'mx_gradient_vec3_1',
  26413. type: 'vec3',
  26414. inputs: [
  26415. { name: 'hash', type: 'uvec3' },
  26416. { name: 'x', type: 'float' },
  26417. { name: 'y', type: 'float' },
  26418. { name: 'z', type: 'float' }
  26419. ]
  26420. } );
  26421. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  26422. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26423. const v = float( v_immutable ).toVar();
  26424. return mul( 0.6616, v );
  26425. } ).setLayout( {
  26426. name: 'mx_gradient_scale2d_0',
  26427. type: 'float',
  26428. inputs: [
  26429. { name: 'v', type: 'float' }
  26430. ]
  26431. } );
  26432. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26433. const v = float( v_immutable ).toVar();
  26434. return mul( 0.9820, v );
  26435. } ).setLayout( {
  26436. name: 'mx_gradient_scale3d_0',
  26437. type: 'float',
  26438. inputs: [
  26439. { name: 'v', type: 'float' }
  26440. ]
  26441. } );
  26442. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26443. const v = vec3( v_immutable ).toVar();
  26444. return mul( 0.6616, v );
  26445. } ).setLayout( {
  26446. name: 'mx_gradient_scale2d_1',
  26447. type: 'vec3',
  26448. inputs: [
  26449. { name: 'v', type: 'vec3' }
  26450. ]
  26451. } );
  26452. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  26453. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26454. const v = vec3( v_immutable ).toVar();
  26455. return mul( 0.9820, v );
  26456. } ).setLayout( {
  26457. name: 'mx_gradient_scale3d_1',
  26458. type: 'vec3',
  26459. inputs: [
  26460. { name: 'v', type: 'vec3' }
  26461. ]
  26462. } );
  26463. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26464. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26465. const k = int( k_immutable ).toVar();
  26466. const x = uint( x_immutable ).toVar();
  26467. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26468. } ).setLayout( {
  26469. name: 'mx_rotl32',
  26470. type: 'uint',
  26471. inputs: [
  26472. { name: 'x', type: 'uint' },
  26473. { name: 'k', type: 'int' }
  26474. ]
  26475. } );
  26476. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26477. a.subAssign( c );
  26478. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26479. c.addAssign( b );
  26480. b.subAssign( a );
  26481. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26482. a.addAssign( c );
  26483. c.subAssign( b );
  26484. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26485. b.addAssign( a );
  26486. a.subAssign( c );
  26487. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26488. c.addAssign( b );
  26489. b.subAssign( a );
  26490. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26491. a.addAssign( c );
  26492. c.subAssign( b );
  26493. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26494. b.addAssign( a );
  26495. } );
  26496. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26497. const c = uint( c_immutable ).toVar();
  26498. const b = uint( b_immutable ).toVar();
  26499. const a = uint( a_immutable ).toVar();
  26500. c.bitXorAssign( b );
  26501. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26502. a.bitXorAssign( c );
  26503. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26504. b.bitXorAssign( a );
  26505. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26506. c.bitXorAssign( b );
  26507. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26508. a.bitXorAssign( c );
  26509. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26510. b.bitXorAssign( a );
  26511. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26512. c.bitXorAssign( b );
  26513. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26514. return c;
  26515. } ).setLayout( {
  26516. name: 'mx_bjfinal',
  26517. type: 'uint',
  26518. inputs: [
  26519. { name: 'a', type: 'uint' },
  26520. { name: 'b', type: 'uint' },
  26521. { name: 'c', type: 'uint' }
  26522. ]
  26523. } );
  26524. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26525. const bits = uint( bits_immutable ).toVar();
  26526. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26527. } ).setLayout( {
  26528. name: 'mx_bits_to_01',
  26529. type: 'float',
  26530. inputs: [
  26531. { name: 'bits', type: 'uint' }
  26532. ]
  26533. } );
  26534. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26535. const t = float( t_immutable ).toVar();
  26536. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26537. } ).setLayout( {
  26538. name: 'mx_fade',
  26539. type: 'float',
  26540. inputs: [
  26541. { name: 't', type: 'float' }
  26542. ]
  26543. } );
  26544. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26545. const x = int( x_immutable ).toVar();
  26546. const len = uint( uint( 1 ) ).toVar();
  26547. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26548. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26549. } ).setLayout( {
  26550. name: 'mx_hash_int_0',
  26551. type: 'uint',
  26552. inputs: [
  26553. { name: 'x', type: 'int' }
  26554. ]
  26555. } );
  26556. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26557. const y = int( y_immutable ).toVar();
  26558. const x = int( x_immutable ).toVar();
  26559. const len = uint( uint( 2 ) ).toVar();
  26560. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26561. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26562. a.addAssign( uint( x ) );
  26563. b.addAssign( uint( y ) );
  26564. return mx_bjfinal( a, b, c );
  26565. } ).setLayout( {
  26566. name: 'mx_hash_int_1',
  26567. type: 'uint',
  26568. inputs: [
  26569. { name: 'x', type: 'int' },
  26570. { name: 'y', type: 'int' }
  26571. ]
  26572. } );
  26573. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26574. const z = int( z_immutable ).toVar();
  26575. const y = int( y_immutable ).toVar();
  26576. const x = int( x_immutable ).toVar();
  26577. const len = uint( uint( 3 ) ).toVar();
  26578. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26579. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26580. a.addAssign( uint( x ) );
  26581. b.addAssign( uint( y ) );
  26582. c.addAssign( uint( z ) );
  26583. return mx_bjfinal( a, b, c );
  26584. } ).setLayout( {
  26585. name: 'mx_hash_int_2',
  26586. type: 'uint',
  26587. inputs: [
  26588. { name: 'x', type: 'int' },
  26589. { name: 'y', type: 'int' },
  26590. { name: 'z', type: 'int' }
  26591. ]
  26592. } );
  26593. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26594. const xx = int( xx_immutable ).toVar();
  26595. const z = int( z_immutable ).toVar();
  26596. const y = int( y_immutable ).toVar();
  26597. const x = int( x_immutable ).toVar();
  26598. const len = uint( uint( 4 ) ).toVar();
  26599. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26600. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26601. a.addAssign( uint( x ) );
  26602. b.addAssign( uint( y ) );
  26603. c.addAssign( uint( z ) );
  26604. mx_bjmix( a, b, c );
  26605. a.addAssign( uint( xx ) );
  26606. return mx_bjfinal( a, b, c );
  26607. } ).setLayout( {
  26608. name: 'mx_hash_int_3',
  26609. type: 'uint',
  26610. inputs: [
  26611. { name: 'x', type: 'int' },
  26612. { name: 'y', type: 'int' },
  26613. { name: 'z', type: 'int' },
  26614. { name: 'xx', type: 'int' }
  26615. ]
  26616. } );
  26617. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26618. const yy = int( yy_immutable ).toVar();
  26619. const xx = int( xx_immutable ).toVar();
  26620. const z = int( z_immutable ).toVar();
  26621. const y = int( y_immutable ).toVar();
  26622. const x = int( x_immutable ).toVar();
  26623. const len = uint( uint( 5 ) ).toVar();
  26624. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26625. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26626. a.addAssign( uint( x ) );
  26627. b.addAssign( uint( y ) );
  26628. c.addAssign( uint( z ) );
  26629. mx_bjmix( a, b, c );
  26630. a.addAssign( uint( xx ) );
  26631. b.addAssign( uint( yy ) );
  26632. return mx_bjfinal( a, b, c );
  26633. } ).setLayout( {
  26634. name: 'mx_hash_int_4',
  26635. type: 'uint',
  26636. inputs: [
  26637. { name: 'x', type: 'int' },
  26638. { name: 'y', type: 'int' },
  26639. { name: 'z', type: 'int' },
  26640. { name: 'xx', type: 'int' },
  26641. { name: 'yy', type: 'int' }
  26642. ]
  26643. } );
  26644. 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 ] );
  26645. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26646. const y = int( y_immutable ).toVar();
  26647. const x = int( x_immutable ).toVar();
  26648. const h = uint( mx_hash_int( x, y ) ).toVar();
  26649. const result = uvec3().toVar();
  26650. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26651. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26652. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26653. return result;
  26654. } ).setLayout( {
  26655. name: 'mx_hash_vec3_0',
  26656. type: 'uvec3',
  26657. inputs: [
  26658. { name: 'x', type: 'int' },
  26659. { name: 'y', type: 'int' }
  26660. ]
  26661. } );
  26662. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26663. const z = int( z_immutable ).toVar();
  26664. const y = int( y_immutable ).toVar();
  26665. const x = int( x_immutable ).toVar();
  26666. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26667. const result = uvec3().toVar();
  26668. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26669. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26670. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26671. return result;
  26672. } ).setLayout( {
  26673. name: 'mx_hash_vec3_1',
  26674. type: 'uvec3',
  26675. inputs: [
  26676. { name: 'x', type: 'int' },
  26677. { name: 'y', type: 'int' },
  26678. { name: 'z', type: 'int' }
  26679. ]
  26680. } );
  26681. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26682. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26683. const p = vec2( p_immutable ).toVar();
  26684. const X = int().toVar(), Y = int().toVar();
  26685. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26686. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26687. const u = float( mx_fade( fx ) ).toVar();
  26688. const v = float( mx_fade( fy ) ).toVar();
  26689. 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();
  26690. return mx_gradient_scale2d( result );
  26691. } ).setLayout( {
  26692. name: 'mx_perlin_noise_float_0',
  26693. type: 'float',
  26694. inputs: [
  26695. { name: 'p', type: 'vec2' }
  26696. ]
  26697. } );
  26698. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26699. const p = vec3( p_immutable ).toVar();
  26700. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26701. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26702. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26703. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26704. const u = float( mx_fade( fx ) ).toVar();
  26705. const v = float( mx_fade( fy ) ).toVar();
  26706. const w = float( mx_fade( fz ) ).toVar();
  26707. 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();
  26708. return mx_gradient_scale3d( result );
  26709. } ).setLayout( {
  26710. name: 'mx_perlin_noise_float_1',
  26711. type: 'float',
  26712. inputs: [
  26713. { name: 'p', type: 'vec3' }
  26714. ]
  26715. } );
  26716. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26717. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26718. const p = vec2( p_immutable ).toVar();
  26719. const X = int().toVar(), Y = int().toVar();
  26720. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26721. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26722. const u = float( mx_fade( fx ) ).toVar();
  26723. const v = float( mx_fade( fy ) ).toVar();
  26724. 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();
  26725. return mx_gradient_scale2d( result );
  26726. } ).setLayout( {
  26727. name: 'mx_perlin_noise_vec3_0',
  26728. type: 'vec3',
  26729. inputs: [
  26730. { name: 'p', type: 'vec2' }
  26731. ]
  26732. } );
  26733. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26734. const p = vec3( p_immutable ).toVar();
  26735. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26736. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26737. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26738. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26739. const u = float( mx_fade( fx ) ).toVar();
  26740. const v = float( mx_fade( fy ) ).toVar();
  26741. const w = float( mx_fade( fz ) ).toVar();
  26742. 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();
  26743. return mx_gradient_scale3d( result );
  26744. } ).setLayout( {
  26745. name: 'mx_perlin_noise_vec3_1',
  26746. type: 'vec3',
  26747. inputs: [
  26748. { name: 'p', type: 'vec3' }
  26749. ]
  26750. } );
  26751. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26752. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26753. const p = float( p_immutable ).toVar();
  26754. const ix = int( mx_floor( p ) ).toVar();
  26755. return mx_bits_to_01( mx_hash_int( ix ) );
  26756. } ).setLayout( {
  26757. name: 'mx_cell_noise_float_0',
  26758. type: 'float',
  26759. inputs: [
  26760. { name: 'p', type: 'float' }
  26761. ]
  26762. } );
  26763. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26764. const p = vec2( p_immutable ).toVar();
  26765. const ix = int( mx_floor( p.x ) ).toVar();
  26766. const iy = int( mx_floor( p.y ) ).toVar();
  26767. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26768. } ).setLayout( {
  26769. name: 'mx_cell_noise_float_1',
  26770. type: 'float',
  26771. inputs: [
  26772. { name: 'p', type: 'vec2' }
  26773. ]
  26774. } );
  26775. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26776. const p = vec3( p_immutable ).toVar();
  26777. const ix = int( mx_floor( p.x ) ).toVar();
  26778. const iy = int( mx_floor( p.y ) ).toVar();
  26779. const iz = int( mx_floor( p.z ) ).toVar();
  26780. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26781. } ).setLayout( {
  26782. name: 'mx_cell_noise_float_2',
  26783. type: 'float',
  26784. inputs: [
  26785. { name: 'p', type: 'vec3' }
  26786. ]
  26787. } );
  26788. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26789. const p = vec4( p_immutable ).toVar();
  26790. const ix = int( mx_floor( p.x ) ).toVar();
  26791. const iy = int( mx_floor( p.y ) ).toVar();
  26792. const iz = int( mx_floor( p.z ) ).toVar();
  26793. const iw = int( mx_floor( p.w ) ).toVar();
  26794. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26795. } ).setLayout( {
  26796. name: 'mx_cell_noise_float_3',
  26797. type: 'float',
  26798. inputs: [
  26799. { name: 'p', type: 'vec4' }
  26800. ]
  26801. } );
  26802. 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 ] );
  26803. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26804. const p = float( p_immutable ).toVar();
  26805. const ix = int( mx_floor( p ) ).toVar();
  26806. 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 ) ) ) );
  26807. } ).setLayout( {
  26808. name: 'mx_cell_noise_vec3_0',
  26809. type: 'vec3',
  26810. inputs: [
  26811. { name: 'p', type: 'float' }
  26812. ]
  26813. } );
  26814. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26815. const p = vec2( p_immutable ).toVar();
  26816. const ix = int( mx_floor( p.x ) ).toVar();
  26817. const iy = int( mx_floor( p.y ) ).toVar();
  26818. 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 ) ) ) );
  26819. } ).setLayout( {
  26820. name: 'mx_cell_noise_vec3_1',
  26821. type: 'vec3',
  26822. inputs: [
  26823. { name: 'p', type: 'vec2' }
  26824. ]
  26825. } );
  26826. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26827. const p = vec3( p_immutable ).toVar();
  26828. const ix = int( mx_floor( p.x ) ).toVar();
  26829. const iy = int( mx_floor( p.y ) ).toVar();
  26830. const iz = int( mx_floor( p.z ) ).toVar();
  26831. 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 ) ) ) );
  26832. } ).setLayout( {
  26833. name: 'mx_cell_noise_vec3_2',
  26834. type: 'vec3',
  26835. inputs: [
  26836. { name: 'p', type: 'vec3' }
  26837. ]
  26838. } );
  26839. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26840. const p = vec4( p_immutable ).toVar();
  26841. const ix = int( mx_floor( p.x ) ).toVar();
  26842. const iy = int( mx_floor( p.y ) ).toVar();
  26843. const iz = int( mx_floor( p.z ) ).toVar();
  26844. const iw = int( mx_floor( p.w ) ).toVar();
  26845. 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 ) ) ) );
  26846. } ).setLayout( {
  26847. name: 'mx_cell_noise_vec3_3',
  26848. type: 'vec3',
  26849. inputs: [
  26850. { name: 'p', type: 'vec4' }
  26851. ]
  26852. } );
  26853. 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 ] );
  26854. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26855. const diminish = float( diminish_immutable ).toVar();
  26856. const lacunarity = float( lacunarity_immutable ).toVar();
  26857. const octaves = int( octaves_immutable ).toVar();
  26858. const p = vec3( p_immutable ).toVar();
  26859. const result = float( 0.0 ).toVar();
  26860. const amplitude = float( 1.0 ).toVar();
  26861. Loop( octaves, () => {
  26862. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26863. amplitude.mulAssign( diminish );
  26864. p.mulAssign( lacunarity );
  26865. } );
  26866. return result;
  26867. } ).setLayout( {
  26868. name: 'mx_fractal_noise_float',
  26869. type: 'float',
  26870. inputs: [
  26871. { name: 'p', type: 'vec3' },
  26872. { name: 'octaves', type: 'int' },
  26873. { name: 'lacunarity', type: 'float' },
  26874. { name: 'diminish', type: 'float' }
  26875. ]
  26876. } );
  26877. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26878. const diminish = float( diminish_immutable ).toVar();
  26879. const lacunarity = float( lacunarity_immutable ).toVar();
  26880. const octaves = int( octaves_immutable ).toVar();
  26881. const p = vec3( p_immutable ).toVar();
  26882. const result = vec3( 0.0 ).toVar();
  26883. const amplitude = float( 1.0 ).toVar();
  26884. Loop( octaves, () => {
  26885. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26886. amplitude.mulAssign( diminish );
  26887. p.mulAssign( lacunarity );
  26888. } );
  26889. return result;
  26890. } ).setLayout( {
  26891. name: 'mx_fractal_noise_vec3',
  26892. type: 'vec3',
  26893. inputs: [
  26894. { name: 'p', type: 'vec3' },
  26895. { name: 'octaves', type: 'int' },
  26896. { name: 'lacunarity', type: 'float' },
  26897. { name: 'diminish', type: 'float' }
  26898. ]
  26899. } );
  26900. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26901. const diminish = float( diminish_immutable ).toVar();
  26902. const lacunarity = float( lacunarity_immutable ).toVar();
  26903. const octaves = int( octaves_immutable ).toVar();
  26904. const p = vec3( p_immutable ).toVar();
  26905. 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 ) );
  26906. } ).setLayout( {
  26907. name: 'mx_fractal_noise_vec2',
  26908. type: 'vec2',
  26909. inputs: [
  26910. { name: 'p', type: 'vec3' },
  26911. { name: 'octaves', type: 'int' },
  26912. { name: 'lacunarity', type: 'float' },
  26913. { name: 'diminish', type: 'float' }
  26914. ]
  26915. } );
  26916. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26917. const diminish = float( diminish_immutable ).toVar();
  26918. const lacunarity = float( lacunarity_immutable ).toVar();
  26919. const octaves = int( octaves_immutable ).toVar();
  26920. const p = vec3( p_immutable ).toVar();
  26921. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26922. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26923. return vec4( c, f );
  26924. } ).setLayout( {
  26925. name: 'mx_fractal_noise_vec4',
  26926. type: 'vec4',
  26927. inputs: [
  26928. { name: 'p', type: 'vec3' },
  26929. { name: 'octaves', type: 'int' },
  26930. { name: 'lacunarity', type: 'float' },
  26931. { name: 'diminish', type: 'float' }
  26932. ]
  26933. } );
  26934. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26935. const metric = int( metric_immutable ).toVar();
  26936. const jitter = float( jitter_immutable ).toVar();
  26937. const yoff = int( yoff_immutable ).toVar();
  26938. const xoff = int( xoff_immutable ).toVar();
  26939. const y = int( y_immutable ).toVar();
  26940. const x = int( x_immutable ).toVar();
  26941. const p = vec2( p_immutable ).toVar();
  26942. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26943. const off = vec2( tmp.x, tmp.y ).toVar();
  26944. off.subAssign( 0.5 );
  26945. off.mulAssign( jitter );
  26946. off.addAssign( 0.5 );
  26947. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26948. const diff = vec2( cellpos.sub( p ) ).toVar();
  26949. If( metric.equal( int( 2 ) ), () => {
  26950. return abs( diff.x ).add( abs( diff.y ) );
  26951. } );
  26952. If( metric.equal( int( 3 ) ), () => {
  26953. return max$1( abs( diff.x ), abs( diff.y ) );
  26954. } );
  26955. return dot( diff, diff );
  26956. } ).setLayout( {
  26957. name: 'mx_worley_distance_0',
  26958. type: 'float',
  26959. inputs: [
  26960. { name: 'p', type: 'vec2' },
  26961. { name: 'x', type: 'int' },
  26962. { name: 'y', type: 'int' },
  26963. { name: 'xoff', type: 'int' },
  26964. { name: 'yoff', type: 'int' },
  26965. { name: 'jitter', type: 'float' },
  26966. { name: 'metric', type: 'int' }
  26967. ]
  26968. } );
  26969. 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 ] ) => {
  26970. const metric = int( metric_immutable ).toVar();
  26971. const jitter = float( jitter_immutable ).toVar();
  26972. const zoff = int( zoff_immutable ).toVar();
  26973. const yoff = int( yoff_immutable ).toVar();
  26974. const xoff = int( xoff_immutable ).toVar();
  26975. const z = int( z_immutable ).toVar();
  26976. const y = int( y_immutable ).toVar();
  26977. const x = int( x_immutable ).toVar();
  26978. const p = vec3( p_immutable ).toVar();
  26979. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26980. off.subAssign( 0.5 );
  26981. off.mulAssign( jitter );
  26982. off.addAssign( 0.5 );
  26983. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26984. const diff = vec3( cellpos.sub( p ) ).toVar();
  26985. If( metric.equal( int( 2 ) ), () => {
  26986. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26987. } );
  26988. If( metric.equal( int( 3 ) ), () => {
  26989. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26990. } );
  26991. return dot( diff, diff );
  26992. } ).setLayout( {
  26993. name: 'mx_worley_distance_1',
  26994. type: 'float',
  26995. inputs: [
  26996. { name: 'p', type: 'vec3' },
  26997. { name: 'x', type: 'int' },
  26998. { name: 'y', type: 'int' },
  26999. { name: 'z', type: 'int' },
  27000. { name: 'xoff', type: 'int' },
  27001. { name: 'yoff', type: 'int' },
  27002. { name: 'zoff', type: 'int' },
  27003. { name: 'jitter', type: 'float' },
  27004. { name: 'metric', type: 'int' }
  27005. ]
  27006. } );
  27007. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  27008. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27009. const metric = int( metric_immutable ).toVar();
  27010. const jitter = float( jitter_immutable ).toVar();
  27011. const p = vec2( p_immutable ).toVar();
  27012. const X = int().toVar(), Y = int().toVar();
  27013. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27014. const sqdist = float( 1e6 ).toVar();
  27015. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27016. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27017. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27018. sqdist.assign( min$1( sqdist, dist ) );
  27019. } );
  27020. } );
  27021. If( metric.equal( int( 0 ) ), () => {
  27022. sqdist.assign( sqrt( sqdist ) );
  27023. } );
  27024. return sqdist;
  27025. } ).setLayout( {
  27026. name: 'mx_worley_noise_float_0',
  27027. type: 'float',
  27028. inputs: [
  27029. { name: 'p', type: 'vec2' },
  27030. { name: 'jitter', type: 'float' },
  27031. { name: 'metric', type: 'int' }
  27032. ]
  27033. } );
  27034. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27035. const metric = int( metric_immutable ).toVar();
  27036. const jitter = float( jitter_immutable ).toVar();
  27037. const p = vec2( p_immutable ).toVar();
  27038. const X = int().toVar(), Y = int().toVar();
  27039. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27040. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27041. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27042. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27043. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27044. If( dist.lessThan( sqdist.x ), () => {
  27045. sqdist.y.assign( sqdist.x );
  27046. sqdist.x.assign( dist );
  27047. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27048. sqdist.y.assign( dist );
  27049. } );
  27050. } );
  27051. } );
  27052. If( metric.equal( int( 0 ) ), () => {
  27053. sqdist.assign( sqrt( sqdist ) );
  27054. } );
  27055. return sqdist;
  27056. } ).setLayout( {
  27057. name: 'mx_worley_noise_vec2_0',
  27058. type: 'vec2',
  27059. inputs: [
  27060. { name: 'p', type: 'vec2' },
  27061. { name: 'jitter', type: 'float' },
  27062. { name: 'metric', type: 'int' }
  27063. ]
  27064. } );
  27065. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27066. const metric = int( metric_immutable ).toVar();
  27067. const jitter = float( jitter_immutable ).toVar();
  27068. const p = vec2( p_immutable ).toVar();
  27069. const X = int().toVar(), Y = int().toVar();
  27070. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27071. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27072. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27073. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27074. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27075. If( dist.lessThan( sqdist.x ), () => {
  27076. sqdist.z.assign( sqdist.y );
  27077. sqdist.y.assign( sqdist.x );
  27078. sqdist.x.assign( dist );
  27079. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27080. sqdist.z.assign( sqdist.y );
  27081. sqdist.y.assign( dist );
  27082. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27083. sqdist.z.assign( dist );
  27084. } );
  27085. } );
  27086. } );
  27087. If( metric.equal( int( 0 ) ), () => {
  27088. sqdist.assign( sqrt( sqdist ) );
  27089. } );
  27090. return sqdist;
  27091. } ).setLayout( {
  27092. name: 'mx_worley_noise_vec3_0',
  27093. type: 'vec3',
  27094. inputs: [
  27095. { name: 'p', type: 'vec2' },
  27096. { name: 'jitter', type: 'float' },
  27097. { name: 'metric', type: 'int' }
  27098. ]
  27099. } );
  27100. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27101. const metric = int( metric_immutable ).toVar();
  27102. const jitter = float( jitter_immutable ).toVar();
  27103. const p = vec3( p_immutable ).toVar();
  27104. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27105. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27106. const sqdist = float( 1e6 ).toVar();
  27107. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27108. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27109. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27110. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27111. sqdist.assign( min$1( sqdist, dist ) );
  27112. } );
  27113. } );
  27114. } );
  27115. If( metric.equal( int( 0 ) ), () => {
  27116. sqdist.assign( sqrt( sqdist ) );
  27117. } );
  27118. return sqdist;
  27119. } ).setLayout( {
  27120. name: 'mx_worley_noise_float_1',
  27121. type: 'float',
  27122. inputs: [
  27123. { name: 'p', type: 'vec3' },
  27124. { name: 'jitter', type: 'float' },
  27125. { name: 'metric', type: 'int' }
  27126. ]
  27127. } );
  27128. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27129. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27130. const metric = int( metric_immutable ).toVar();
  27131. const jitter = float( jitter_immutable ).toVar();
  27132. const p = vec3( p_immutable ).toVar();
  27133. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27134. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27135. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27136. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27137. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27138. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27139. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27140. If( dist.lessThan( sqdist.x ), () => {
  27141. sqdist.y.assign( sqdist.x );
  27142. sqdist.x.assign( dist );
  27143. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27144. sqdist.y.assign( dist );
  27145. } );
  27146. } );
  27147. } );
  27148. } );
  27149. If( metric.equal( int( 0 ) ), () => {
  27150. sqdist.assign( sqrt( sqdist ) );
  27151. } );
  27152. return sqdist;
  27153. } ).setLayout( {
  27154. name: 'mx_worley_noise_vec2_1',
  27155. type: 'vec2',
  27156. inputs: [
  27157. { name: 'p', type: 'vec3' },
  27158. { name: 'jitter', type: 'float' },
  27159. { name: 'metric', type: 'int' }
  27160. ]
  27161. } );
  27162. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27163. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27164. const metric = int( metric_immutable ).toVar();
  27165. const jitter = float( jitter_immutable ).toVar();
  27166. const p = vec3( p_immutable ).toVar();
  27167. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27168. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27169. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27170. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27171. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27172. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27173. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27174. If( dist.lessThan( sqdist.x ), () => {
  27175. sqdist.z.assign( sqdist.y );
  27176. sqdist.y.assign( sqdist.x );
  27177. sqdist.x.assign( dist );
  27178. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27179. sqdist.z.assign( sqdist.y );
  27180. sqdist.y.assign( dist );
  27181. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27182. sqdist.z.assign( dist );
  27183. } );
  27184. } );
  27185. } );
  27186. } );
  27187. If( metric.equal( int( 0 ) ), () => {
  27188. sqdist.assign( sqrt( sqdist ) );
  27189. } );
  27190. return sqdist;
  27191. } ).setLayout( {
  27192. name: 'mx_worley_noise_vec3_1',
  27193. type: 'vec3',
  27194. inputs: [
  27195. { name: 'p', type: 'vec3' },
  27196. { name: 'jitter', type: 'float' },
  27197. { name: 'metric', type: 'int' }
  27198. ]
  27199. } );
  27200. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27201. // Three.js Transpiler
  27202. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27203. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27204. const s = hsv.y;
  27205. const v = hsv.z;
  27206. const result = vec3().toVar();
  27207. If( s.lessThan( 0.0001 ), () => {
  27208. result.assign( vec3( v, v, v ) );
  27209. } ).Else( () => {
  27210. let h = hsv.x;
  27211. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27212. const hi = int( trunc( h ) );
  27213. const f = h.sub( float( hi ) );
  27214. const p = v.mul( s.oneMinus() );
  27215. const q = v.mul( s.mul( f ).oneMinus() );
  27216. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27217. If( hi.equal( int( 0 ) ), () => {
  27218. result.assign( vec3( v, t, p ) );
  27219. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27220. result.assign( vec3( q, v, p ) );
  27221. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27222. result.assign( vec3( p, v, t ) );
  27223. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27224. result.assign( vec3( p, q, v ) );
  27225. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27226. result.assign( vec3( t, p, v ) );
  27227. } ).Else( () => {
  27228. result.assign( vec3( v, p, q ) );
  27229. } );
  27230. } );
  27231. return result;
  27232. } ).setLayout( {
  27233. name: 'mx_hsvtorgb',
  27234. type: 'vec3',
  27235. inputs: [
  27236. { name: 'hsv', type: 'vec3' }
  27237. ]
  27238. } );
  27239. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27240. const c = vec3( c_immutable ).toVar();
  27241. const r = float( c.x ).toVar();
  27242. const g = float( c.y ).toVar();
  27243. const b = float( c.z ).toVar();
  27244. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27245. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27246. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27247. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27248. v.assign( maxcomp );
  27249. If( maxcomp.greaterThan( 0.0 ), () => {
  27250. s.assign( delta.div( maxcomp ) );
  27251. } ).Else( () => {
  27252. s.assign( 0.0 );
  27253. } );
  27254. If( s.lessThanEqual( 0.0 ), () => {
  27255. h.assign( 0.0 );
  27256. } ).Else( () => {
  27257. If( r.greaterThanEqual( maxcomp ), () => {
  27258. h.assign( g.sub( b ).div( delta ) );
  27259. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27260. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27261. } ).Else( () => {
  27262. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27263. } );
  27264. h.mulAssign( 1.0 / 6.0 );
  27265. If( h.lessThan( 0.0 ), () => {
  27266. h.addAssign( 1.0 );
  27267. } );
  27268. } );
  27269. return vec3( h, s, v );
  27270. } ).setLayout( {
  27271. name: 'mx_rgbtohsv',
  27272. type: 'vec3',
  27273. inputs: [
  27274. { name: 'c', type: 'vec3' }
  27275. ]
  27276. } );
  27277. // Three.js Transpiler
  27278. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27279. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27280. const color = vec3( color_immutable ).toVar();
  27281. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27282. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27283. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27284. return mix( linSeg, powSeg, isAbove );
  27285. } ).setLayout( {
  27286. name: 'mx_srgb_texture_to_lin_rec709',
  27287. type: 'vec3',
  27288. inputs: [
  27289. { name: 'color', type: 'vec3' }
  27290. ]
  27291. } );
  27292. const mx_aastep = ( threshold, value ) => {
  27293. threshold = float( threshold );
  27294. value = float( value );
  27295. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27296. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27297. };
  27298. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27299. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27300. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27301. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27302. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27303. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27304. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27305. const mx_safepower = ( in1, in2 = 1 ) => {
  27306. in1 = float( in1 );
  27307. return in1.abs().pow( in2 ).mul( in1.sign() );
  27308. };
  27309. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27310. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27311. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27312. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27313. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27314. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27315. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27316. return noise_vec4.mul( amplitude ).add( pivot );
  27317. };
  27318. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27319. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27320. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27321. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27322. 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 );
  27323. 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 );
  27324. 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 );
  27325. 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 );
  27326. /** @module getParallaxCorrectNormal **/
  27327. /**
  27328. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27329. *
  27330. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27331. *
  27332. * ```js
  27333. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27334. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27335. * ```
  27336. * @function
  27337. * @param {Node<vec3>} normal - The normal to correct.
  27338. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27339. * @param {Node<vec3>} cubePos - The cube position.
  27340. * @return {Node<vec3>} The parallax corrected normal.
  27341. */
  27342. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27343. const nDir = normalize( normal ).toVar( 'nDir' );
  27344. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27345. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27346. const rbminmax = vec3().toVar( 'rbminmax' );
  27347. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27348. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27349. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27350. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27351. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27352. return boxIntersection.sub( cubePos );
  27353. } );
  27354. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27355. // normal is assumed to have unit length
  27356. const x = normal.x, y = normal.y, z = normal.z;
  27357. // band 0
  27358. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27359. // band 1
  27360. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27361. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27362. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27363. // band 2
  27364. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27365. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27366. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27367. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27368. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27369. return result;
  27370. } );
  27371. // constants
  27372. var TSL = /*#__PURE__*/Object.freeze({
  27373. __proto__: null,
  27374. BRDF_GGX: BRDF_GGX,
  27375. BRDF_Lambert: BRDF_Lambert,
  27376. BasicShadowFilter: BasicShadowFilter,
  27377. Break: Break,
  27378. Const: Const,
  27379. Continue: Continue,
  27380. DFGApprox: DFGApprox,
  27381. D_GGX: D_GGX,
  27382. Discard: Discard,
  27383. EPSILON: EPSILON,
  27384. F_Schlick: F_Schlick,
  27385. Fn: Fn,
  27386. INFINITY: INFINITY,
  27387. If: If,
  27388. Loop: Loop,
  27389. NodeAccess: NodeAccess,
  27390. NodeShaderStage: NodeShaderStage,
  27391. NodeType: NodeType,
  27392. NodeUpdateType: NodeUpdateType,
  27393. PCFShadowFilter: PCFShadowFilter,
  27394. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27395. PI: PI,
  27396. PI2: PI2,
  27397. Return: Return,
  27398. Schlick_to_F0: Schlick_to_F0,
  27399. ScriptableNodeResources: ScriptableNodeResources,
  27400. ShaderNode: ShaderNode,
  27401. TBNViewMatrix: TBNViewMatrix,
  27402. VSMShadowFilter: VSMShadowFilter,
  27403. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27404. Var: Var,
  27405. abs: abs,
  27406. acesFilmicToneMapping: acesFilmicToneMapping,
  27407. acos: acos,
  27408. add: add,
  27409. addMethodChaining: addMethodChaining,
  27410. addNodeElement: addNodeElement,
  27411. agxToneMapping: agxToneMapping,
  27412. all: all,
  27413. alphaT: alphaT,
  27414. and: and,
  27415. anisotropy: anisotropy,
  27416. anisotropyB: anisotropyB,
  27417. anisotropyT: anisotropyT,
  27418. any: any,
  27419. append: append,
  27420. array: array,
  27421. arrayBuffer: arrayBuffer,
  27422. asin: asin,
  27423. assign: assign,
  27424. atan: atan,
  27425. atan2: atan2,
  27426. atomicAdd: atomicAdd,
  27427. atomicAnd: atomicAnd,
  27428. atomicFunc: atomicFunc,
  27429. atomicLoad: atomicLoad,
  27430. atomicMax: atomicMax,
  27431. atomicMin: atomicMin,
  27432. atomicOr: atomicOr,
  27433. atomicStore: atomicStore,
  27434. atomicSub: atomicSub,
  27435. atomicXor: atomicXor,
  27436. attenuationColor: attenuationColor,
  27437. attenuationDistance: attenuationDistance,
  27438. attribute: attribute,
  27439. attributeArray: attributeArray,
  27440. backgroundBlurriness: backgroundBlurriness,
  27441. backgroundIntensity: backgroundIntensity,
  27442. backgroundRotation: backgroundRotation,
  27443. batch: batch,
  27444. billboarding: billboarding,
  27445. bitAnd: bitAnd,
  27446. bitNot: bitNot,
  27447. bitOr: bitOr,
  27448. bitXor: bitXor,
  27449. bitangentGeometry: bitangentGeometry,
  27450. bitangentLocal: bitangentLocal,
  27451. bitangentView: bitangentView,
  27452. bitangentWorld: bitangentWorld,
  27453. bitcast: bitcast,
  27454. blendBurn: blendBurn,
  27455. blendColor: blendColor,
  27456. blendDodge: blendDodge,
  27457. blendOverlay: blendOverlay,
  27458. blendScreen: blendScreen,
  27459. blur: blur,
  27460. bool: bool,
  27461. buffer: buffer,
  27462. bufferAttribute: bufferAttribute,
  27463. bumpMap: bumpMap,
  27464. burn: burn,
  27465. bvec2: bvec2,
  27466. bvec3: bvec3,
  27467. bvec4: bvec4,
  27468. bypass: bypass,
  27469. cache: cache,
  27470. call: call,
  27471. cameraFar: cameraFar,
  27472. cameraIndex: cameraIndex,
  27473. cameraNear: cameraNear,
  27474. cameraNormalMatrix: cameraNormalMatrix,
  27475. cameraPosition: cameraPosition,
  27476. cameraProjectionMatrix: cameraProjectionMatrix,
  27477. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27478. cameraViewMatrix: cameraViewMatrix,
  27479. cameraWorldMatrix: cameraWorldMatrix,
  27480. cbrt: cbrt,
  27481. cdl: cdl,
  27482. ceil: ceil,
  27483. checker: checker,
  27484. cineonToneMapping: cineonToneMapping,
  27485. clamp: clamp,
  27486. clearcoat: clearcoat,
  27487. clearcoatRoughness: clearcoatRoughness,
  27488. code: code,
  27489. color: color,
  27490. colorSpaceToWorking: colorSpaceToWorking,
  27491. colorToDirection: colorToDirection,
  27492. compute: compute,
  27493. cond: cond,
  27494. context: context,
  27495. convert: convert,
  27496. convertColorSpace: convertColorSpace,
  27497. convertToTexture: convertToTexture,
  27498. cos: cos,
  27499. cross: cross,
  27500. cubeTexture: cubeTexture,
  27501. dFdx: dFdx,
  27502. dFdy: dFdy,
  27503. dashSize: dashSize,
  27504. defaultBuildStages: defaultBuildStages,
  27505. defaultShaderStages: defaultShaderStages,
  27506. defined: defined,
  27507. degrees: degrees,
  27508. deltaTime: deltaTime,
  27509. densityFog: densityFog,
  27510. densityFogFactor: densityFogFactor,
  27511. depth: depth,
  27512. depthPass: depthPass,
  27513. difference: difference,
  27514. diffuseColor: diffuseColor,
  27515. directPointLight: directPointLight,
  27516. directionToColor: directionToColor,
  27517. dispersion: dispersion,
  27518. distance: distance,
  27519. div: div,
  27520. dodge: dodge,
  27521. dot: dot,
  27522. drawIndex: drawIndex,
  27523. dynamicBufferAttribute: dynamicBufferAttribute,
  27524. element: element,
  27525. emissive: emissive,
  27526. equal: equal,
  27527. equals: equals,
  27528. equirectUV: equirectUV,
  27529. exp: exp,
  27530. exp2: exp2,
  27531. expression: expression,
  27532. faceDirection: faceDirection,
  27533. faceForward: faceForward,
  27534. faceforward: faceforward,
  27535. float: float,
  27536. floor: floor,
  27537. fog: fog,
  27538. fract: fract,
  27539. frameGroup: frameGroup,
  27540. frameId: frameId,
  27541. frontFacing: frontFacing,
  27542. fwidth: fwidth,
  27543. gain: gain,
  27544. gapSize: gapSize,
  27545. getConstNodeType: getConstNodeType,
  27546. getCurrentStack: getCurrentStack,
  27547. getDirection: getDirection,
  27548. getDistanceAttenuation: getDistanceAttenuation,
  27549. getGeometryRoughness: getGeometryRoughness,
  27550. getNormalFromDepth: getNormalFromDepth,
  27551. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27552. getRoughness: getRoughness,
  27553. getScreenPosition: getScreenPosition,
  27554. getShIrradianceAt: getShIrradianceAt,
  27555. getTextureIndex: getTextureIndex,
  27556. getViewPosition: getViewPosition,
  27557. globalId: globalId,
  27558. glsl: glsl,
  27559. glslFn: glslFn,
  27560. grayscale: grayscale,
  27561. greaterThan: greaterThan,
  27562. greaterThanEqual: greaterThanEqual,
  27563. hash: hash,
  27564. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27565. highpModelViewMatrix: highpModelViewMatrix,
  27566. hue: hue,
  27567. instance: instance,
  27568. instanceIndex: instanceIndex,
  27569. instancedArray: instancedArray,
  27570. instancedBufferAttribute: instancedBufferAttribute,
  27571. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27572. instancedMesh: instancedMesh,
  27573. int: int,
  27574. inverseSqrt: inverseSqrt,
  27575. inversesqrt: inversesqrt,
  27576. invocationLocalIndex: invocationLocalIndex,
  27577. invocationSubgroupIndex: invocationSubgroupIndex,
  27578. ior: ior,
  27579. iridescence: iridescence,
  27580. iridescenceIOR: iridescenceIOR,
  27581. iridescenceThickness: iridescenceThickness,
  27582. ivec2: ivec2,
  27583. ivec3: ivec3,
  27584. ivec4: ivec4,
  27585. js: js,
  27586. label: label,
  27587. length: length,
  27588. lengthSq: lengthSq,
  27589. lessThan: lessThan,
  27590. lessThanEqual: lessThanEqual,
  27591. lightPosition: lightPosition,
  27592. lightProjectionUV: lightProjectionUV,
  27593. lightShadowMatrix: lightShadowMatrix,
  27594. lightTargetDirection: lightTargetDirection,
  27595. lightTargetPosition: lightTargetPosition,
  27596. lightViewPosition: lightViewPosition,
  27597. lightingContext: lightingContext,
  27598. lights: lights,
  27599. linearDepth: linearDepth,
  27600. linearToneMapping: linearToneMapping,
  27601. localId: localId,
  27602. log: log,
  27603. log2: log2,
  27604. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27605. loop: loop,
  27606. luminance: luminance,
  27607. mat2: mat2,
  27608. mat3: mat3,
  27609. mat4: mat4,
  27610. matcapUV: matcapUV,
  27611. materialAO: materialAO,
  27612. materialAlphaTest: materialAlphaTest,
  27613. materialAnisotropy: materialAnisotropy,
  27614. materialAnisotropyVector: materialAnisotropyVector,
  27615. materialAttenuationColor: materialAttenuationColor,
  27616. materialAttenuationDistance: materialAttenuationDistance,
  27617. materialClearcoat: materialClearcoat,
  27618. materialClearcoatNormal: materialClearcoatNormal,
  27619. materialClearcoatRoughness: materialClearcoatRoughness,
  27620. materialColor: materialColor,
  27621. materialDispersion: materialDispersion,
  27622. materialEmissive: materialEmissive,
  27623. materialIOR: materialIOR,
  27624. materialIridescence: materialIridescence,
  27625. materialIridescenceIOR: materialIridescenceIOR,
  27626. materialIridescenceThickness: materialIridescenceThickness,
  27627. materialLightMap: materialLightMap,
  27628. materialLineDashOffset: materialLineDashOffset,
  27629. materialLineDashSize: materialLineDashSize,
  27630. materialLineGapSize: materialLineGapSize,
  27631. materialLineScale: materialLineScale,
  27632. materialLineWidth: materialLineWidth,
  27633. materialMetalness: materialMetalness,
  27634. materialNormal: materialNormal,
  27635. materialOpacity: materialOpacity,
  27636. materialPointSize: materialPointSize,
  27637. materialReference: materialReference,
  27638. materialReflectivity: materialReflectivity,
  27639. materialRefractionRatio: materialRefractionRatio,
  27640. materialRotation: materialRotation,
  27641. materialRoughness: materialRoughness,
  27642. materialSheen: materialSheen,
  27643. materialSheenRoughness: materialSheenRoughness,
  27644. materialShininess: materialShininess,
  27645. materialSpecular: materialSpecular,
  27646. materialSpecularColor: materialSpecularColor,
  27647. materialSpecularIntensity: materialSpecularIntensity,
  27648. materialSpecularStrength: materialSpecularStrength,
  27649. materialThickness: materialThickness,
  27650. materialTransmission: materialTransmission,
  27651. max: max$1,
  27652. maxMipLevel: maxMipLevel,
  27653. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27654. metalness: metalness,
  27655. min: min$1,
  27656. mix: mix,
  27657. mixElement: mixElement,
  27658. mod: mod,
  27659. modInt: modInt,
  27660. modelDirection: modelDirection,
  27661. modelNormalMatrix: modelNormalMatrix,
  27662. modelPosition: modelPosition,
  27663. modelScale: modelScale,
  27664. modelViewMatrix: modelViewMatrix,
  27665. modelViewPosition: modelViewPosition,
  27666. modelViewProjection: modelViewProjection,
  27667. modelWorldMatrix: modelWorldMatrix,
  27668. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27669. morphReference: morphReference,
  27670. mrt: mrt,
  27671. mul: mul,
  27672. mx_aastep: mx_aastep,
  27673. mx_cell_noise_float: mx_cell_noise_float,
  27674. mx_contrast: mx_contrast,
  27675. mx_fractal_noise_float: mx_fractal_noise_float,
  27676. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27677. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27678. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27679. mx_hsvtorgb: mx_hsvtorgb,
  27680. mx_noise_float: mx_noise_float,
  27681. mx_noise_vec3: mx_noise_vec3,
  27682. mx_noise_vec4: mx_noise_vec4,
  27683. mx_ramplr: mx_ramplr,
  27684. mx_ramptb: mx_ramptb,
  27685. mx_rgbtohsv: mx_rgbtohsv,
  27686. mx_safepower: mx_safepower,
  27687. mx_splitlr: mx_splitlr,
  27688. mx_splittb: mx_splittb,
  27689. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27690. mx_transform_uv: mx_transform_uv,
  27691. mx_worley_noise_float: mx_worley_noise_float,
  27692. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27693. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27694. negate: negate,
  27695. neutralToneMapping: neutralToneMapping,
  27696. nodeArray: nodeArray,
  27697. nodeImmutable: nodeImmutable,
  27698. nodeObject: nodeObject,
  27699. nodeObjects: nodeObjects,
  27700. nodeProxy: nodeProxy,
  27701. normalFlat: normalFlat,
  27702. normalGeometry: normalGeometry,
  27703. normalLocal: normalLocal,
  27704. normalMap: normalMap,
  27705. normalView: normalView,
  27706. normalWorld: normalWorld,
  27707. normalize: normalize,
  27708. not: not,
  27709. notEqual: notEqual,
  27710. numWorkgroups: numWorkgroups,
  27711. objectDirection: objectDirection,
  27712. objectGroup: objectGroup,
  27713. objectPosition: objectPosition,
  27714. objectScale: objectScale,
  27715. objectViewPosition: objectViewPosition,
  27716. objectWorldMatrix: objectWorldMatrix,
  27717. oneMinus: oneMinus,
  27718. or: or,
  27719. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27720. oscSawtooth: oscSawtooth,
  27721. oscSine: oscSine,
  27722. oscSquare: oscSquare,
  27723. oscTriangle: oscTriangle,
  27724. output: output,
  27725. outputStruct: outputStruct,
  27726. overlay: overlay,
  27727. overloadingFn: overloadingFn,
  27728. parabola: parabola,
  27729. parallaxDirection: parallaxDirection,
  27730. parallaxUV: parallaxUV,
  27731. parameter: parameter,
  27732. pass: pass,
  27733. passTexture: passTexture,
  27734. pcurve: pcurve,
  27735. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27736. pmremTexture: pmremTexture,
  27737. pointUV: pointUV,
  27738. pointWidth: pointWidth,
  27739. positionGeometry: positionGeometry,
  27740. positionLocal: positionLocal,
  27741. positionPrevious: positionPrevious,
  27742. positionView: positionView,
  27743. positionViewDirection: positionViewDirection,
  27744. positionWorld: positionWorld,
  27745. positionWorldDirection: positionWorldDirection,
  27746. posterize: posterize,
  27747. pow: pow,
  27748. pow2: pow2,
  27749. pow3: pow3,
  27750. pow4: pow4,
  27751. property: property,
  27752. radians: radians,
  27753. rand: rand,
  27754. range: range,
  27755. rangeFog: rangeFog,
  27756. rangeFogFactor: rangeFogFactor,
  27757. reciprocal: reciprocal,
  27758. reference: reference,
  27759. referenceBuffer: referenceBuffer,
  27760. reflect: reflect,
  27761. reflectVector: reflectVector,
  27762. reflectView: reflectView,
  27763. reflector: reflector,
  27764. refract: refract,
  27765. refractVector: refractVector,
  27766. refractView: refractView,
  27767. reinhardToneMapping: reinhardToneMapping,
  27768. remainder: remainder,
  27769. remap: remap,
  27770. remapClamp: remapClamp,
  27771. renderGroup: renderGroup,
  27772. renderOutput: renderOutput,
  27773. rendererReference: rendererReference,
  27774. rotate: rotate,
  27775. rotateUV: rotateUV,
  27776. roughness: roughness,
  27777. round: round,
  27778. rtt: rtt,
  27779. sRGBTransferEOTF: sRGBTransferEOTF,
  27780. sRGBTransferOETF: sRGBTransferOETF,
  27781. sampler: sampler,
  27782. saturate: saturate,
  27783. saturation: saturation,
  27784. screen: screen,
  27785. screenCoordinate: screenCoordinate,
  27786. screenSize: screenSize,
  27787. screenUV: screenUV,
  27788. scriptable: scriptable,
  27789. scriptableValue: scriptableValue,
  27790. select: select,
  27791. setCurrentStack: setCurrentStack,
  27792. shaderStages: shaderStages,
  27793. shadow: shadow,
  27794. shadowPositionWorld: shadowPositionWorld,
  27795. shapeCircle: shapeCircle,
  27796. sharedUniformGroup: sharedUniformGroup,
  27797. sheen: sheen,
  27798. sheenRoughness: sheenRoughness,
  27799. shiftLeft: shiftLeft,
  27800. shiftRight: shiftRight,
  27801. shininess: shininess,
  27802. sign: sign,
  27803. sin: sin,
  27804. sinc: sinc,
  27805. skinning: skinning,
  27806. skinningReference: skinningReference,
  27807. smoothstep: smoothstep,
  27808. smoothstepElement: smoothstepElement,
  27809. specularColor: specularColor,
  27810. specularF90: specularF90,
  27811. spherizeUV: spherizeUV,
  27812. split: split,
  27813. spritesheetUV: spritesheetUV,
  27814. sqrt: sqrt,
  27815. stack: stack,
  27816. step: step,
  27817. storage: storage,
  27818. storageBarrier: storageBarrier,
  27819. storageObject: storageObject,
  27820. storageTexture: storageTexture,
  27821. string: string,
  27822. sub: sub,
  27823. subgroupIndex: subgroupIndex,
  27824. subgroupSize: subgroupSize,
  27825. tan: tan,
  27826. tangentGeometry: tangentGeometry,
  27827. tangentLocal: tangentLocal,
  27828. tangentView: tangentView,
  27829. tangentWorld: tangentWorld,
  27830. temp: temp,
  27831. texture: texture,
  27832. texture3D: texture3D,
  27833. textureBarrier: textureBarrier,
  27834. textureBicubic: textureBicubic,
  27835. textureCubeUV: textureCubeUV,
  27836. textureLoad: textureLoad,
  27837. textureSize: textureSize,
  27838. textureStore: textureStore,
  27839. thickness: thickness,
  27840. time: time,
  27841. timerDelta: timerDelta,
  27842. timerGlobal: timerGlobal,
  27843. timerLocal: timerLocal,
  27844. toOutputColorSpace: toOutputColorSpace,
  27845. toWorkingColorSpace: toWorkingColorSpace,
  27846. toneMapping: toneMapping,
  27847. toneMappingExposure: toneMappingExposure,
  27848. toonOutlinePass: toonOutlinePass,
  27849. transformDirection: transformDirection,
  27850. transformNormal: transformNormal,
  27851. transformNormalToView: transformNormalToView,
  27852. transformedBentNormalView: transformedBentNormalView,
  27853. transformedBitangentView: transformedBitangentView,
  27854. transformedBitangentWorld: transformedBitangentWorld,
  27855. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27856. transformedNormalView: transformedNormalView,
  27857. transformedNormalWorld: transformedNormalWorld,
  27858. transformedTangentView: transformedTangentView,
  27859. transformedTangentWorld: transformedTangentWorld,
  27860. transmission: transmission,
  27861. transpose: transpose,
  27862. triNoise3D: triNoise3D,
  27863. triplanarTexture: triplanarTexture,
  27864. triplanarTextures: triplanarTextures,
  27865. trunc: trunc,
  27866. tslFn: tslFn,
  27867. uint: uint,
  27868. uniform: uniform,
  27869. uniformArray: uniformArray,
  27870. uniformGroup: uniformGroup,
  27871. uniforms: uniforms,
  27872. userData: userData,
  27873. uv: uv,
  27874. uvec2: uvec2,
  27875. uvec3: uvec3,
  27876. uvec4: uvec4,
  27877. varying: varying,
  27878. varyingProperty: varyingProperty,
  27879. vec2: vec2,
  27880. vec3: vec3,
  27881. vec4: vec4,
  27882. vectorComponents: vectorComponents,
  27883. velocity: velocity,
  27884. vertexColor: vertexColor,
  27885. vertexIndex: vertexIndex,
  27886. vertexStage: vertexStage,
  27887. vibrance: vibrance,
  27888. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27889. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27890. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27891. viewport: viewport,
  27892. viewportBottomLeft: viewportBottomLeft,
  27893. viewportCoordinate: viewportCoordinate,
  27894. viewportDepthTexture: viewportDepthTexture,
  27895. viewportLinearDepth: viewportLinearDepth,
  27896. viewportMipTexture: viewportMipTexture,
  27897. viewportResolution: viewportResolution,
  27898. viewportSafeUV: viewportSafeUV,
  27899. viewportSharedTexture: viewportSharedTexture,
  27900. viewportSize: viewportSize,
  27901. viewportTexture: viewportTexture,
  27902. viewportTopLeft: viewportTopLeft,
  27903. viewportUV: viewportUV,
  27904. wgsl: wgsl,
  27905. wgslFn: wgslFn,
  27906. workgroupArray: workgroupArray,
  27907. workgroupBarrier: workgroupBarrier,
  27908. workgroupId: workgroupId,
  27909. workingToColorSpace: workingToColorSpace,
  27910. xor: xor
  27911. });
  27912. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27913. /**
  27914. * This renderer module manages the background.
  27915. *
  27916. * @private
  27917. * @augments DataMap
  27918. */
  27919. class Background extends DataMap {
  27920. /**
  27921. * Constructs a new background management component.
  27922. *
  27923. * @param {Renderer} renderer - The renderer.
  27924. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27925. */
  27926. constructor( renderer, nodes ) {
  27927. super();
  27928. /**
  27929. * The renderer.
  27930. *
  27931. * @type {Renderer}
  27932. */
  27933. this.renderer = renderer;
  27934. /**
  27935. * Renderer component for managing nodes related logic.
  27936. *
  27937. * @type {Nodes}
  27938. */
  27939. this.nodes = nodes;
  27940. }
  27941. /**
  27942. * Updates the background for the given scene. Depending on how `Scene.background`
  27943. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27944. * or add a mesh to the render list for rendering the background as a textured plane
  27945. * or skybox.
  27946. *
  27947. * @param {Scene} scene - The scene.
  27948. * @param {RenderList} renderList - The current render list.
  27949. * @param {RenderContext} renderContext - The current render context.
  27950. */
  27951. update( scene, renderList, renderContext ) {
  27952. const renderer = this.renderer;
  27953. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27954. let forceClear = false;
  27955. if ( background === null ) {
  27956. // no background settings, use clear color configuration from the renderer
  27957. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27958. _clearColor$1.a = renderer._clearColor.a;
  27959. } else if ( background.isColor === true ) {
  27960. // background is an opaque color
  27961. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27962. _clearColor$1.a = 1;
  27963. forceClear = true;
  27964. } else if ( background.isNode === true ) {
  27965. const sceneData = this.get( scene );
  27966. const backgroundNode = background;
  27967. _clearColor$1.copy( renderer._clearColor );
  27968. let backgroundMesh = sceneData.backgroundMesh;
  27969. if ( backgroundMesh === undefined ) {
  27970. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27971. // @TODO: Add Texture2D support using node context
  27972. getUV: () => backgroundRotation.mul( normalWorld ),
  27973. getTextureLevel: () => backgroundBlurriness
  27974. } );
  27975. let viewProj = modelViewProjection;
  27976. viewProj = viewProj.setZ( viewProj.w );
  27977. const nodeMaterial = new NodeMaterial();
  27978. nodeMaterial.name = 'Background.material';
  27979. nodeMaterial.side = BackSide;
  27980. nodeMaterial.depthTest = false;
  27981. nodeMaterial.depthWrite = false;
  27982. nodeMaterial.fog = false;
  27983. nodeMaterial.lights = false;
  27984. nodeMaterial.vertexNode = viewProj;
  27985. nodeMaterial.colorNode = backgroundMeshNode;
  27986. sceneData.backgroundMeshNode = backgroundMeshNode;
  27987. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27988. backgroundMesh.frustumCulled = false;
  27989. backgroundMesh.name = 'Background.mesh';
  27990. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27991. this.matrixWorld.copyPosition( camera.matrixWorld );
  27992. };
  27993. }
  27994. const backgroundCacheKey = backgroundNode.getCacheKey();
  27995. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27996. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27997. sceneData.backgroundMeshNode.needsUpdate = true;
  27998. backgroundMesh.material.needsUpdate = true;
  27999. sceneData.backgroundCacheKey = backgroundCacheKey;
  28000. }
  28001. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  28002. } else {
  28003. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  28004. }
  28005. //
  28006. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  28007. if ( environmentBlendMode === 'additive' ) {
  28008. _clearColor$1.set( 0, 0, 0, 1 );
  28009. } else if ( environmentBlendMode === 'alpha-blend' ) {
  28010. _clearColor$1.set( 0, 0, 0, 0 );
  28011. }
  28012. //
  28013. if ( renderer.autoClear === true || forceClear === true ) {
  28014. const clearColorValue = renderContext.clearColorValue;
  28015. clearColorValue.r = _clearColor$1.r;
  28016. clearColorValue.g = _clearColor$1.g;
  28017. clearColorValue.b = _clearColor$1.b;
  28018. clearColorValue.a = _clearColor$1.a;
  28019. // premultiply alpha
  28020. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  28021. clearColorValue.r *= clearColorValue.a;
  28022. clearColorValue.g *= clearColorValue.a;
  28023. clearColorValue.b *= clearColorValue.a;
  28024. }
  28025. //
  28026. renderContext.depthClearValue = renderer._clearDepth;
  28027. renderContext.stencilClearValue = renderer._clearStencil;
  28028. renderContext.clearColor = renderer.autoClearColor === true;
  28029. renderContext.clearDepth = renderer.autoClearDepth === true;
  28030. renderContext.clearStencil = renderer.autoClearStencil === true;
  28031. } else {
  28032. renderContext.clearColor = false;
  28033. renderContext.clearDepth = false;
  28034. renderContext.clearStencil = false;
  28035. }
  28036. }
  28037. }
  28038. let _id$6 = 0;
  28039. /**
  28040. * A bind group represents a collection of bindings and thus a collection
  28041. * or resources. Bind groups are assigned to pipelines to provide them
  28042. * with the required resources (like uniform buffers or textures).
  28043. *
  28044. * @private
  28045. */
  28046. class BindGroup {
  28047. /**
  28048. * Constructs a new bind group.
  28049. *
  28050. * @param {String} name - The bind group's name.
  28051. * @param {Array<Binding>} bindings - An array of bindings.
  28052. * @param {Number} index - The group index.
  28053. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  28054. */
  28055. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  28056. /**
  28057. * The bind group's name.
  28058. *
  28059. * @type {String}
  28060. */
  28061. this.name = name;
  28062. /**
  28063. * An array of bindings.
  28064. *
  28065. * @type {Array<Binding>}
  28066. */
  28067. this.bindings = bindings;
  28068. /**
  28069. * The group index.
  28070. *
  28071. * @type {Number}
  28072. */
  28073. this.index = index;
  28074. /**
  28075. * An array of reference bindings.
  28076. *
  28077. * @type {Array<Binding>}
  28078. */
  28079. this.bindingsReference = bindingsReference;
  28080. /**
  28081. * The group's ID.
  28082. *
  28083. * @type {Number}
  28084. */
  28085. this.id = _id$6 ++;
  28086. }
  28087. }
  28088. /**
  28089. * This module represents the state of a node builder after it was
  28090. * used to build the nodes for a render object. The state holds the
  28091. * results of the build for further processing in the renderer.
  28092. *
  28093. * Render objects with identical cache keys share the same node builder state.
  28094. *
  28095. * @private
  28096. */
  28097. class NodeBuilderState {
  28098. /**
  28099. * Constructs a new node builder state.
  28100. *
  28101. * @param {String?} vertexShader - The native vertex shader code.
  28102. * @param {String?} fragmentShader - The native fragment shader code.
  28103. * @param {String?} computeShader - The native compute shader code.
  28104. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  28105. * @param {Array<BindGroup>} bindings - An array of bind groups.
  28106. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  28107. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  28108. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  28109. * @param {NodeMaterialObserver} observer - A node material observer.
  28110. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  28111. */
  28112. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  28113. /**
  28114. * The native vertex shader code.
  28115. *
  28116. * @type {String}
  28117. */
  28118. this.vertexShader = vertexShader;
  28119. /**
  28120. * The native fragment shader code.
  28121. *
  28122. * @type {String}
  28123. */
  28124. this.fragmentShader = fragmentShader;
  28125. /**
  28126. * The native compute shader code.
  28127. *
  28128. * @type {String}
  28129. */
  28130. this.computeShader = computeShader;
  28131. /**
  28132. * An array with transform attribute objects.
  28133. * Only relevant when using compute shaders with WebGL 2.
  28134. *
  28135. * @type {Array<Object>}
  28136. */
  28137. this.transforms = transforms;
  28138. /**
  28139. * An array of node attributes representing
  28140. * the attributes of the shaders.
  28141. *
  28142. * @type {Array<NodeAttribute>}
  28143. */
  28144. this.nodeAttributes = nodeAttributes;
  28145. /**
  28146. * An array of bind groups representing the uniform or storage
  28147. * buffers, texture or samplers of the shader.
  28148. *
  28149. * @type {Array<BindGroup>}
  28150. */
  28151. this.bindings = bindings;
  28152. /**
  28153. * An array of nodes that implement their `update()` method.
  28154. *
  28155. * @type {Array<Node>}
  28156. */
  28157. this.updateNodes = updateNodes;
  28158. /**
  28159. * An array of nodes that implement their `updateBefore()` method.
  28160. *
  28161. * @type {Array<Node>}
  28162. */
  28163. this.updateBeforeNodes = updateBeforeNodes;
  28164. /**
  28165. * An array of nodes that implement their `updateAfter()` method.
  28166. *
  28167. * @type {Array<Node>}
  28168. */
  28169. this.updateAfterNodes = updateAfterNodes;
  28170. /**
  28171. * A node material observer.
  28172. *
  28173. * @type {NodeMaterialObserver}
  28174. */
  28175. this.observer = observer;
  28176. /**
  28177. * How often this state is used by render objects.
  28178. *
  28179. * @type {Number}
  28180. */
  28181. this.usedTimes = 0;
  28182. }
  28183. /**
  28184. * This method is used to create a array of bind groups based
  28185. * on the existing bind groups of this state. Shared groups are
  28186. * not cloned.
  28187. *
  28188. * @return {Array<BindGroup>} A array of bind groups.
  28189. */
  28190. createBindings() {
  28191. const bindings = [];
  28192. for ( const instanceGroup of this.bindings ) {
  28193. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  28194. if ( shared !== true ) {
  28195. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28196. bindings.push( bindingsGroup );
  28197. for ( const instanceBinding of instanceGroup.bindings ) {
  28198. bindingsGroup.bindings.push( instanceBinding.clone() );
  28199. }
  28200. } else {
  28201. bindings.push( instanceGroup );
  28202. }
  28203. }
  28204. return bindings;
  28205. }
  28206. }
  28207. /**
  28208. * {@link NodeBuilder} is going to create instances of this class during the build process
  28209. * of nodes. They represent the final shader attributes that are going to be generated
  28210. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28211. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28212. */
  28213. class NodeAttribute {
  28214. /**
  28215. * Constructs a new node attribute.
  28216. *
  28217. * @param {String} name - The name of the attribute.
  28218. * @param {String} type - The type of the attribute.
  28219. * @param {Node?} node - An optional reference to the node.
  28220. */
  28221. constructor( name, type, node = null ) {
  28222. /**
  28223. * This flag can be used for type testing.
  28224. *
  28225. * @type {Boolean}
  28226. * @readonly
  28227. * @default true
  28228. */
  28229. this.isNodeAttribute = true;
  28230. /**
  28231. * The name of the attribute.
  28232. *
  28233. * @type {String}
  28234. */
  28235. this.name = name;
  28236. /**
  28237. * The type of the attribute.
  28238. *
  28239. * @type {String}
  28240. */
  28241. this.type = type;
  28242. /**
  28243. * An optional reference to the node.
  28244. *
  28245. * @type {Node?}
  28246. * @default null
  28247. */
  28248. this.node = node;
  28249. }
  28250. }
  28251. /**
  28252. * {@link NodeBuilder} is going to create instances of this class during the build process
  28253. * of nodes. They represent the final shader uniforms that are going to be generated
  28254. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28255. * for this purpose.
  28256. */
  28257. class NodeUniform {
  28258. /**
  28259. * Constructs a new node uniform.
  28260. *
  28261. * @param {String} name - The name of the uniform.
  28262. * @param {String} type - The type of the uniform.
  28263. * @param {UniformNode} node - An reference to the node.
  28264. */
  28265. constructor( name, type, node ) {
  28266. /**
  28267. * This flag can be used for type testing.
  28268. *
  28269. * @type {Boolean}
  28270. * @readonly
  28271. * @default true
  28272. */
  28273. this.isNodeUniform = true;
  28274. /**
  28275. * The name of the uniform.
  28276. *
  28277. * @type {String}
  28278. */
  28279. this.name = name;
  28280. /**
  28281. * The type of the uniform.
  28282. *
  28283. * @type {String}
  28284. */
  28285. this.type = type;
  28286. /**
  28287. * An reference to the node.
  28288. *
  28289. * @type {UniformNode}
  28290. */
  28291. this.node = node.getSelf();
  28292. }
  28293. /**
  28294. * The value of the uniform node.
  28295. *
  28296. * @type {Any}
  28297. */
  28298. get value() {
  28299. return this.node.value;
  28300. }
  28301. set value( val ) {
  28302. this.node.value = val;
  28303. }
  28304. /**
  28305. * The id of the uniform node.
  28306. *
  28307. * @type {Number}
  28308. */
  28309. get id() {
  28310. return this.node.id;
  28311. }
  28312. /**
  28313. * The uniform node's group.
  28314. *
  28315. * @type {UniformGroupNode}
  28316. */
  28317. get groupNode() {
  28318. return this.node.groupNode;
  28319. }
  28320. }
  28321. /**
  28322. * {@link NodeBuilder} is going to create instances of this class during the build process
  28323. * of nodes. They represent the final shader variables that are going to be generated
  28324. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28325. * this purpose.
  28326. */
  28327. class NodeVar {
  28328. /**
  28329. * Constructs a new node variable.
  28330. *
  28331. * @param {String} name - The name of the variable.
  28332. * @param {String} type - The type of the variable.
  28333. * @param {Boolean} [readOnly=false] - The read-only flag.
  28334. * @param {Number?} [count=null] - The size.
  28335. */
  28336. constructor( name, type, readOnly = false, count = null ) {
  28337. /**
  28338. * This flag can be used for type testing.
  28339. *
  28340. * @type {Boolean}
  28341. * @readonly
  28342. * @default true
  28343. */
  28344. this.isNodeVar = true;
  28345. /**
  28346. * The name of the variable.
  28347. *
  28348. * @type {String}
  28349. */
  28350. this.name = name;
  28351. /**
  28352. * The type of the variable.
  28353. *
  28354. * @type {String}
  28355. */
  28356. this.type = type;
  28357. /**
  28358. * The read-only flag.
  28359. *
  28360. * @type {Boolean}
  28361. */
  28362. this.readOnly = readOnly;
  28363. /**
  28364. * The size.
  28365. *
  28366. * @type {Number?}
  28367. */
  28368. this.count = count;
  28369. }
  28370. }
  28371. /**
  28372. * {@link NodeBuilder} is going to create instances of this class during the build process
  28373. * of nodes. They represent the final shader varyings that are going to be generated
  28374. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28375. * this purpose.
  28376. *
  28377. * @augments NodeVar
  28378. */
  28379. class NodeVarying extends NodeVar {
  28380. /**
  28381. * Constructs a new node varying.
  28382. *
  28383. * @param {String} name - The name of the varying.
  28384. * @param {String} type - The type of the varying.
  28385. */
  28386. constructor( name, type ) {
  28387. super( name, type );
  28388. /**
  28389. * Whether this varying requires interpolation or not. This property can be used
  28390. * to check if the varying can be optimized for a variable.
  28391. *
  28392. * @type {Boolean}
  28393. * @default false
  28394. */
  28395. this.needsInterpolation = false;
  28396. /**
  28397. * This flag can be used for type testing.
  28398. *
  28399. * @type {Boolean}
  28400. * @readonly
  28401. * @default true
  28402. */
  28403. this.isNodeVarying = true;
  28404. }
  28405. }
  28406. /**
  28407. * {@link NodeBuilder} is going to create instances of this class during the build process
  28408. * of nodes. They represent user-defined, native shader code portions that are going to be
  28409. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  28410. * for this purpose.
  28411. */
  28412. class NodeCode {
  28413. /**
  28414. * Constructs a new code node.
  28415. *
  28416. * @param {String} name - The name of the code.
  28417. * @param {String} type - The node type.
  28418. * @param {String} [code=''] - The native shader code.
  28419. */
  28420. constructor( name, type, code = '' ) {
  28421. /**
  28422. * The name of the code.
  28423. *
  28424. * @type {String}
  28425. */
  28426. this.name = name;
  28427. /**
  28428. * The node type.
  28429. *
  28430. * @type {String}
  28431. */
  28432. this.type = type;
  28433. /**
  28434. * The native shader code.
  28435. *
  28436. * @type {String}
  28437. * @default ''
  28438. */
  28439. this.code = code;
  28440. Object.defineProperty( this, 'isNodeCode', { value: true } );
  28441. }
  28442. }
  28443. let _id$5 = 0;
  28444. /**
  28445. * This utility class is used in {@link NodeBuilder} as an internal
  28446. * cache data structure for node data.
  28447. */
  28448. class NodeCache {
  28449. /**
  28450. * Constructs a new node cache.
  28451. *
  28452. * @param {NodeCache?} parent - A reference to a parent cache.
  28453. */
  28454. constructor( parent = null ) {
  28455. /**
  28456. * The id of the cache.
  28457. *
  28458. * @type {Number}
  28459. * @readonly
  28460. */
  28461. this.id = _id$5 ++;
  28462. /**
  28463. * A weak map for managing node data.
  28464. *
  28465. * @type {WeakMap<Node, Object>}
  28466. */
  28467. this.nodesData = new WeakMap();
  28468. /**
  28469. * Reference to a parent node cache.
  28470. *
  28471. * @type {NodeCache?}
  28472. * @default null
  28473. */
  28474. this.parent = parent;
  28475. }
  28476. /**
  28477. * Returns the data for the given node.
  28478. *
  28479. * @param {Node} node - The node.
  28480. * @return {Object?} The data for the node.
  28481. */
  28482. getData( node ) {
  28483. let data = this.nodesData.get( node );
  28484. if ( data === undefined && this.parent !== null ) {
  28485. data = this.parent.getData( node );
  28486. }
  28487. return data;
  28488. }
  28489. /**
  28490. * Sets the data for a given node.
  28491. *
  28492. * @param {Node} node - The node.
  28493. * @param {Object} data - The data that should be cached.
  28494. */
  28495. setData( node, data ) {
  28496. this.nodesData.set( node, data );
  28497. }
  28498. }
  28499. /**
  28500. * {@link NodeBuilder} is going to create instances of this class during the build process
  28501. * of nodes. They represent the final shader struct data that are going to be generated
  28502. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  28503. * for this purpose.
  28504. */
  28505. class StructTypeNode extends Node {
  28506. static get type() {
  28507. return 'StructTypeNode';
  28508. }
  28509. /**
  28510. * Constructs a new struct type node.
  28511. *
  28512. * @param {String} name - The name of the struct.
  28513. * @param {Array<String>} types - An array of types.
  28514. */
  28515. constructor( name, types ) {
  28516. super();
  28517. /**
  28518. * The name of the struct.
  28519. *
  28520. * @type {String}
  28521. */
  28522. this.name = name;
  28523. /**
  28524. * An array of types.
  28525. *
  28526. * @type {Array<String>}
  28527. */
  28528. this.types = types;
  28529. /**
  28530. * This flag can be used for type testing.
  28531. *
  28532. * @type {Boolean}
  28533. * @readonly
  28534. * @default true
  28535. */
  28536. this.isStructTypeNode = true;
  28537. }
  28538. /**
  28539. * Returns the member types.
  28540. *
  28541. * @return {Array<String>} The types.
  28542. */
  28543. getMemberTypes() {
  28544. return this.types;
  28545. }
  28546. }
  28547. /**
  28548. * Abstract base class for uniforms.
  28549. *
  28550. * @abstract
  28551. * @private
  28552. */
  28553. class Uniform {
  28554. /**
  28555. * Constructs a new uniform.
  28556. *
  28557. * @param {String} name - The uniform's name.
  28558. * @param {Any} value - The uniform's value.
  28559. */
  28560. constructor( name, value ) {
  28561. /**
  28562. * The uniform's name.
  28563. *
  28564. * @type {String}
  28565. */
  28566. this.name = name;
  28567. /**
  28568. * The uniform's value.
  28569. *
  28570. * @type {Any}
  28571. */
  28572. this.value = value;
  28573. /**
  28574. * Used to build the uniform buffer according to the STD140 layout.
  28575. * Derived uniforms will set this property to a data type specific
  28576. * value.
  28577. *
  28578. * @type {Number}
  28579. */
  28580. this.boundary = 0;
  28581. /**
  28582. * The item size. Derived uniforms will set this property to a data
  28583. * type specific value.
  28584. *
  28585. * @type {Number}
  28586. */
  28587. this.itemSize = 0;
  28588. /**
  28589. * This property is set by {@link UniformsGroup} and marks
  28590. * the start position in the uniform buffer.
  28591. *
  28592. * @type {Number}
  28593. */
  28594. this.offset = 0;
  28595. }
  28596. /**
  28597. * Sets the uniform's value.
  28598. *
  28599. * @param {Any} value - The value to set.
  28600. */
  28601. setValue( value ) {
  28602. this.value = value;
  28603. }
  28604. /**
  28605. * Returns the uniform's value.
  28606. *
  28607. * @return {Any} The value.
  28608. */
  28609. getValue() {
  28610. return this.value;
  28611. }
  28612. }
  28613. /**
  28614. * Represents a Number uniform.
  28615. *
  28616. * @private
  28617. * @augments Uniform
  28618. */
  28619. class NumberUniform extends Uniform {
  28620. /**
  28621. * Constructs a new Number uniform.
  28622. *
  28623. * @param {String} name - The uniform's name.
  28624. * @param {Number} value - The uniform's value.
  28625. */
  28626. constructor( name, value = 0 ) {
  28627. super( name, value );
  28628. /**
  28629. * This flag can be used for type testing.
  28630. *
  28631. * @type {Boolean}
  28632. * @readonly
  28633. * @default true
  28634. */
  28635. this.isNumberUniform = true;
  28636. this.boundary = 4;
  28637. this.itemSize = 1;
  28638. }
  28639. }
  28640. /**
  28641. * Represents a Vector2 uniform.
  28642. *
  28643. * @private
  28644. * @augments Uniform
  28645. */
  28646. class Vector2Uniform extends Uniform {
  28647. /**
  28648. * Constructs a new Number uniform.
  28649. *
  28650. * @param {String} name - The uniform's name.
  28651. * @param {Vector2} value - The uniform's value.
  28652. */
  28653. constructor( name, value = new Vector2() ) {
  28654. super( name, value );
  28655. /**
  28656. * This flag can be used for type testing.
  28657. *
  28658. * @type {Boolean}
  28659. * @readonly
  28660. * @default true
  28661. */
  28662. this.isVector2Uniform = true;
  28663. this.boundary = 8;
  28664. this.itemSize = 2;
  28665. }
  28666. }
  28667. /**
  28668. * Represents a Vector3 uniform.
  28669. *
  28670. * @private
  28671. * @augments Uniform
  28672. */
  28673. class Vector3Uniform extends Uniform {
  28674. /**
  28675. * Constructs a new Number uniform.
  28676. *
  28677. * @param {String} name - The uniform's name.
  28678. * @param {Vector3} value - The uniform's value.
  28679. */
  28680. constructor( name, value = new Vector3() ) {
  28681. super( name, value );
  28682. /**
  28683. * This flag can be used for type testing.
  28684. *
  28685. * @type {Boolean}
  28686. * @readonly
  28687. * @default true
  28688. */
  28689. this.isVector3Uniform = true;
  28690. this.boundary = 16;
  28691. this.itemSize = 3;
  28692. }
  28693. }
  28694. /**
  28695. * Represents a Vector4 uniform.
  28696. *
  28697. * @private
  28698. * @augments Uniform
  28699. */
  28700. class Vector4Uniform extends Uniform {
  28701. /**
  28702. * Constructs a new Number uniform.
  28703. *
  28704. * @param {String} name - The uniform's name.
  28705. * @param {Vector4} value - The uniform's value.
  28706. */
  28707. constructor( name, value = new Vector4() ) {
  28708. super( name, value );
  28709. /**
  28710. * This flag can be used for type testing.
  28711. *
  28712. * @type {Boolean}
  28713. * @readonly
  28714. * @default true
  28715. */
  28716. this.isVector4Uniform = true;
  28717. this.boundary = 16;
  28718. this.itemSize = 4;
  28719. }
  28720. }
  28721. /**
  28722. * Represents a Color uniform.
  28723. *
  28724. * @private
  28725. * @augments Uniform
  28726. */
  28727. class ColorUniform extends Uniform {
  28728. /**
  28729. * Constructs a new Number uniform.
  28730. *
  28731. * @param {String} name - The uniform's name.
  28732. * @param {Color} value - The uniform's value.
  28733. */
  28734. constructor( name, value = new Color() ) {
  28735. super( name, value );
  28736. /**
  28737. * This flag can be used for type testing.
  28738. *
  28739. * @type {Boolean}
  28740. * @readonly
  28741. * @default true
  28742. */
  28743. this.isColorUniform = true;
  28744. this.boundary = 16;
  28745. this.itemSize = 3;
  28746. }
  28747. }
  28748. /**
  28749. * Represents a Matrix2 uniform.
  28750. *
  28751. * @private
  28752. * @augments Uniform
  28753. */
  28754. class Matrix2Uniform extends Uniform {
  28755. /**
  28756. * Constructs a new Number uniform.
  28757. *
  28758. * @param {String} name - The uniform's name.
  28759. * @param {Matrix2} value - The uniform's value.
  28760. */
  28761. constructor( name, value = new Matrix2() ) {
  28762. super( name, value );
  28763. /**
  28764. * This flag can be used for type testing.
  28765. *
  28766. * @type {Boolean}
  28767. * @readonly
  28768. * @default true
  28769. */
  28770. this.isMatrix2Uniform = true;
  28771. this.boundary = 16;
  28772. this.itemSize = 4;
  28773. }
  28774. }
  28775. /**
  28776. * Represents a Matrix3 uniform.
  28777. *
  28778. * @private
  28779. * @augments Uniform
  28780. */
  28781. class Matrix3Uniform extends Uniform {
  28782. /**
  28783. * Constructs a new Number uniform.
  28784. *
  28785. * @param {String} name - The uniform's name.
  28786. * @param {Matrix3} value - The uniform's value.
  28787. */
  28788. constructor( name, value = new Matrix3() ) {
  28789. super( name, value );
  28790. /**
  28791. * This flag can be used for type testing.
  28792. *
  28793. * @type {Boolean}
  28794. * @readonly
  28795. * @default true
  28796. */
  28797. this.isMatrix3Uniform = true;
  28798. this.boundary = 48;
  28799. this.itemSize = 12;
  28800. }
  28801. }
  28802. /**
  28803. * Represents a Matrix4 uniform.
  28804. *
  28805. * @private
  28806. * @augments Uniform
  28807. */
  28808. class Matrix4Uniform extends Uniform {
  28809. /**
  28810. * Constructs a new Number uniform.
  28811. *
  28812. * @param {String} name - The uniform's name.
  28813. * @param {Matrix4} value - The uniform's value.
  28814. */
  28815. constructor( name, value = new Matrix4() ) {
  28816. super( name, value );
  28817. /**
  28818. * This flag can be used for type testing.
  28819. *
  28820. * @type {Boolean}
  28821. * @readonly
  28822. * @default true
  28823. */
  28824. this.isMatrix4Uniform = true;
  28825. this.boundary = 64;
  28826. this.itemSize = 16;
  28827. }
  28828. }
  28829. /**
  28830. * A special form of Number uniform binding type.
  28831. * It's value is managed by a node object.
  28832. *
  28833. * @private
  28834. * @augments NumberUniform
  28835. */
  28836. class NumberNodeUniform extends NumberUniform {
  28837. /**
  28838. * Constructs a new node-based Number uniform.
  28839. *
  28840. * @param {NodeUniform} nodeUniform - The node uniform.
  28841. */
  28842. constructor( nodeUniform ) {
  28843. super( nodeUniform.name, nodeUniform.value );
  28844. /**
  28845. * The node uniform.
  28846. *
  28847. * @type {NodeUniform}
  28848. */
  28849. this.nodeUniform = nodeUniform;
  28850. }
  28851. /**
  28852. * Overwritten to return the value of the node uniform.
  28853. *
  28854. * @return {Number} The value.
  28855. */
  28856. getValue() {
  28857. return this.nodeUniform.value;
  28858. }
  28859. /**
  28860. * Returns the node uniform data type.
  28861. *
  28862. * @return {String} The data type.
  28863. */
  28864. getType() {
  28865. return this.nodeUniform.type;
  28866. }
  28867. }
  28868. /**
  28869. * A special form of Vector2 uniform binding type.
  28870. * It's value is managed by a node object.
  28871. *
  28872. * @private
  28873. * @augments Vector2Uniform
  28874. */
  28875. class Vector2NodeUniform extends Vector2Uniform {
  28876. /**
  28877. * Constructs a new node-based Vector2 uniform.
  28878. *
  28879. * @param {NodeUniform} nodeUniform - The node uniform.
  28880. */
  28881. constructor( nodeUniform ) {
  28882. super( nodeUniform.name, nodeUniform.value );
  28883. /**
  28884. * The node uniform.
  28885. *
  28886. * @type {NodeUniform}
  28887. */
  28888. this.nodeUniform = nodeUniform;
  28889. }
  28890. /**
  28891. * Overwritten to return the value of the node uniform.
  28892. *
  28893. * @return {Vector2} The value.
  28894. */
  28895. getValue() {
  28896. return this.nodeUniform.value;
  28897. }
  28898. /**
  28899. * Returns the node uniform data type.
  28900. *
  28901. * @return {String} The data type.
  28902. */
  28903. getType() {
  28904. return this.nodeUniform.type;
  28905. }
  28906. }
  28907. /**
  28908. * A special form of Vector3 uniform binding type.
  28909. * It's value is managed by a node object.
  28910. *
  28911. * @private
  28912. * @augments Vector3Uniform
  28913. */
  28914. class Vector3NodeUniform extends Vector3Uniform {
  28915. /**
  28916. * Constructs a new node-based Vector3 uniform.
  28917. *
  28918. * @param {NodeUniform} nodeUniform - The node uniform.
  28919. */
  28920. constructor( nodeUniform ) {
  28921. super( nodeUniform.name, nodeUniform.value );
  28922. /**
  28923. * The node uniform.
  28924. *
  28925. * @type {NodeUniform}
  28926. */
  28927. this.nodeUniform = nodeUniform;
  28928. }
  28929. /**
  28930. * Overwritten to return the value of the node uniform.
  28931. *
  28932. * @return {Vector3} The value.
  28933. */
  28934. getValue() {
  28935. return this.nodeUniform.value;
  28936. }
  28937. /**
  28938. * Returns the node uniform data type.
  28939. *
  28940. * @return {String} The data type.
  28941. */
  28942. getType() {
  28943. return this.nodeUniform.type;
  28944. }
  28945. }
  28946. /**
  28947. * A special form of Vector4 uniform binding type.
  28948. * It's value is managed by a node object.
  28949. *
  28950. * @private
  28951. * @augments Vector4Uniform
  28952. */
  28953. class Vector4NodeUniform extends Vector4Uniform {
  28954. /**
  28955. * Constructs a new node-based Vector4 uniform.
  28956. *
  28957. * @param {NodeUniform} nodeUniform - The node uniform.
  28958. */
  28959. constructor( nodeUniform ) {
  28960. super( nodeUniform.name, nodeUniform.value );
  28961. /**
  28962. * The node uniform.
  28963. *
  28964. * @type {NodeUniform}
  28965. */
  28966. this.nodeUniform = nodeUniform;
  28967. }
  28968. /**
  28969. * Overwritten to return the value of the node uniform.
  28970. *
  28971. * @return {Vector4} The value.
  28972. */
  28973. getValue() {
  28974. return this.nodeUniform.value;
  28975. }
  28976. /**
  28977. * Returns the node uniform data type.
  28978. *
  28979. * @return {String} The data type.
  28980. */
  28981. getType() {
  28982. return this.nodeUniform.type;
  28983. }
  28984. }
  28985. /**
  28986. * A special form of Color uniform binding type.
  28987. * It's value is managed by a node object.
  28988. *
  28989. * @private
  28990. * @augments ColorUniform
  28991. */
  28992. class ColorNodeUniform extends ColorUniform {
  28993. /**
  28994. * Constructs a new node-based Color uniform.
  28995. *
  28996. * @param {NodeUniform} nodeUniform - The node uniform.
  28997. */
  28998. constructor( nodeUniform ) {
  28999. super( nodeUniform.name, nodeUniform.value );
  29000. /**
  29001. * The node uniform.
  29002. *
  29003. * @type {NodeUniform}
  29004. */
  29005. this.nodeUniform = nodeUniform;
  29006. }
  29007. /**
  29008. * Overwritten to return the value of the node uniform.
  29009. *
  29010. * @return {Color} The value.
  29011. */
  29012. getValue() {
  29013. return this.nodeUniform.value;
  29014. }
  29015. /**
  29016. * Returns the node uniform data type.
  29017. *
  29018. * @return {String} The data type.
  29019. */
  29020. getType() {
  29021. return this.nodeUniform.type;
  29022. }
  29023. }
  29024. /**
  29025. * A special form of Matrix2 uniform binding type.
  29026. * It's value is managed by a node object.
  29027. *
  29028. * @private
  29029. * @augments Matrix2Uniform
  29030. */
  29031. class Matrix2NodeUniform extends Matrix2Uniform {
  29032. /**
  29033. * Constructs a new node-based Matrix2 uniform.
  29034. *
  29035. * @param {NodeUniform} nodeUniform - The node uniform.
  29036. */
  29037. constructor( nodeUniform ) {
  29038. super( nodeUniform.name, nodeUniform.value );
  29039. /**
  29040. * The node uniform.
  29041. *
  29042. * @type {NodeUniform}
  29043. */
  29044. this.nodeUniform = nodeUniform;
  29045. }
  29046. /**
  29047. * Overwritten to return the value of the node uniform.
  29048. *
  29049. * @return {Matrix2} The value.
  29050. */
  29051. getValue() {
  29052. return this.nodeUniform.value;
  29053. }
  29054. /**
  29055. * Returns the node uniform data type.
  29056. *
  29057. * @return {String} The data type.
  29058. */
  29059. getType() {
  29060. return this.nodeUniform.type;
  29061. }
  29062. }
  29063. /**
  29064. * A special form of Matrix3 uniform binding type.
  29065. * It's value is managed by a node object.
  29066. *
  29067. * @private
  29068. * @augments Matrix3Uniform
  29069. */
  29070. class Matrix3NodeUniform extends Matrix3Uniform {
  29071. /**
  29072. * Constructs a new node-based Matrix3 uniform.
  29073. *
  29074. * @param {NodeUniform} nodeUniform - The node uniform.
  29075. */
  29076. constructor( nodeUniform ) {
  29077. super( nodeUniform.name, nodeUniform.value );
  29078. /**
  29079. * The node uniform.
  29080. *
  29081. * @type {NodeUniform}
  29082. */
  29083. this.nodeUniform = nodeUniform;
  29084. }
  29085. /**
  29086. * Overwritten to return the value of the node uniform.
  29087. *
  29088. * @return {Matrix3} The value.
  29089. */
  29090. getValue() {
  29091. return this.nodeUniform.value;
  29092. }
  29093. /**
  29094. * Returns the node uniform data type.
  29095. *
  29096. * @return {String} The data type.
  29097. */
  29098. getType() {
  29099. return this.nodeUniform.type;
  29100. }
  29101. }
  29102. /**
  29103. * A special form of Matrix4 uniform binding type.
  29104. * It's value is managed by a node object.
  29105. *
  29106. * @private
  29107. * @augments Matrix4Uniform
  29108. */
  29109. class Matrix4NodeUniform extends Matrix4Uniform {
  29110. /**
  29111. * Constructs a new node-based Matrix4 uniform.
  29112. *
  29113. * @param {NodeUniform} nodeUniform - The node uniform.
  29114. */
  29115. constructor( nodeUniform ) {
  29116. super( nodeUniform.name, nodeUniform.value );
  29117. /**
  29118. * The node uniform.
  29119. *
  29120. * @type {NodeUniform}
  29121. */
  29122. this.nodeUniform = nodeUniform;
  29123. }
  29124. /**
  29125. * Overwritten to return the value of the node uniform.
  29126. *
  29127. * @return {Matrix4} The value.
  29128. */
  29129. getValue() {
  29130. return this.nodeUniform.value;
  29131. }
  29132. /**
  29133. * Returns the node uniform data type.
  29134. *
  29135. * @return {String} The data type.
  29136. */
  29137. getType() {
  29138. return this.nodeUniform.type;
  29139. }
  29140. }
  29141. const LOD_MIN = 4;
  29142. // The standard deviations (radians) associated with the extra mips. These are
  29143. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29144. // geometric shadowing function. These sigma values squared must match the
  29145. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29146. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29147. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29148. // samples and exit early, but not recompile the shader.
  29149. const MAX_SAMPLES = 20;
  29150. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  29151. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  29152. const _clearColor = /*@__PURE__*/ new Color();
  29153. let _oldTarget = null;
  29154. let _oldActiveCubeFace = 0;
  29155. let _oldActiveMipmapLevel = 0;
  29156. // Golden Ratio
  29157. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29158. const INV_PHI = 1 / PHI;
  29159. // Vertices of a dodecahedron (except the opposites, which represent the
  29160. // same axis), used as axis directions evenly spread on a sphere.
  29161. const _axisDirections = [
  29162. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  29163. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29164. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29165. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29166. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29167. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29168. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  29169. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  29170. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  29171. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  29172. ];
  29173. // maps blur materials to their uniforms dictionary
  29174. const _uniformsMap = new WeakMap();
  29175. // WebGPU Face indices
  29176. const _faceLib = [
  29177. 3, 1, 5,
  29178. 0, 4, 2
  29179. ];
  29180. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  29181. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  29182. /**
  29183. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29184. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29185. * blur to be quickly accessed based on material roughness. It is packed into a
  29186. * special CubeUV format that allows us to perform custom interpolation so that
  29187. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29188. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29189. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29190. * higher roughness levels. In this way we maintain resolution to smoothly
  29191. * interpolate diffuse lighting while limiting sampling computation.
  29192. *
  29193. * Paper: Fast, Accurate Image-Based Lighting
  29194. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  29195. */
  29196. class PMREMGenerator {
  29197. constructor( renderer ) {
  29198. this._renderer = renderer;
  29199. this._pingPongRenderTarget = null;
  29200. this._lodMax = 0;
  29201. this._cubeSize = 0;
  29202. this._lodPlanes = [];
  29203. this._sizeLods = [];
  29204. this._sigmas = [];
  29205. this._lodMeshes = [];
  29206. this._blurMaterial = null;
  29207. this._cubemapMaterial = null;
  29208. this._equirectMaterial = null;
  29209. this._backgroundBox = null;
  29210. }
  29211. get _hasInitialized() {
  29212. return this._renderer.hasInitialized();
  29213. }
  29214. /**
  29215. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29216. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29217. * in radians to be applied to the scene before PMREM generation. Optional near
  29218. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29219. * is placed at the origin).
  29220. *
  29221. * @param {Scene} scene - The scene to be captured.
  29222. * @param {Number} [sigma=0] - The blur radius in radians.
  29223. * @param {Number} [near=0.1] - The near plane distance.
  29224. * @param {Number} [far=100] - The far plane distance.
  29225. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29226. * @return {RenderTarget} The resulting PMREM.
  29227. * @see fromSceneAsync
  29228. */
  29229. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29230. this._setSize( 256 );
  29231. if ( this._hasInitialized === false ) {
  29232. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29233. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29234. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  29235. return cubeUVRenderTarget;
  29236. }
  29237. _oldTarget = this._renderer.getRenderTarget();
  29238. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29239. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29240. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29241. cubeUVRenderTarget.depthBuffer = true;
  29242. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29243. if ( sigma > 0 ) {
  29244. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29245. }
  29246. this._applyPMREM( cubeUVRenderTarget );
  29247. this._cleanup( cubeUVRenderTarget );
  29248. return cubeUVRenderTarget;
  29249. }
  29250. /**
  29251. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29252. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29253. * in radians to be applied to the scene before PMREM generation. Optional near
  29254. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29255. * is placed at the origin).
  29256. *
  29257. * @param {Scene} scene - The scene to be captured.
  29258. * @param {Number} [sigma=0] - The blur radius in radians.
  29259. * @param {Number} [near=0.1] - The near plane distance.
  29260. * @param {Number} [far=100] - The far plane distance.
  29261. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29262. * @return {Promise<RenderTarget>} The resulting PMREM.
  29263. * @see fromScene
  29264. */
  29265. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29266. if ( this._hasInitialized === false ) await this._renderer.init();
  29267. return this.fromScene( scene, sigma, near, far, renderTarget );
  29268. }
  29269. /**
  29270. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29271. * or HDR. The ideal input image size is 1k (1024 x 512),
  29272. * as this matches best with the 256 x 256 cubemap output.
  29273. *
  29274. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29275. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29276. * @return {RenderTarget} The resulting PMREM.
  29277. * @see fromEquirectangularAsync
  29278. */
  29279. fromEquirectangular( equirectangular, renderTarget = null ) {
  29280. if ( this._hasInitialized === false ) {
  29281. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29282. this._setSizeFromTexture( equirectangular );
  29283. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29284. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29285. return cubeUVRenderTarget;
  29286. }
  29287. return this._fromTexture( equirectangular, renderTarget );
  29288. }
  29289. /**
  29290. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29291. * or HDR. The ideal input image size is 1k (1024 x 512),
  29292. * as this matches best with the 256 x 256 cubemap output.
  29293. *
  29294. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29295. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29296. * @return {Promise<RenderTarget>} The resulting PMREM.
  29297. * @see fromEquirectangular
  29298. */
  29299. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29300. if ( this._hasInitialized === false ) await this._renderer.init();
  29301. return this._fromTexture( equirectangular, renderTarget );
  29302. }
  29303. /**
  29304. * Generates a PMREM from an cubemap texture, which can be either LDR
  29305. * or HDR. The ideal input cube size is 256 x 256,
  29306. * as this matches best with the 256 x 256 cubemap output.
  29307. *
  29308. * @param {Texture} cubemap - The cubemap texture to be converted.
  29309. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29310. * @return {RenderTarget} The resulting PMREM.
  29311. * @see fromCubemapAsync
  29312. */
  29313. fromCubemap( cubemap, renderTarget = null ) {
  29314. if ( this._hasInitialized === false ) {
  29315. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29316. this._setSizeFromTexture( cubemap );
  29317. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29318. this.fromCubemapAsync( cubemap, renderTarget );
  29319. return cubeUVRenderTarget;
  29320. }
  29321. return this._fromTexture( cubemap, renderTarget );
  29322. }
  29323. /**
  29324. * Generates a PMREM from an cubemap texture, which can be either LDR
  29325. * or HDR. The ideal input cube size is 256 x 256,
  29326. * with the 256 x 256 cubemap output.
  29327. *
  29328. * @param {Texture} cubemap - The cubemap texture to be converted.
  29329. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29330. * @return {Promise<RenderTarget>} The resulting PMREM.
  29331. * @see fromCubemap
  29332. */
  29333. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29334. if ( this._hasInitialized === false ) await this._renderer.init();
  29335. return this._fromTexture( cubemap, renderTarget );
  29336. }
  29337. /**
  29338. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29339. * your texture's network fetch for increased concurrency.
  29340. *
  29341. * @returns {Promise}
  29342. */
  29343. async compileCubemapShader() {
  29344. if ( this._cubemapMaterial === null ) {
  29345. this._cubemapMaterial = _getCubemapMaterial();
  29346. await this._compileMaterial( this._cubemapMaterial );
  29347. }
  29348. }
  29349. /**
  29350. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29351. * your texture's network fetch for increased concurrency.
  29352. *
  29353. * @returns {Promise}
  29354. */
  29355. async compileEquirectangularShader() {
  29356. if ( this._equirectMaterial === null ) {
  29357. this._equirectMaterial = _getEquirectMaterial();
  29358. await this._compileMaterial( this._equirectMaterial );
  29359. }
  29360. }
  29361. /**
  29362. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29363. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29364. * one of them will cause any others to also become unusable.
  29365. */
  29366. dispose() {
  29367. this._dispose();
  29368. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29369. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29370. if ( this._backgroundBox !== null ) {
  29371. this._backgroundBox.geometry.dispose();
  29372. this._backgroundBox.material.dispose();
  29373. }
  29374. }
  29375. // private interface
  29376. _setSizeFromTexture( texture ) {
  29377. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29378. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29379. } else { // Equirectangular
  29380. this._setSize( texture.image.width / 4 );
  29381. }
  29382. }
  29383. _setSize( cubeSize ) {
  29384. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29385. this._cubeSize = Math.pow( 2, this._lodMax );
  29386. }
  29387. _dispose() {
  29388. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29389. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29390. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29391. this._lodPlanes[ i ].dispose();
  29392. }
  29393. }
  29394. _cleanup( outputTarget ) {
  29395. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29396. outputTarget.scissorTest = false;
  29397. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29398. }
  29399. _fromTexture( texture, renderTarget ) {
  29400. this._setSizeFromTexture( texture );
  29401. _oldTarget = this._renderer.getRenderTarget();
  29402. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29403. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29404. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29405. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29406. this._applyPMREM( cubeUVRenderTarget );
  29407. this._cleanup( cubeUVRenderTarget );
  29408. return cubeUVRenderTarget;
  29409. }
  29410. _allocateTargets() {
  29411. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29412. const height = 4 * this._cubeSize;
  29413. const params = {
  29414. magFilter: LinearFilter,
  29415. minFilter: LinearFilter,
  29416. generateMipmaps: false,
  29417. type: HalfFloatType,
  29418. format: RGBAFormat,
  29419. colorSpace: LinearSRGBColorSpace,
  29420. //depthBuffer: false
  29421. };
  29422. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29423. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29424. if ( this._pingPongRenderTarget !== null ) {
  29425. this._dispose();
  29426. }
  29427. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29428. const { _lodMax } = this;
  29429. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29430. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29431. }
  29432. return cubeUVRenderTarget;
  29433. }
  29434. async _compileMaterial( material ) {
  29435. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  29436. await this._renderer.compile( tmpMesh, _flatCamera );
  29437. }
  29438. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29439. const cubeCamera = _cubeCamera;
  29440. cubeCamera.near = near;
  29441. cubeCamera.far = far;
  29442. // px, py, pz, nx, ny, nz
  29443. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  29444. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  29445. const renderer = this._renderer;
  29446. const originalAutoClear = renderer.autoClear;
  29447. renderer.getClearColor( _clearColor );
  29448. renderer.autoClear = false;
  29449. let backgroundBox = this._backgroundBox;
  29450. if ( backgroundBox === null ) {
  29451. const backgroundMaterial = new MeshBasicMaterial( {
  29452. name: 'PMREM.Background',
  29453. side: BackSide,
  29454. depthWrite: false,
  29455. depthTest: false
  29456. } );
  29457. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  29458. }
  29459. let useSolidColor = false;
  29460. const background = scene.background;
  29461. if ( background ) {
  29462. if ( background.isColor ) {
  29463. backgroundBox.material.color.copy( background );
  29464. scene.background = null;
  29465. useSolidColor = true;
  29466. }
  29467. } else {
  29468. backgroundBox.material.color.copy( _clearColor );
  29469. useSolidColor = true;
  29470. }
  29471. renderer.setRenderTarget( cubeUVRenderTarget );
  29472. renderer.clear();
  29473. if ( useSolidColor ) {
  29474. renderer.render( backgroundBox, cubeCamera );
  29475. }
  29476. for ( let i = 0; i < 6; i ++ ) {
  29477. const col = i % 3;
  29478. if ( col === 0 ) {
  29479. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29480. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29481. } else if ( col === 1 ) {
  29482. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29483. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29484. } else {
  29485. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29486. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29487. }
  29488. const size = this._cubeSize;
  29489. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  29490. renderer.render( scene, cubeCamera );
  29491. }
  29492. renderer.autoClear = originalAutoClear;
  29493. scene.background = background;
  29494. }
  29495. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29496. const renderer = this._renderer;
  29497. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  29498. if ( isCubeTexture ) {
  29499. if ( this._cubemapMaterial === null ) {
  29500. this._cubemapMaterial = _getCubemapMaterial( texture );
  29501. }
  29502. } else {
  29503. if ( this._equirectMaterial === null ) {
  29504. this._equirectMaterial = _getEquirectMaterial( texture );
  29505. }
  29506. }
  29507. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  29508. material.fragmentNode.value = texture;
  29509. const mesh = this._lodMeshes[ 0 ];
  29510. mesh.material = material;
  29511. const size = this._cubeSize;
  29512. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  29513. renderer.setRenderTarget( cubeUVRenderTarget );
  29514. renderer.render( mesh, _flatCamera );
  29515. }
  29516. _applyPMREM( cubeUVRenderTarget ) {
  29517. const renderer = this._renderer;
  29518. const autoClear = renderer.autoClear;
  29519. renderer.autoClear = false;
  29520. const n = this._lodPlanes.length;
  29521. for ( let i = 1; i < n; i ++ ) {
  29522. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  29523. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  29524. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29525. }
  29526. renderer.autoClear = autoClear;
  29527. }
  29528. /**
  29529. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29530. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29531. * the blur latitudinally (around the poles), and then longitudinally (towards
  29532. * the poles) to approximate the orthogonally-separable blur. It is least
  29533. * accurate at the poles, but still does a decent job.
  29534. *
  29535. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  29536. * @param {Number} lodIn - The input level-of-detail.
  29537. * @param {Number} lodOut - The output level-of-detail.
  29538. * @param {Number} sigma - The blur radius in radians.
  29539. * @param {Vector3} [poleAxis] - The pole axis.
  29540. */
  29541. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29542. const pingPongRenderTarget = this._pingPongRenderTarget;
  29543. this._halfBlur(
  29544. cubeUVRenderTarget,
  29545. pingPongRenderTarget,
  29546. lodIn,
  29547. lodOut,
  29548. sigma,
  29549. 'latitudinal',
  29550. poleAxis );
  29551. this._halfBlur(
  29552. pingPongRenderTarget,
  29553. cubeUVRenderTarget,
  29554. lodOut,
  29555. lodOut,
  29556. sigma,
  29557. 'longitudinal',
  29558. poleAxis );
  29559. }
  29560. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29561. const renderer = this._renderer;
  29562. const blurMaterial = this._blurMaterial;
  29563. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29564. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  29565. }
  29566. // Number of standard deviations at which to cut off the discrete approximation.
  29567. const STANDARD_DEVIATIONS = 3;
  29568. const blurMesh = this._lodMeshes[ lodOut ];
  29569. blurMesh.material = blurMaterial;
  29570. const blurUniforms = _uniformsMap.get( blurMaterial );
  29571. const pixels = this._sizeLods[ lodIn ] - 1;
  29572. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29573. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29574. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29575. if ( samples > MAX_SAMPLES ) {
  29576. console.warn( `sigmaRadians, ${
  29577. sigmaRadians}, is too large and will clip, as it requested ${
  29578. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29579. }
  29580. const weights = [];
  29581. let sum = 0;
  29582. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29583. const x = i / sigmaPixels;
  29584. const weight = Math.exp( - x * x / 2 );
  29585. weights.push( weight );
  29586. if ( i === 0 ) {
  29587. sum += weight;
  29588. } else if ( i < samples ) {
  29589. sum += 2 * weight;
  29590. }
  29591. }
  29592. for ( let i = 0; i < weights.length; i ++ ) {
  29593. weights[ i ] = weights[ i ] / sum;
  29594. }
  29595. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  29596. blurUniforms.envMap.value = targetIn.texture;
  29597. blurUniforms.samples.value = samples;
  29598. blurUniforms.weights.array = weights;
  29599. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29600. if ( poleAxis ) {
  29601. blurUniforms.poleAxis.value = poleAxis;
  29602. }
  29603. const { _lodMax } = this;
  29604. blurUniforms.dTheta.value = radiansPerPixel;
  29605. blurUniforms.mipInt.value = _lodMax - lodIn;
  29606. const outputSize = this._sizeLods[ lodOut ];
  29607. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29608. const y = 4 * ( this._cubeSize - outputSize );
  29609. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29610. renderer.setRenderTarget( targetOut );
  29611. renderer.render( blurMesh, _flatCamera );
  29612. }
  29613. }
  29614. function _createPlanes( lodMax ) {
  29615. const lodPlanes = [];
  29616. const sizeLods = [];
  29617. const sigmas = [];
  29618. const lodMeshes = [];
  29619. let lod = lodMax;
  29620. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29621. for ( let i = 0; i < totalLods; i ++ ) {
  29622. const sizeLod = Math.pow( 2, lod );
  29623. sizeLods.push( sizeLod );
  29624. let sigma = 1.0 / sizeLod;
  29625. if ( i > lodMax - LOD_MIN ) {
  29626. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29627. } else if ( i === 0 ) {
  29628. sigma = 0;
  29629. }
  29630. sigmas.push( sigma );
  29631. const texelSize = 1.0 / ( sizeLod - 2 );
  29632. const min = - texelSize;
  29633. const max = 1 + texelSize;
  29634. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29635. const cubeFaces = 6;
  29636. const vertices = 6;
  29637. const positionSize = 3;
  29638. const uvSize = 2;
  29639. const faceIndexSize = 1;
  29640. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29641. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29642. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29643. for ( let face = 0; face < cubeFaces; face ++ ) {
  29644. const x = ( face % 3 ) * 2 / 3 - 1;
  29645. const y = face > 2 ? 0 : -1;
  29646. const coordinates = [
  29647. x, y, 0,
  29648. x + 2 / 3, y, 0,
  29649. x + 2 / 3, y + 1, 0,
  29650. x, y, 0,
  29651. x + 2 / 3, y + 1, 0,
  29652. x, y + 1, 0
  29653. ];
  29654. const faceIdx = _faceLib[ face ];
  29655. position.set( coordinates, positionSize * vertices * faceIdx );
  29656. uv.set( uv1, uvSize * vertices * faceIdx );
  29657. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29658. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29659. }
  29660. const planes = new BufferGeometry();
  29661. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29662. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29663. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29664. lodPlanes.push( planes );
  29665. lodMeshes.push( new Mesh( planes, null ) );
  29666. if ( lod > LOD_MIN ) {
  29667. lod --;
  29668. }
  29669. }
  29670. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29671. }
  29672. function _createRenderTarget( width, height, params ) {
  29673. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29674. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29675. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29676. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29677. cubeUVRenderTarget.scissorTest = true;
  29678. return cubeUVRenderTarget;
  29679. }
  29680. function _setViewport( target, x, y, width, height ) {
  29681. target.viewport.set( x, y, width, height );
  29682. target.scissor.set( x, y, width, height );
  29683. }
  29684. function _getMaterial( type ) {
  29685. const material = new NodeMaterial();
  29686. material.depthTest = false;
  29687. material.depthWrite = false;
  29688. material.blending = NoBlending;
  29689. material.name = `PMREM_${ type }`;
  29690. return material;
  29691. }
  29692. function _getBlurShader( lodMax, width, height ) {
  29693. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29694. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29695. const dTheta = uniform( 0 );
  29696. const n = float( MAX_SAMPLES );
  29697. const latitudinal = uniform( 0 ); // false, bool
  29698. const samples = uniform( 1 ); // int
  29699. const envMap = texture( null );
  29700. const mipInt = uniform( 0 ); // int
  29701. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29702. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29703. const CUBEUV_MAX_MIP = float( lodMax );
  29704. const materialUniforms = {
  29705. n,
  29706. latitudinal,
  29707. weights,
  29708. poleAxis,
  29709. outputDirection: _outputDirection,
  29710. dTheta,
  29711. samples,
  29712. envMap,
  29713. mipInt,
  29714. CUBEUV_TEXEL_WIDTH,
  29715. CUBEUV_TEXEL_HEIGHT,
  29716. CUBEUV_MAX_MIP
  29717. };
  29718. const material = _getMaterial( 'blur' );
  29719. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29720. _uniformsMap.set( material, materialUniforms );
  29721. return material;
  29722. }
  29723. function _getCubemapMaterial( envTexture ) {
  29724. const material = _getMaterial( 'cubemap' );
  29725. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  29726. return material;
  29727. }
  29728. function _getEquirectMaterial( envTexture ) {
  29729. const material = _getMaterial( 'equirect' );
  29730. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  29731. return material;
  29732. }
  29733. const rendererCache = new WeakMap();
  29734. const typeFromArray = new Map( [
  29735. [ Int8Array, 'int' ],
  29736. [ Int16Array, 'int' ],
  29737. [ Int32Array, 'int' ],
  29738. [ Uint8Array, 'uint' ],
  29739. [ Uint16Array, 'uint' ],
  29740. [ Uint32Array, 'uint' ],
  29741. [ Float32Array, 'float' ]
  29742. ] );
  29743. const toFloat = ( value ) => {
  29744. if ( /e/g.test( value ) ) {
  29745. return String( value ).replace( /\+/g, '' );
  29746. } else {
  29747. value = Number( value );
  29748. return value + ( value % 1 ? '' : '.0' );
  29749. }
  29750. };
  29751. /**
  29752. * Base class for builders which generate a shader program based
  29753. * on a 3D object and its node material definition.
  29754. */
  29755. class NodeBuilder {
  29756. /**
  29757. * Constructs a new node builder.
  29758. *
  29759. * @param {Object3D} object - The 3D object.
  29760. * @param {Renderer} renderer - The current renderer.
  29761. * @param {NodeParser} parser - A reference to a node parser.
  29762. */
  29763. constructor( object, renderer, parser ) {
  29764. /**
  29765. * The 3D object.
  29766. *
  29767. * @type {Object3D}
  29768. */
  29769. this.object = object;
  29770. /**
  29771. * The material of the 3D object.
  29772. *
  29773. * @type {Material?}
  29774. */
  29775. this.material = ( object && object.material ) || null;
  29776. /**
  29777. * The geometry of the 3D object.
  29778. *
  29779. * @type {BufferGeometry?}
  29780. */
  29781. this.geometry = ( object && object.geometry ) || null;
  29782. /**
  29783. * The current renderer.
  29784. *
  29785. * @type {Renderer}
  29786. */
  29787. this.renderer = renderer;
  29788. /**
  29789. * A reference to a node parser.
  29790. *
  29791. * @type {NodeParser}
  29792. */
  29793. this.parser = parser;
  29794. /**
  29795. * The scene the 3D object belongs to.
  29796. *
  29797. * @type {Scene?}
  29798. * @default null
  29799. */
  29800. this.scene = null;
  29801. /**
  29802. * The camera the 3D object is rendered with.
  29803. *
  29804. * @type {Camera?}
  29805. * @default null
  29806. */
  29807. this.camera = null;
  29808. /**
  29809. * A list of all nodes the builder is processing
  29810. * for this 3D object.
  29811. *
  29812. * @type {Array<Node>}
  29813. */
  29814. this.nodes = [];
  29815. /**
  29816. * A list of all sequential nodes.
  29817. *
  29818. * @type {Array<Node>}
  29819. */
  29820. this.sequentialNodes = [];
  29821. /**
  29822. * A list of all nodes which {@link Node#update} method should be executed.
  29823. *
  29824. * @type {Array<Node>}
  29825. */
  29826. this.updateNodes = [];
  29827. /**
  29828. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29829. *
  29830. * @type {Array<Node>}
  29831. */
  29832. this.updateBeforeNodes = [];
  29833. /**
  29834. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29835. *
  29836. * @type {Array<Node>}
  29837. */
  29838. this.updateAfterNodes = [];
  29839. /**
  29840. * A dictionary that assigns each node to a unique hash.
  29841. *
  29842. * @type {Object<Number,Node>}
  29843. */
  29844. this.hashNodes = {};
  29845. /**
  29846. * A reference to a node material observer.
  29847. *
  29848. * @type {NodeMaterialObserver?}
  29849. * @default null
  29850. */
  29851. this.observer = null;
  29852. /**
  29853. * A reference to the current lights node.
  29854. *
  29855. * @type {LightsNode?}
  29856. * @default null
  29857. */
  29858. this.lightsNode = null;
  29859. /**
  29860. * A reference to the current environment node.
  29861. *
  29862. * @type {Node?}
  29863. * @default null
  29864. */
  29865. this.environmentNode = null;
  29866. /**
  29867. * A reference to the current fog node.
  29868. *
  29869. * @type {FogNode?}
  29870. * @default null
  29871. */
  29872. this.fogNode = null;
  29873. /**
  29874. * The current clipping context.
  29875. *
  29876. * @type {ClippingContext?}
  29877. */
  29878. this.clippingContext = null;
  29879. /**
  29880. * The generated vertex shader.
  29881. *
  29882. * @type {String?}
  29883. */
  29884. this.vertexShader = null;
  29885. /**
  29886. * The generated fragment shader.
  29887. *
  29888. * @type {String?}
  29889. */
  29890. this.fragmentShader = null;
  29891. /**
  29892. * The generated compute shader.
  29893. *
  29894. * @type {String?}
  29895. */
  29896. this.computeShader = null;
  29897. /**
  29898. * Nodes used in the primary flow of code generation.
  29899. *
  29900. * @type {Object<String,Array<Node>>}
  29901. */
  29902. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29903. /**
  29904. * Nodes code from `.flowNodes`.
  29905. *
  29906. * @type {Object<String,String>}
  29907. */
  29908. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29909. /**
  29910. * This dictionary holds the node uniforms of the builder.
  29911. * The uniforms are maintained in an array for each shader stage.
  29912. *
  29913. * @type {Object}
  29914. */
  29915. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29916. /**
  29917. * This dictionary holds the output structs of the builder.
  29918. * The structs are maintained in an array for each shader stage.
  29919. *
  29920. * @type {Object}
  29921. */
  29922. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29923. /**
  29924. * This dictionary holds the bindings for each shader stage.
  29925. *
  29926. * @type {Object}
  29927. */
  29928. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29929. /**
  29930. * This dictionary maintains the binding indices per bind group.
  29931. *
  29932. * @type {Object}
  29933. */
  29934. this.bindingsIndexes = {};
  29935. /**
  29936. * Reference to the array of bind groups.
  29937. *
  29938. * @type {Array<BindGroup>?}
  29939. */
  29940. this.bindGroups = null;
  29941. /**
  29942. * This array holds the node attributes of this builder
  29943. * created via {@link AttributeNode}.
  29944. *
  29945. * @type {Array<NodeAttribute>}
  29946. */
  29947. this.attributes = [];
  29948. /**
  29949. * This array holds the node attributes of this builder
  29950. * created via {@link BufferAttributeNode}.
  29951. *
  29952. * @type {Array<NodeAttribute>}
  29953. */
  29954. this.bufferAttributes = [];
  29955. /**
  29956. * This array holds the node varyings of this builder.
  29957. *
  29958. * @type {Array<NodeVarying>}
  29959. */
  29960. this.varyings = [];
  29961. /**
  29962. * This dictionary holds the (native) node codes of this builder.
  29963. * The codes are maintained in an array for each shader stage.
  29964. *
  29965. * @type {Object<String,Array<NodeCode>>}
  29966. */
  29967. this.codes = {};
  29968. /**
  29969. * This dictionary holds the node variables of this builder.
  29970. * The variables are maintained in an array for each shader stage.
  29971. *
  29972. * @type {Object<String,Array<NodeVar>>}
  29973. */
  29974. this.vars = {};
  29975. /**
  29976. * Current code flow.
  29977. * All code generated in this stack will be stored in `.flow`.
  29978. *
  29979. * @type {{code: String}}
  29980. */
  29981. this.flow = { code: '' };
  29982. /**
  29983. * A chain of nodes.
  29984. * Used to check recursive calls in node-graph.
  29985. *
  29986. * @type {Array<Node>}
  29987. */
  29988. this.chaining = [];
  29989. /**
  29990. * The current stack.
  29991. * This reflects the current process in the code block hierarchy,
  29992. * it is useful to know if the current process is inside a conditional for example.
  29993. *
  29994. * @type {StackNode}
  29995. */
  29996. this.stack = stack();
  29997. /**
  29998. * List of stack nodes.
  29999. * The current stack hierarchy is stored in an array.
  30000. *
  30001. * @type {Array<StackNode>}
  30002. */
  30003. this.stacks = [];
  30004. /**
  30005. * A tab value. Used for shader string generation.
  30006. *
  30007. * @type {String}
  30008. * @default '\t'
  30009. */
  30010. this.tab = '\t';
  30011. /**
  30012. * Reference to the current function node.
  30013. *
  30014. * @type {FunctionNode?}
  30015. * @default null
  30016. */
  30017. this.currentFunctionNode = null;
  30018. /**
  30019. * The builder's context.
  30020. *
  30021. * @type {Object}
  30022. */
  30023. this.context = {
  30024. material: this.material
  30025. };
  30026. /**
  30027. * The builder's cache.
  30028. *
  30029. * @type {NodeCache}
  30030. */
  30031. this.cache = new NodeCache();
  30032. /**
  30033. * Since the {@link NodeBuilder#cache} might be temporarily
  30034. * overwritten by other caches, this member retains the reference
  30035. * to the builder's own cache.
  30036. *
  30037. * @type {NodeCache}
  30038. * @default this.cache
  30039. */
  30040. this.globalCache = this.cache;
  30041. this.flowsData = new WeakMap();
  30042. /**
  30043. * The current shader stage.
  30044. *
  30045. * @type {('vertex'|'fragment'|'compute'|'any')?}
  30046. */
  30047. this.shaderStage = null;
  30048. /**
  30049. * The current build stage.
  30050. *
  30051. * @type {('setup'|'analyze'|'generate')?}
  30052. */
  30053. this.buildStage = null;
  30054. /**
  30055. * Whether comparison in shader code are generated with methods or not.
  30056. *
  30057. * @type {Boolean}
  30058. * @default false
  30059. */
  30060. this.useComparisonMethod = false;
  30061. }
  30062. /**
  30063. * Returns the bind groups of the current renderer.
  30064. *
  30065. * @return {ChainMap} The cache.
  30066. */
  30067. getBindGroupsCache() {
  30068. let bindGroupsCache = rendererCache.get( this.renderer );
  30069. if ( bindGroupsCache === undefined ) {
  30070. bindGroupsCache = new ChainMap();
  30071. rendererCache.set( this.renderer, bindGroupsCache );
  30072. }
  30073. return bindGroupsCache;
  30074. }
  30075. /**
  30076. * Factory method for creating an instance of {@link RenderTarget} with the given
  30077. * dimensions and options.
  30078. *
  30079. * @param {Number} width - The width of the render target.
  30080. * @param {Number} height - The height of the render target.
  30081. * @param {Object} options - The options of the render target.
  30082. * @return {RenderTarget} The render target.
  30083. */
  30084. createRenderTarget( width, height, options ) {
  30085. return new RenderTarget( width, height, options );
  30086. }
  30087. /**
  30088. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  30089. * dimensions and options.
  30090. *
  30091. * @param {Number} size - The size of the cube render target.
  30092. * @param {Object} options - The options of the cube render target.
  30093. * @return {CubeRenderTarget} The cube render target.
  30094. */
  30095. createCubeRenderTarget( size, options ) {
  30096. return new CubeRenderTarget( size, options );
  30097. }
  30098. /**
  30099. * Factory method for creating an instance of {@link PMREMGenerator}.
  30100. *
  30101. * @return {PMREMGenerator} The PMREM generator.
  30102. */
  30103. createPMREMGenerator() {
  30104. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30105. return new PMREMGenerator( this.renderer );
  30106. }
  30107. /**
  30108. * Whether the given node is included in the internal array of nodes or not.
  30109. *
  30110. * @param {Node} node - The node to test.
  30111. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  30112. */
  30113. includes( node ) {
  30114. return this.nodes.includes( node );
  30115. }
  30116. /**
  30117. * Returns the output struct name which is required by
  30118. * {@link module:OutputStructNode}.
  30119. *
  30120. * @abstract
  30121. * @return {String} The name of the output struct.
  30122. */
  30123. getOutputStructName() {}
  30124. /**
  30125. * Returns a bind group for the given group name and binding.
  30126. *
  30127. * @private
  30128. * @param {String} groupName - The group name.
  30129. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  30130. * @return {BindGroup} The bind group
  30131. */
  30132. _getBindGroup( groupName, bindings ) {
  30133. const bindGroupsCache = this.getBindGroupsCache();
  30134. //
  30135. const bindingsArray = [];
  30136. let sharedGroup = true;
  30137. for ( const binding of bindings ) {
  30138. bindingsArray.push( binding );
  30139. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30140. }
  30141. //
  30142. let bindGroup;
  30143. if ( sharedGroup ) {
  30144. bindGroup = bindGroupsCache.get( bindingsArray );
  30145. if ( bindGroup === undefined ) {
  30146. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30147. bindGroupsCache.set( bindingsArray, bindGroup );
  30148. }
  30149. } else {
  30150. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30151. }
  30152. return bindGroup;
  30153. }
  30154. /**
  30155. * Returns an array of node uniform groups for the given group name and shader stage.
  30156. *
  30157. * @param {String} groupName - The group name.
  30158. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30159. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  30160. */
  30161. getBindGroupArray( groupName, shaderStage ) {
  30162. const bindings = this.bindings[ shaderStage ];
  30163. let bindGroup = bindings[ groupName ];
  30164. if ( bindGroup === undefined ) {
  30165. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  30166. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  30167. }
  30168. bindings[ groupName ] = bindGroup = [];
  30169. }
  30170. return bindGroup;
  30171. }
  30172. /**
  30173. * Returns a list bindings of all shader stages separated by groups.
  30174. *
  30175. * @return {Array<BindGroup>} The list of bindings.
  30176. */
  30177. getBindings() {
  30178. let bindingsGroups = this.bindGroups;
  30179. if ( bindingsGroups === null ) {
  30180. const groups = {};
  30181. const bindings = this.bindings;
  30182. for ( const shaderStage of shaderStages ) {
  30183. for ( const groupName in bindings[ shaderStage ] ) {
  30184. const uniforms = bindings[ shaderStage ][ groupName ];
  30185. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  30186. groupUniforms.push( ...uniforms );
  30187. }
  30188. }
  30189. bindingsGroups = [];
  30190. for ( const groupName in groups ) {
  30191. const group = groups[ groupName ];
  30192. const bindingsGroup = this._getBindGroup( groupName, group );
  30193. bindingsGroups.push( bindingsGroup );
  30194. }
  30195. this.bindGroups = bindingsGroups;
  30196. }
  30197. return bindingsGroups;
  30198. }
  30199. /**
  30200. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  30201. */
  30202. sortBindingGroups() {
  30203. const bindingsGroups = this.getBindings();
  30204. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30205. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30206. const bindingGroup = bindingsGroups[ i ];
  30207. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30208. bindingGroup.index = i;
  30209. }
  30210. }
  30211. /**
  30212. * The builder maintains each node in a hash-based dictionary.
  30213. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30214. *
  30215. * @param {Node} node - The node to add.
  30216. * @param {Number} hash - The hash of the node.
  30217. */
  30218. setHashNode( node, hash ) {
  30219. this.hashNodes[ hash ] = node;
  30220. }
  30221. /**
  30222. * Adds a node to this builder.
  30223. *
  30224. * @param {Node} node - The node to add.
  30225. */
  30226. addNode( node ) {
  30227. if ( this.nodes.includes( node ) === false ) {
  30228. this.nodes.push( node );
  30229. this.setHashNode( node, node.getHash( this ) );
  30230. }
  30231. }
  30232. /**
  30233. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30234. * and need to follow a certain sequence in the calls to work correctly.
  30235. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30236. *
  30237. * @param {Node} node - The node to add.
  30238. */
  30239. addSequentialNode( node ) {
  30240. if ( this.sequentialNodes.includes( node ) === false ) {
  30241. this.sequentialNodes.push( node );
  30242. }
  30243. }
  30244. /**
  30245. * Checks the update types of nodes
  30246. */
  30247. buildUpdateNodes() {
  30248. for ( const node of this.nodes ) {
  30249. const updateType = node.getUpdateType();
  30250. if ( updateType !== NodeUpdateType.NONE ) {
  30251. this.updateNodes.push( node.getSelf() );
  30252. }
  30253. }
  30254. for ( const node of this.sequentialNodes ) {
  30255. const updateBeforeType = node.getUpdateBeforeType();
  30256. const updateAfterType = node.getUpdateAfterType();
  30257. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30258. this.updateBeforeNodes.push( node.getSelf() );
  30259. }
  30260. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30261. this.updateAfterNodes.push( node.getSelf() );
  30262. }
  30263. }
  30264. }
  30265. /**
  30266. * A reference the current node which is the
  30267. * last node in the chain of nodes.
  30268. *
  30269. * @type {Node}
  30270. */
  30271. get currentNode() {
  30272. return this.chaining[ this.chaining.length - 1 ];
  30273. }
  30274. /**
  30275. * Whether the given texture is filtered or not.
  30276. *
  30277. * @param {Texture} texture - The texture to check.
  30278. * @return {Boolean} Whether the given texture is filtered or not.
  30279. */
  30280. isFilteredTexture( texture ) {
  30281. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30282. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30283. }
  30284. /**
  30285. * Adds the given node to the internal node chain.
  30286. * This is used to check recursive calls in node-graph.
  30287. *
  30288. * @param {Node} node - The node to add.
  30289. */
  30290. addChain( node ) {
  30291. /*
  30292. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30293. console.warn( 'Recursive node: ', node );
  30294. }
  30295. */
  30296. this.chaining.push( node );
  30297. }
  30298. /**
  30299. * Removes the given node from the internal node chain.
  30300. *
  30301. * @param {Node} node - The node to remove.
  30302. */
  30303. removeChain( node ) {
  30304. const lastChain = this.chaining.pop();
  30305. if ( lastChain !== node ) {
  30306. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30307. }
  30308. }
  30309. /**
  30310. * Returns the native shader method name for a given generic name. E.g.
  30311. * the method name `textureDimensions` matches the WGSL name but must be
  30312. * resolved to `textureSize` in GLSL.
  30313. *
  30314. * @abstract
  30315. * @param {String} method - The method name to resolve.
  30316. * @return {String} The resolved method name.
  30317. */
  30318. getMethod( method ) {
  30319. return method;
  30320. }
  30321. /**
  30322. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30323. *
  30324. * @param {Number} hash - The hash of the node.
  30325. * @return {Node} The found node.
  30326. */
  30327. getNodeFromHash( hash ) {
  30328. return this.hashNodes[ hash ];
  30329. }
  30330. /**
  30331. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30332. *
  30333. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30334. * @param {Node} node - The node to add.
  30335. * @return {Node} The node.
  30336. */
  30337. addFlow( shaderStage, node ) {
  30338. this.flowNodes[ shaderStage ].push( node );
  30339. return node;
  30340. }
  30341. /**
  30342. * Sets builder's context.
  30343. *
  30344. * @param {Object} context - The context to set.
  30345. */
  30346. setContext( context ) {
  30347. this.context = context;
  30348. }
  30349. /**
  30350. * Returns the builder's current context.
  30351. *
  30352. * @return {Object} The builder's current context.
  30353. */
  30354. getContext() {
  30355. return this.context;
  30356. }
  30357. /**
  30358. * Gets a context used in shader construction that can be shared across different materials.
  30359. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30360. *
  30361. * @return {Object} The builder's current context without material.
  30362. */
  30363. getSharedContext() {
  30364. ({ ...this.context });
  30365. return this.context;
  30366. }
  30367. /**
  30368. * Sets builder's cache.
  30369. *
  30370. * @param {NodeCache} cache - The cache to set.
  30371. */
  30372. setCache( cache ) {
  30373. this.cache = cache;
  30374. }
  30375. /**
  30376. * Returns the builder's current cache.
  30377. *
  30378. * @return {NodeCache} The builder's current cache.
  30379. */
  30380. getCache() {
  30381. return this.cache;
  30382. }
  30383. /**
  30384. * Returns a cache for the given node.
  30385. *
  30386. * @param {Node} node - The node.
  30387. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30388. * @return {NodeCache} The cache.
  30389. */
  30390. getCacheFromNode( node, parent = true ) {
  30391. const data = this.getDataFromNode( node );
  30392. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30393. return data.cache;
  30394. }
  30395. /**
  30396. * Whether the requested feature is available or not.
  30397. *
  30398. * @abstract
  30399. * @param {String} name - The requested feature.
  30400. * @return {Boolean} Whether the requested feature is supported or not.
  30401. */
  30402. isAvailable( /*name*/ ) {
  30403. return false;
  30404. }
  30405. /**
  30406. * Returns the vertexIndex input variable as a native shader string.
  30407. *
  30408. * @abstract
  30409. * @return {String} The instanceIndex shader string.
  30410. */
  30411. getVertexIndex() {
  30412. console.warn( 'Abstract function.' );
  30413. }
  30414. /**
  30415. * Returns the instanceIndex input variable as a native shader string.
  30416. *
  30417. * @abstract
  30418. * @return {String} The instanceIndex shader string.
  30419. */
  30420. getInstanceIndex() {
  30421. console.warn( 'Abstract function.' );
  30422. }
  30423. /**
  30424. * Returns the drawIndex input variable as a native shader string.
  30425. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30426. *
  30427. * @abstract
  30428. * @return {String} The drawIndex shader string.
  30429. */
  30430. getDrawIndex() {
  30431. console.warn( 'Abstract function.' );
  30432. }
  30433. /**
  30434. * Returns the frontFacing input variable as a native shader string.
  30435. *
  30436. * @abstract
  30437. * @return {String} The frontFacing shader string.
  30438. */
  30439. getFrontFacing() {
  30440. console.warn( 'Abstract function.' );
  30441. }
  30442. /**
  30443. * Returns the fragCoord input variable as a native shader string.
  30444. *
  30445. * @abstract
  30446. * @return {String} The fragCoord shader string.
  30447. */
  30448. getFragCoord() {
  30449. console.warn( 'Abstract function.' );
  30450. }
  30451. /**
  30452. * Whether to flip texture data along its vertical axis or not. WebGL needs
  30453. * this method evaluate to `true`, WebGPU to `false`.
  30454. *
  30455. * @abstract
  30456. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  30457. */
  30458. isFlipY() {
  30459. return false;
  30460. }
  30461. /**
  30462. * Calling this method increases the usage count for the given node by one.
  30463. *
  30464. * @param {Node} node - The node to increase the usage count for.
  30465. * @return {Number} The updated usage count.
  30466. */
  30467. increaseUsage( node ) {
  30468. const nodeData = this.getDataFromNode( node );
  30469. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30470. return nodeData.usageCount;
  30471. }
  30472. /**
  30473. * Generates a texture sample shader string for the given texture data.
  30474. *
  30475. * @abstract
  30476. * @param {Texture} texture - The texture.
  30477. * @param {String} textureProperty - The texture property name.
  30478. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30479. * @return {String} The generated shader string.
  30480. */
  30481. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30482. console.warn( 'Abstract function.' );
  30483. }
  30484. /**
  30485. * Generates a texture LOD shader string for the given texture data.
  30486. *
  30487. * @abstract
  30488. * @param {Texture} texture - The texture.
  30489. * @param {String} textureProperty - The texture property name.
  30490. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30491. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  30492. * @param {String} levelSnippet - Snippet defining the mip level.
  30493. * @return {String} The generated shader string.
  30494. */
  30495. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  30496. console.warn( 'Abstract function.' );
  30497. }
  30498. /**
  30499. * Generates the array declaration string.
  30500. *
  30501. * @param {String} type - The type.
  30502. * @param {Number?} [count] - The count.
  30503. * @return {String} The generated value as a shader string.
  30504. */
  30505. generateArrayDeclaration( type, count ) {
  30506. return this.getType( type ) + '[ ' + count + ' ]';
  30507. }
  30508. /**
  30509. * Generates the array shader string for the given type and value.
  30510. *
  30511. * @param {String} type - The type.
  30512. * @param {Number?} [count] - The count.
  30513. * @param {Array<Node>?} [values=null] - The default values.
  30514. * @return {String} The generated value as a shader string.
  30515. */
  30516. generateArray( type, count, values = null ) {
  30517. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  30518. for ( let i = 0; i < count; i ++ ) {
  30519. const value = values ? values[ i ] : null;
  30520. if ( value !== null ) {
  30521. snippet += value.build( this, type );
  30522. } else {
  30523. snippet += this.generateConst( type );
  30524. }
  30525. if ( i < count - 1 ) snippet += ', ';
  30526. }
  30527. snippet += ' )';
  30528. return snippet;
  30529. }
  30530. /**
  30531. * Generates the shader string for the given type and value.
  30532. *
  30533. * @param {String} type - The type.
  30534. * @param {Any?} [value=null] - The value.
  30535. * @return {String} The generated value as a shader string.
  30536. */
  30537. generateConst( type, value = null ) {
  30538. if ( value === null ) {
  30539. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30540. else if ( type === 'bool' ) value = false;
  30541. else if ( type === 'color' ) value = new Color();
  30542. else if ( type === 'vec2' ) value = new Vector2();
  30543. else if ( type === 'vec3' ) value = new Vector3();
  30544. else if ( type === 'vec4' ) value = new Vector4();
  30545. }
  30546. if ( type === 'float' ) return toFloat( value );
  30547. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30548. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30549. if ( type === 'bool' ) return value ? 'true' : 'false';
  30550. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30551. const typeLength = this.getTypeLength( type );
  30552. const componentType = this.getComponentType( type );
  30553. const generateConst = value => this.generateConst( componentType, value );
  30554. if ( typeLength === 2 ) {
  30555. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30556. } else if ( typeLength === 3 ) {
  30557. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30558. } else if ( typeLength === 4 ) {
  30559. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30560. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30561. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30562. } else if ( typeLength > 4 ) {
  30563. return `${ this.getType( type ) }()`;
  30564. }
  30565. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30566. }
  30567. /**
  30568. * It might be necessary to convert certain data types to different ones
  30569. * so this method can be used to hide the conversion.
  30570. *
  30571. * @param {String} type - The type.
  30572. * @return {String} The updated type.
  30573. */
  30574. getType( type ) {
  30575. if ( type === 'color' ) return 'vec3';
  30576. return type;
  30577. }
  30578. /**
  30579. * Whether the given attribute name is defined in the geometry or not.
  30580. *
  30581. * @param {String} name - The attribute name.
  30582. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  30583. */
  30584. hasGeometryAttribute( name ) {
  30585. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30586. }
  30587. /**
  30588. * Returns a node attribute for the given name and type.
  30589. *
  30590. * @param {String} name - The attribute's name.
  30591. * @param {String} type - The attribute's type.
  30592. * @return {NodeAttribute} The node attribute.
  30593. */
  30594. getAttribute( name, type ) {
  30595. const attributes = this.attributes;
  30596. // find attribute
  30597. for ( const attribute of attributes ) {
  30598. if ( attribute.name === name ) {
  30599. return attribute;
  30600. }
  30601. }
  30602. // create a new if no exist
  30603. const attribute = new NodeAttribute( name, type );
  30604. attributes.push( attribute );
  30605. return attribute;
  30606. }
  30607. /**
  30608. * Returns for the given node and shader stage the property name for the shader.
  30609. *
  30610. * @param {Node} node - The node.
  30611. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30612. * @return {String} The property name.
  30613. */
  30614. getPropertyName( node/*, shaderStage*/ ) {
  30615. return node.name;
  30616. }
  30617. /**
  30618. * Whether the given type is a vector type or not.
  30619. *
  30620. * @param {String} type - The type to check.
  30621. * @return {Boolean} Whether the given type is a vector type or not.
  30622. */
  30623. isVector( type ) {
  30624. return /vec\d/.test( type );
  30625. }
  30626. /**
  30627. * Whether the given type is a matrix type or not.
  30628. *
  30629. * @param {String} type - The type to check.
  30630. * @return {Boolean} Whether the given type is a matrix type or not.
  30631. */
  30632. isMatrix( type ) {
  30633. return /mat\d/.test( type );
  30634. }
  30635. /**
  30636. * Whether the given type is a reference type or not.
  30637. *
  30638. * @param {String} type - The type to check.
  30639. * @return {Boolean} Whether the given type is a reference type or not.
  30640. */
  30641. isReference( type ) {
  30642. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30643. }
  30644. /**
  30645. * Checks if the given texture requires a manual conversion to the working color space.
  30646. *
  30647. * @abstract
  30648. * @param {Texture} texture - The texture to check.
  30649. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30650. */
  30651. needsToWorkingColorSpace( /*texture*/ ) {
  30652. return false;
  30653. }
  30654. /**
  30655. * Returns the component type of a given texture.
  30656. *
  30657. * @param {Texture} texture - The texture.
  30658. * @return {String} The component type.
  30659. */
  30660. getComponentTypeFromTexture( texture ) {
  30661. const type = texture.type;
  30662. if ( texture.isDataTexture ) {
  30663. if ( type === IntType ) return 'int';
  30664. if ( type === UnsignedIntType ) return 'uint';
  30665. }
  30666. return 'float';
  30667. }
  30668. /**
  30669. * Returns the element type for a given type.
  30670. *
  30671. * @param {String} type - The type.
  30672. * @return {String} The element type.
  30673. */
  30674. getElementType( type ) {
  30675. if ( type === 'mat2' ) return 'vec2';
  30676. if ( type === 'mat3' ) return 'vec3';
  30677. if ( type === 'mat4' ) return 'vec4';
  30678. return this.getComponentType( type );
  30679. }
  30680. /**
  30681. * Returns the component type for a given type.
  30682. *
  30683. * @param {String} type - The type.
  30684. * @return {String} The component type.
  30685. */
  30686. getComponentType( type ) {
  30687. type = this.getVectorType( type );
  30688. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30689. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30690. if ( componentType === null ) return null;
  30691. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30692. if ( componentType[ 1 ] === 'i' ) return 'int';
  30693. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30694. return 'float';
  30695. }
  30696. /**
  30697. * Returns the vector type for a given type.
  30698. *
  30699. * @param {String} type - The type.
  30700. * @return {String} The vector type.
  30701. */
  30702. getVectorType( type ) {
  30703. if ( type === 'color' ) return 'vec3';
  30704. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30705. return type;
  30706. }
  30707. /**
  30708. * Returns the data type for the given the length and component type.
  30709. *
  30710. * @param {Number} length - The length.
  30711. * @param {String} [componentType='float'] - The component type.
  30712. * @return {String} The type.
  30713. */
  30714. getTypeFromLength( length, componentType = 'float' ) {
  30715. if ( length === 1 ) return componentType;
  30716. let baseType = getTypeFromLength( length );
  30717. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30718. // fix edge case for mat2x2 being same size as vec4
  30719. if ( /mat2/.test( componentType ) === true ) {
  30720. baseType = baseType.replace( 'vec', 'mat' );
  30721. }
  30722. return prefix + baseType;
  30723. }
  30724. /**
  30725. * Returns the type for a given typed array.
  30726. *
  30727. * @param {TypedArray} array - The typed array.
  30728. * @return {String} The type.
  30729. */
  30730. getTypeFromArray( array ) {
  30731. return typeFromArray.get( array.constructor );
  30732. }
  30733. /**
  30734. * Returns the type for a given buffer attribute.
  30735. *
  30736. * @param {BufferAttribute} attribute - The buffer attribute.
  30737. * @return {String} The type.
  30738. */
  30739. getTypeFromAttribute( attribute ) {
  30740. let dataAttribute = attribute;
  30741. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30742. const array = dataAttribute.array;
  30743. const itemSize = attribute.itemSize;
  30744. const normalized = attribute.normalized;
  30745. let arrayType;
  30746. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30747. arrayType = this.getTypeFromArray( array );
  30748. }
  30749. return this.getTypeFromLength( itemSize, arrayType );
  30750. }
  30751. /**
  30752. * Returns the length for the given data type.
  30753. *
  30754. * @param {String} type - The data type.
  30755. * @return {Number} The length.
  30756. */
  30757. getTypeLength( type ) {
  30758. const vecType = this.getVectorType( type );
  30759. const vecNum = /vec([2-4])/.exec( vecType );
  30760. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30761. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30762. if ( /mat2/.test( type ) === true ) return 4;
  30763. if ( /mat3/.test( type ) === true ) return 9;
  30764. if ( /mat4/.test( type ) === true ) return 16;
  30765. return 0;
  30766. }
  30767. /**
  30768. * Returns the vector type for a given matrix type.
  30769. *
  30770. * @param {String} type - The matrix type.
  30771. * @return {String} The vector type.
  30772. */
  30773. getVectorFromMatrix( type ) {
  30774. return type.replace( 'mat', 'vec' );
  30775. }
  30776. /**
  30777. * For a given type this method changes the component type to the
  30778. * given value. E.g. `vec4` should be changed to the new component type
  30779. * `uint` which results in `uvec4`.
  30780. *
  30781. * @param {String} type - The type.
  30782. * @param {String} newComponentType - The new component type.
  30783. * @return {String} The new type.
  30784. */
  30785. changeComponentType( type, newComponentType ) {
  30786. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30787. }
  30788. /**
  30789. * Returns the integer type pendant for the given type.
  30790. *
  30791. * @param {String} type - The type.
  30792. * @return {String} The integer type.
  30793. */
  30794. getIntegerType( type ) {
  30795. const componentType = this.getComponentType( type );
  30796. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30797. return this.changeComponentType( type, 'int' );
  30798. }
  30799. /**
  30800. * Adds a stack node to the internal stack.
  30801. *
  30802. * @return {StackNode} The added stack node.
  30803. */
  30804. addStack() {
  30805. this.stack = stack( this.stack );
  30806. this.stacks.push( getCurrentStack() || this.stack );
  30807. setCurrentStack( this.stack );
  30808. return this.stack;
  30809. }
  30810. /**
  30811. * Removes the last stack node from the internal stack.
  30812. *
  30813. * @return {StackNode} The removed stack node.
  30814. */
  30815. removeStack() {
  30816. const lastStack = this.stack;
  30817. this.stack = lastStack.parent;
  30818. setCurrentStack( this.stacks.pop() );
  30819. return lastStack;
  30820. }
  30821. /**
  30822. * The builder maintains (cached) data for each node during the building process. This method
  30823. * can be used to get these data for a specific shader stage and cache.
  30824. *
  30825. * @param {Node} node - The node to get the data for.
  30826. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30827. * @param {NodeCache?} cache - An optional cache.
  30828. * @return {Object} The node data.
  30829. */
  30830. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30831. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30832. let nodeData = cache.getData( node );
  30833. if ( nodeData === undefined ) {
  30834. nodeData = {};
  30835. cache.setData( node, nodeData );
  30836. }
  30837. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30838. return nodeData[ shaderStage ];
  30839. }
  30840. /**
  30841. * Returns the properties for the given node and shader stage.
  30842. *
  30843. * @param {Node} node - The node to get the properties for.
  30844. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30845. * @return {Object} The node properties.
  30846. */
  30847. getNodeProperties( node, shaderStage = 'any' ) {
  30848. const nodeData = this.getDataFromNode( node, shaderStage );
  30849. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30850. }
  30851. /**
  30852. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30853. *
  30854. * @param {BufferAttributeNode} node - The buffer attribute node.
  30855. * @param {String} type - The node type.
  30856. * @return {NodeAttribute} The node attribute.
  30857. */
  30858. getBufferAttributeFromNode( node, type ) {
  30859. const nodeData = this.getDataFromNode( node );
  30860. let bufferAttribute = nodeData.bufferAttribute;
  30861. if ( bufferAttribute === undefined ) {
  30862. const index = this.uniforms.index ++;
  30863. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30864. this.bufferAttributes.push( bufferAttribute );
  30865. nodeData.bufferAttribute = bufferAttribute;
  30866. }
  30867. return bufferAttribute;
  30868. }
  30869. /**
  30870. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30871. *
  30872. * @param {OutputStructNode} node - The output struct node.
  30873. * @param {Array<String>} types - The output struct types.
  30874. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30875. * @return {StructTypeNode} The struct type attribute.
  30876. */
  30877. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30878. const nodeData = this.getDataFromNode( node, shaderStage );
  30879. let structType = nodeData.structType;
  30880. if ( structType === undefined ) {
  30881. const index = this.structs.index ++;
  30882. structType = new StructTypeNode( 'StructType' + index, types );
  30883. this.structs[ shaderStage ].push( structType );
  30884. nodeData.structType = structType;
  30885. }
  30886. return structType;
  30887. }
  30888. /**
  30889. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30890. *
  30891. * @param {UniformNode} node - The uniform node.
  30892. * @param {String} type - The uniform type.
  30893. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30894. * @param {String?} name - The name of the uniform.
  30895. * @return {NodeUniform} The node uniform.
  30896. */
  30897. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30898. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30899. let nodeUniform = nodeData.uniform;
  30900. if ( nodeUniform === undefined ) {
  30901. const index = this.uniforms.index ++;
  30902. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30903. this.uniforms[ shaderStage ].push( nodeUniform );
  30904. nodeData.uniform = nodeUniform;
  30905. }
  30906. return nodeUniform;
  30907. }
  30908. /**
  30909. * Returns the array length.
  30910. *
  30911. * @param {Node} node - The node.
  30912. * @return {Number?} The array length.
  30913. */
  30914. getArrayCount( node ) {
  30915. let count = null;
  30916. if ( node.isArrayNode ) count = node.count;
  30917. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  30918. return count;
  30919. }
  30920. /**
  30921. * Returns an instance of {@link NodeVar} for the given variable node.
  30922. *
  30923. * @param {VarNode} node - The variable node.
  30924. * @param {String?} name - The variable's name.
  30925. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30926. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30927. * @param {Boolean} [readOnly=false] - Whether the variable is read-only or not.
  30928. *
  30929. * @return {NodeVar} The node variable.
  30930. */
  30931. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  30932. const nodeData = this.getDataFromNode( node, shaderStage );
  30933. let nodeVar = nodeData.variable;
  30934. if ( nodeVar === undefined ) {
  30935. const idNS = readOnly ? '_const' : '_var';
  30936. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30937. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  30938. if ( name === null ) {
  30939. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  30940. this.vars[ idNS ] ++;
  30941. }
  30942. //
  30943. const count = this.getArrayCount( node );
  30944. nodeVar = new NodeVar( name, type, readOnly, count );
  30945. if ( ! readOnly ) {
  30946. vars.push( nodeVar );
  30947. }
  30948. nodeData.variable = nodeVar;
  30949. }
  30950. return nodeVar;
  30951. }
  30952. /**
  30953. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  30954. *
  30955. * @param {Node} node - The varying node.
  30956. * @return {Boolean} Returns true if deterministic.
  30957. */
  30958. isDeterministic( node ) {
  30959. if ( node.isMathNode ) {
  30960. return this.isDeterministic( node.aNode ) &&
  30961. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  30962. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  30963. } else if ( node.isOperatorNode ) {
  30964. return this.isDeterministic( node.aNode ) &&
  30965. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  30966. } else if ( node.isArrayNode ) {
  30967. if ( node.values !== null ) {
  30968. for ( const n of node.values ) {
  30969. if ( ! this.isDeterministic( n ) ) {
  30970. return false;
  30971. }
  30972. }
  30973. }
  30974. return true;
  30975. } else if ( node.isConstNode ) {
  30976. return true;
  30977. }
  30978. return false;
  30979. }
  30980. /**
  30981. * Returns an instance of {@link NodeVarying} for the given varying node.
  30982. *
  30983. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30984. * @param {String?} name - The varying's name.
  30985. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30986. * @return {NodeVar} The node varying.
  30987. */
  30988. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30989. const nodeData = this.getDataFromNode( node, 'any' );
  30990. let nodeVarying = nodeData.varying;
  30991. if ( nodeVarying === undefined ) {
  30992. const varyings = this.varyings;
  30993. const index = varyings.length;
  30994. if ( name === null ) name = 'nodeVarying' + index;
  30995. nodeVarying = new NodeVarying( name, type );
  30996. varyings.push( nodeVarying );
  30997. nodeData.varying = nodeVarying;
  30998. }
  30999. return nodeVarying;
  31000. }
  31001. /**
  31002. * Returns an instance of {@link NodeCode} for the given code node.
  31003. *
  31004. * @param {CodeNode} node - The code node.
  31005. * @param {String} type - The node type.
  31006. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31007. * @return {NodeCode} The node code.
  31008. */
  31009. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31010. const nodeData = this.getDataFromNode( node );
  31011. let nodeCode = nodeData.code;
  31012. if ( nodeCode === undefined ) {
  31013. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31014. const index = codes.length;
  31015. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31016. codes.push( nodeCode );
  31017. nodeData.code = nodeCode;
  31018. }
  31019. return nodeCode;
  31020. }
  31021. /**
  31022. * Adds a code flow based on the code-block hierarchy.
  31023. * This is used so that code-blocks like If,Else create their variables locally if the Node
  31024. * is only used inside one of these conditionals in the current shader stage.
  31025. *
  31026. * @param {Node} node - The node to add.
  31027. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  31028. */
  31029. addFlowCodeHierarchy( node, nodeBlock ) {
  31030. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31031. let needsFlowCode = true;
  31032. let nodeBlockHierarchy = nodeBlock;
  31033. while ( nodeBlockHierarchy ) {
  31034. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31035. needsFlowCode = false;
  31036. break;
  31037. }
  31038. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31039. }
  31040. if ( needsFlowCode ) {
  31041. for ( const flowCode of flowCodes ) {
  31042. this.addLineFlowCode( flowCode );
  31043. }
  31044. }
  31045. }
  31046. /**
  31047. * Add a inline-code to the current flow code-block.
  31048. *
  31049. * @param {Node} node - The node to add.
  31050. * @param {String} code - The code to add.
  31051. * @param {Node} nodeBlock - Current ConditionalNode
  31052. */
  31053. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31054. const nodeData = this.getDataFromNode( node );
  31055. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31056. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31057. flowCodes.push( code );
  31058. codeBlock.set( nodeBlock, true );
  31059. }
  31060. /**
  31061. * Add a inline-code to the current flow.
  31062. *
  31063. * @param {String} code - The code to add.
  31064. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  31065. * @return {NodeBuilder} A reference to this node builder.
  31066. */
  31067. addLineFlowCode( code, node = null ) {
  31068. if ( code === '' ) return this;
  31069. if ( node !== null && this.context.nodeBlock ) {
  31070. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31071. }
  31072. code = this.tab + code;
  31073. if ( ! /;\s*$/.test( code ) ) {
  31074. code = code + ';\n';
  31075. }
  31076. this.flow.code += code;
  31077. return this;
  31078. }
  31079. /**
  31080. * Adds a code to the current code flow.
  31081. *
  31082. * @param {String} code - Shader code.
  31083. * @return {NodeBuilder} A reference to this node builder.
  31084. */
  31085. addFlowCode( code ) {
  31086. this.flow.code += code;
  31087. return this;
  31088. }
  31089. /**
  31090. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  31091. * Typically used in codes with If,Else.
  31092. *
  31093. * @return {NodeBuilder} A reference to this node builder.
  31094. */
  31095. addFlowTab() {
  31096. this.tab += '\t';
  31097. return this;
  31098. }
  31099. /**
  31100. * Removes a tab.
  31101. *
  31102. * @return {NodeBuilder} A reference to this node builder.
  31103. */
  31104. removeFlowTab() {
  31105. this.tab = this.tab.slice( 0, -1 );
  31106. return this;
  31107. }
  31108. /**
  31109. * Gets the current flow data based on a Node.
  31110. *
  31111. * @param {Node} node - Node that the flow was started.
  31112. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31113. * @return {Object} The flow data.
  31114. */
  31115. getFlowData( node/*, shaderStage*/ ) {
  31116. return this.flowsData.get( node );
  31117. }
  31118. /**
  31119. * Executes the node flow based on a root node to generate the final shader code.
  31120. *
  31121. * @param {Node} node - The node to execute.
  31122. * @return {Object} The code flow.
  31123. */
  31124. flowNode( node ) {
  31125. const output = node.getNodeType( this );
  31126. const flowData = this.flowChildNode( node, output );
  31127. this.flowsData.set( node, flowData );
  31128. return flowData;
  31129. }
  31130. /**
  31131. * Returns the native shader operator name for a given generic name.
  31132. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31133. *
  31134. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  31135. * @return {FunctionNode} The build function node.
  31136. */
  31137. buildFunctionNode( shaderNode ) {
  31138. const fn = new FunctionNode();
  31139. const previous = this.currentFunctionNode;
  31140. this.currentFunctionNode = fn;
  31141. fn.code = this.buildFunctionCode( shaderNode );
  31142. this.currentFunctionNode = previous;
  31143. return fn;
  31144. }
  31145. /**
  31146. * Generates a code flow based on a TSL function: Fn().
  31147. *
  31148. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  31149. * @return {Object}
  31150. */
  31151. flowShaderNode( shaderNode ) {
  31152. const layout = shaderNode.layout;
  31153. const inputs = {
  31154. [ Symbol.iterator ]() {
  31155. let index = 0;
  31156. const values = Object.values( this );
  31157. return {
  31158. next: () => ( {
  31159. value: values[ index ],
  31160. done: index ++ >= values.length
  31161. } )
  31162. };
  31163. }
  31164. };
  31165. for ( const input of layout.inputs ) {
  31166. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31167. }
  31168. //
  31169. shaderNode.layout = null;
  31170. const callNode = shaderNode.call( inputs );
  31171. const flowData = this.flowStagesNode( callNode, layout.type );
  31172. shaderNode.layout = layout;
  31173. return flowData;
  31174. }
  31175. /**
  31176. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  31177. *
  31178. * @param {Node} node - The node to execute.
  31179. * @param {String?} output - Expected output type. For example 'vec3'.
  31180. * @return {Object}
  31181. */
  31182. flowStagesNode( node, output = null ) {
  31183. const previousFlow = this.flow;
  31184. const previousVars = this.vars;
  31185. const previousCache = this.cache;
  31186. const previousBuildStage = this.buildStage;
  31187. const previousStack = this.stack;
  31188. const flow = {
  31189. code: ''
  31190. };
  31191. this.flow = flow;
  31192. this.vars = {};
  31193. this.cache = new NodeCache();
  31194. this.stack = stack();
  31195. for ( const buildStage of defaultBuildStages ) {
  31196. this.setBuildStage( buildStage );
  31197. flow.result = node.build( this, output );
  31198. }
  31199. flow.vars = this.getVars( this.shaderStage );
  31200. this.flow = previousFlow;
  31201. this.vars = previousVars;
  31202. this.cache = previousCache;
  31203. this.stack = previousStack;
  31204. this.setBuildStage( previousBuildStage );
  31205. return flow;
  31206. }
  31207. /**
  31208. * Returns the native shader operator name for a given generic name.
  31209. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31210. *
  31211. * @abstract
  31212. * @param {String} op - The operator name to resolve.
  31213. * @return {String} The resolved operator name.
  31214. */
  31215. getFunctionOperator( /* op */ ) {
  31216. return null;
  31217. }
  31218. /**
  31219. * Generates a code flow based on a child Node.
  31220. *
  31221. * @param {Node} node - The node to execute.
  31222. * @param {String?} output - Expected output type. For example 'vec3'.
  31223. * @return {Object} The code flow.
  31224. */
  31225. flowChildNode( node, output = null ) {
  31226. const previousFlow = this.flow;
  31227. const flow = {
  31228. code: ''
  31229. };
  31230. this.flow = flow;
  31231. flow.result = node.build( this, output );
  31232. this.flow = previousFlow;
  31233. return flow;
  31234. }
  31235. /**
  31236. * Executes a flow of code in a different stage.
  31237. *
  31238. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  31239. * return the value in fragment-stage even if it is being executed in an input fragment.
  31240. *
  31241. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31242. * @param {Node} node - The node to execute.
  31243. * @param {String?} output - Expected output type. For example 'vec3'.
  31244. * @param {String?} propertyName - The property name to assign the result.
  31245. * @return {Object}
  31246. */
  31247. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31248. const previousShaderStage = this.shaderStage;
  31249. this.setShaderStage( shaderStage );
  31250. const flowData = this.flowChildNode( node, output );
  31251. if ( propertyName !== null ) {
  31252. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31253. }
  31254. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31255. this.setShaderStage( previousShaderStage );
  31256. return flowData;
  31257. }
  31258. /**
  31259. * Returns an array holding all node attributes of this node builder.
  31260. *
  31261. * @return {Array<NodeAttribute>} The node attributes of this builder.
  31262. */
  31263. getAttributesArray() {
  31264. return this.attributes.concat( this.bufferAttributes );
  31265. }
  31266. /**
  31267. * Returns the attribute definitions as a shader string for the given shader stage.
  31268. *
  31269. * @abstract
  31270. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31271. * @return {String} The attribute code section.
  31272. */
  31273. getAttributes( /*shaderStage*/ ) {
  31274. console.warn( 'Abstract function.' );
  31275. }
  31276. /**
  31277. * Returns the varying definitions as a shader string for the given shader stage.
  31278. *
  31279. * @abstract
  31280. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31281. * @return {String} The varying code section.
  31282. */
  31283. getVaryings( /*shaderStage*/ ) {
  31284. console.warn( 'Abstract function.' );
  31285. }
  31286. /**
  31287. * Returns a single variable definition as a shader string for the given variable type and name.
  31288. *
  31289. * @param {String} type - The variable's type.
  31290. * @param {String} name - The variable's name.
  31291. * @param {Number?} [count=null] - The array length.
  31292. * @return {String} The shader string.
  31293. */
  31294. getVar( type, name, count = null ) {
  31295. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  31296. }
  31297. /**
  31298. * Returns the variable definitions as a shader string for the given shader stage.
  31299. *
  31300. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31301. * @return {String} The variable code section.
  31302. */
  31303. getVars( shaderStage ) {
  31304. let snippet = '';
  31305. const vars = this.vars[ shaderStage ];
  31306. if ( vars !== undefined ) {
  31307. for ( const variable of vars ) {
  31308. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31309. }
  31310. }
  31311. return snippet;
  31312. }
  31313. /**
  31314. * Returns the uniform definitions as a shader string for the given shader stage.
  31315. *
  31316. * @abstract
  31317. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31318. * @return {String} The uniform code section.
  31319. */
  31320. getUniforms( /*shaderStage*/ ) {
  31321. console.warn( 'Abstract function.' );
  31322. }
  31323. /**
  31324. * Returns the native code definitions as a shader string for the given shader stage.
  31325. *
  31326. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31327. * @return {String} The native code section.
  31328. */
  31329. getCodes( shaderStage ) {
  31330. const codes = this.codes[ shaderStage ];
  31331. let code = '';
  31332. if ( codes !== undefined ) {
  31333. for ( const nodeCode of codes ) {
  31334. code += nodeCode.code + '\n';
  31335. }
  31336. }
  31337. return code;
  31338. }
  31339. /**
  31340. * Returns the hash of this node builder.
  31341. *
  31342. * @return {String} The hash.
  31343. */
  31344. getHash() {
  31345. return this.vertexShader + this.fragmentShader + this.computeShader;
  31346. }
  31347. /**
  31348. * Sets the current shader stage.
  31349. *
  31350. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  31351. */
  31352. setShaderStage( shaderStage ) {
  31353. this.shaderStage = shaderStage;
  31354. }
  31355. /**
  31356. * Returns the current shader stage.
  31357. *
  31358. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  31359. */
  31360. getShaderStage() {
  31361. return this.shaderStage;
  31362. }
  31363. /**
  31364. * Sets the current build stage.
  31365. *
  31366. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  31367. */
  31368. setBuildStage( buildStage ) {
  31369. this.buildStage = buildStage;
  31370. }
  31371. /**
  31372. * Returns the current build stage.
  31373. *
  31374. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  31375. */
  31376. getBuildStage() {
  31377. return this.buildStage;
  31378. }
  31379. /**
  31380. * Controls the code build of the shader stages.
  31381. *
  31382. * @abstract
  31383. */
  31384. buildCode() {
  31385. console.warn( 'Abstract function.' );
  31386. }
  31387. /**
  31388. * Central build method which controls the build for the given object.
  31389. *
  31390. * @return {NodeBuilder} A reference to this node builder.
  31391. */
  31392. build() {
  31393. const { object, material, renderer } = this;
  31394. if ( material !== null ) {
  31395. let nodeMaterial = renderer.library.fromMaterial( material );
  31396. if ( nodeMaterial === null ) {
  31397. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31398. nodeMaterial = new NodeMaterial();
  31399. }
  31400. nodeMaterial.build( this );
  31401. } else {
  31402. this.addFlow( 'compute', object );
  31403. }
  31404. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31405. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31406. // generate() -> stage 3: generate shader
  31407. for ( const buildStage of defaultBuildStages ) {
  31408. this.setBuildStage( buildStage );
  31409. if ( this.context.vertex && this.context.vertex.isNode ) {
  31410. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31411. }
  31412. for ( const shaderStage of shaderStages ) {
  31413. this.setShaderStage( shaderStage );
  31414. const flowNodes = this.flowNodes[ shaderStage ];
  31415. for ( const node of flowNodes ) {
  31416. if ( buildStage === 'generate' ) {
  31417. this.flowNode( node );
  31418. } else {
  31419. node.build( this );
  31420. }
  31421. }
  31422. }
  31423. }
  31424. this.setBuildStage( null );
  31425. this.setShaderStage( null );
  31426. // stage 4: build code for a specific output
  31427. this.buildCode();
  31428. this.buildUpdateNodes();
  31429. return this;
  31430. }
  31431. /**
  31432. * Returns a uniform representation which is later used for UBO generation and rendering.
  31433. *
  31434. * @param {NodeUniform} uniformNode - The uniform node.
  31435. * @param {String} type - The requested type.
  31436. * @return {Uniform} The uniform.
  31437. */
  31438. getNodeUniform( uniformNode, type ) {
  31439. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31440. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31441. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31442. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31443. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31444. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  31445. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31446. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31447. throw new Error( `Uniform "${type}" not declared.` );
  31448. }
  31449. /**
  31450. * Formats the given shader snippet from a given type into another one. E.g.
  31451. * this method might be used to convert a simple float string `"1.0"` into a
  31452. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  31453. *
  31454. * @param {String} snippet - The shader snippet.
  31455. * @param {String} fromType - The source type.
  31456. * @param {String} toType - The target type.
  31457. * @return {String} The updated shader string.
  31458. */
  31459. format( snippet, fromType, toType ) {
  31460. fromType = this.getVectorType( fromType );
  31461. toType = this.getVectorType( toType );
  31462. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31463. return snippet;
  31464. }
  31465. const fromTypeLength = this.getTypeLength( fromType );
  31466. const toTypeLength = this.getTypeLength( toType );
  31467. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31468. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31469. }
  31470. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31471. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31472. }
  31473. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31474. // @TODO: ignore for now
  31475. return snippet;
  31476. }
  31477. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31478. // @TODO: ignore for now
  31479. return snippet;
  31480. }
  31481. if ( fromTypeLength === toTypeLength ) {
  31482. return `${ this.getType( toType ) }( ${ snippet } )`;
  31483. }
  31484. if ( fromTypeLength > toTypeLength ) {
  31485. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31486. }
  31487. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31488. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31489. }
  31490. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31491. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31492. }
  31493. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31494. // convert a number value to vector type, e.g:
  31495. // vec3( 1u ) -> vec3( float( 1u ) )
  31496. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31497. }
  31498. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31499. }
  31500. /**
  31501. * Returns a signature with the engine's current revision.
  31502. *
  31503. * @return {String} The signature.
  31504. */
  31505. getSignature() {
  31506. return `// Three.js r${ REVISION } - Node System\n`;
  31507. }
  31508. // Deprecated
  31509. /**
  31510. * @function
  31511. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  31512. *
  31513. * @param {String} [type='NodeMaterial'] - The node material type.
  31514. * @throws {Error}
  31515. */
  31516. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31517. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31518. }
  31519. }
  31520. /**
  31521. * Management class for updating nodes. The module tracks metrics like
  31522. * the elapsed time, delta time, the render and frame ID to correctly
  31523. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  31524. * and {@link Node#updateAfter} depending on the node's configuration.
  31525. */
  31526. class NodeFrame {
  31527. /**
  31528. * Constructs a new node fame.
  31529. */
  31530. constructor() {
  31531. /**
  31532. * The elapsed time in seconds.
  31533. *
  31534. * @type {Number}
  31535. * @default 0
  31536. */
  31537. this.time = 0;
  31538. /**
  31539. * The delta time in seconds.
  31540. *
  31541. * @type {Number}
  31542. * @default 0
  31543. */
  31544. this.deltaTime = 0;
  31545. /**
  31546. * The frame ID.
  31547. *
  31548. * @type {Number}
  31549. * @default 0
  31550. */
  31551. this.frameId = 0;
  31552. /**
  31553. * The render ID.
  31554. *
  31555. * @type {Number}
  31556. * @default 0
  31557. */
  31558. this.renderId = 0;
  31559. /**
  31560. * Used to control the {@link Node#update} call.
  31561. *
  31562. * @type {WeakMap<Node, Object>}
  31563. */
  31564. this.updateMap = new WeakMap();
  31565. /**
  31566. * Used to control the {@link Node#updateBefore} call.
  31567. *
  31568. * @type {WeakMap<Node, Object>}
  31569. */
  31570. this.updateBeforeMap = new WeakMap();
  31571. /**
  31572. * Used to control the {@link Node#updateAfter} call.
  31573. *
  31574. * @type {WeakMap<Node, Object>}
  31575. */
  31576. this.updateAfterMap = new WeakMap();
  31577. /**
  31578. * A reference to the current renderer.
  31579. *
  31580. * @type {Renderer?}
  31581. * @default null
  31582. */
  31583. this.renderer = null;
  31584. /**
  31585. * A reference to the current material.
  31586. *
  31587. * @type {Material?}
  31588. * @default null
  31589. */
  31590. this.material = null;
  31591. /**
  31592. * A reference to the current camera.
  31593. *
  31594. * @type {Camera?}
  31595. * @default null
  31596. */
  31597. this.camera = null;
  31598. /**
  31599. * A reference to the current 3D object.
  31600. *
  31601. * @type {Object3D?}
  31602. * @default null
  31603. */
  31604. this.object = null;
  31605. /**
  31606. * A reference to the current scene.
  31607. *
  31608. * @type {Scene?}
  31609. * @default null
  31610. */
  31611. this.scene = null;
  31612. }
  31613. /**
  31614. * Returns a dictionary for a given node and update map which
  31615. * is used to correctly call node update methods per frame or render.
  31616. *
  31617. * @private
  31618. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  31619. * @param {Node} nodeRef - The reference to the current node.
  31620. * @return {Object<String,WeakMap>} The dictionary.
  31621. */
  31622. _getMaps( referenceMap, nodeRef ) {
  31623. let maps = referenceMap.get( nodeRef );
  31624. if ( maps === undefined ) {
  31625. maps = {
  31626. renderMap: new WeakMap(),
  31627. frameMap: new WeakMap()
  31628. };
  31629. referenceMap.set( nodeRef, maps );
  31630. }
  31631. return maps;
  31632. }
  31633. /**
  31634. * This method executes the {@link Node#updateBefore} for the given node.
  31635. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  31636. * is only executed once per frame, render or object depending on the update
  31637. * type.
  31638. *
  31639. * @param {Node} node - The node that should be updated.
  31640. */
  31641. updateBeforeNode( node ) {
  31642. const updateType = node.getUpdateBeforeType();
  31643. const reference = node.updateReference( this );
  31644. if ( updateType === NodeUpdateType.FRAME ) {
  31645. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31646. if ( frameMap.get( reference ) !== this.frameId ) {
  31647. if ( node.updateBefore( this ) !== false ) {
  31648. frameMap.set( reference, this.frameId );
  31649. }
  31650. }
  31651. } else if ( updateType === NodeUpdateType.RENDER ) {
  31652. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31653. if ( renderMap.get( reference ) !== this.renderId ) {
  31654. if ( node.updateBefore( this ) !== false ) {
  31655. renderMap.set( reference, this.renderId );
  31656. }
  31657. }
  31658. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31659. node.updateBefore( this );
  31660. }
  31661. }
  31662. /**
  31663. * This method executes the {@link Node#updateAfter} for the given node.
  31664. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  31665. * is only executed once per frame, render or object depending on the update
  31666. * type.
  31667. *
  31668. * @param {Node} node - The node that should be updated.
  31669. */
  31670. updateAfterNode( node ) {
  31671. const updateType = node.getUpdateAfterType();
  31672. const reference = node.updateReference( this );
  31673. if ( updateType === NodeUpdateType.FRAME ) {
  31674. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31675. if ( frameMap.get( reference ) !== this.frameId ) {
  31676. if ( node.updateAfter( this ) !== false ) {
  31677. frameMap.set( reference, this.frameId );
  31678. }
  31679. }
  31680. } else if ( updateType === NodeUpdateType.RENDER ) {
  31681. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31682. if ( renderMap.get( reference ) !== this.renderId ) {
  31683. if ( node.updateAfter( this ) !== false ) {
  31684. renderMap.set( reference, this.renderId );
  31685. }
  31686. }
  31687. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31688. node.updateAfter( this );
  31689. }
  31690. }
  31691. /**
  31692. * This method executes the {@link Node#update} for the given node.
  31693. * It makes sure {@link Node#updateType} is honored meaning the update
  31694. * is only executed once per frame, render or object depending on the update
  31695. * type.
  31696. *
  31697. * @param {Node} node - The node that should be updated.
  31698. */
  31699. updateNode( node ) {
  31700. const updateType = node.getUpdateType();
  31701. const reference = node.updateReference( this );
  31702. if ( updateType === NodeUpdateType.FRAME ) {
  31703. const { frameMap } = this._getMaps( this.updateMap, reference );
  31704. if ( frameMap.get( reference ) !== this.frameId ) {
  31705. if ( node.update( this ) !== false ) {
  31706. frameMap.set( reference, this.frameId );
  31707. }
  31708. }
  31709. } else if ( updateType === NodeUpdateType.RENDER ) {
  31710. const { renderMap } = this._getMaps( this.updateMap, reference );
  31711. if ( renderMap.get( reference ) !== this.renderId ) {
  31712. if ( node.update( this ) !== false ) {
  31713. renderMap.set( reference, this.renderId );
  31714. }
  31715. }
  31716. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31717. node.update( this );
  31718. }
  31719. }
  31720. /**
  31721. * Updates the internal state of the node frame. This method is
  31722. * called by the renderer in its internal animation loop.
  31723. */
  31724. update() {
  31725. this.frameId ++;
  31726. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31727. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31728. this.lastTime = performance.now();
  31729. this.time += this.deltaTime;
  31730. }
  31731. }
  31732. /**
  31733. * Describes the input of a {@link NodeFunction}.
  31734. */
  31735. class NodeFunctionInput {
  31736. /**
  31737. * Constructs a new node function input.
  31738. *
  31739. * @param {String} type - The input type.
  31740. * @param {String} name - The input name.
  31741. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31742. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31743. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31744. */
  31745. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31746. /**
  31747. * The input type.
  31748. *
  31749. * @type {String}
  31750. */
  31751. this.type = type;
  31752. /**
  31753. * The input name.
  31754. *
  31755. * @type {String}
  31756. */
  31757. this.name = name;
  31758. /**
  31759. * If the input is an Array, count will be the length.
  31760. *
  31761. * @type {Number?}
  31762. * @default null
  31763. */
  31764. this.count = count;
  31765. /**
  31766. *The parameter qualifier (only relevant for GLSL).
  31767. *
  31768. * @type {('in'|'out'|'inout')}
  31769. * @default ''
  31770. */
  31771. this.qualifier = qualifier;
  31772. /**
  31773. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31774. *
  31775. * @type {Boolean}
  31776. * @default false
  31777. */
  31778. this.isConst = isConst;
  31779. }
  31780. }
  31781. NodeFunctionInput.isNodeFunctionInput = true;
  31782. /**
  31783. * Module for representing directional lights as nodes.
  31784. *
  31785. * @augments AnalyticLightNode
  31786. */
  31787. class DirectionalLightNode extends AnalyticLightNode {
  31788. static get type() {
  31789. return 'DirectionalLightNode';
  31790. }
  31791. /**
  31792. * Constructs a new directional light node.
  31793. *
  31794. * @param {DirectionalLight?} [light=null] - The directional light source.
  31795. */
  31796. constructor( light = null ) {
  31797. super( light );
  31798. }
  31799. setup( builder ) {
  31800. super.setup( builder );
  31801. const lightingModel = builder.context.lightingModel;
  31802. const lightColor = this.colorNode;
  31803. const lightDirection = lightTargetDirection( this.light );
  31804. const reflectedLight = builder.context.reflectedLight;
  31805. lightingModel.direct( {
  31806. lightDirection,
  31807. lightColor,
  31808. reflectedLight
  31809. }, builder.stack, builder );
  31810. }
  31811. }
  31812. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31813. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31814. let _ltcLib = null;
  31815. /**
  31816. * Module for representing rect area lights as nodes.
  31817. *
  31818. * @augments AnalyticLightNode
  31819. */
  31820. class RectAreaLightNode extends AnalyticLightNode {
  31821. static get type() {
  31822. return 'RectAreaLightNode';
  31823. }
  31824. /**
  31825. * Constructs a new rect area light node.
  31826. *
  31827. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31828. */
  31829. constructor( light = null ) {
  31830. super( light );
  31831. /**
  31832. * Uniform node representing the half height of the are light.
  31833. *
  31834. * @type {UniformNode<vec3>}
  31835. */
  31836. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31837. /**
  31838. * Uniform node representing the half width of the are light.
  31839. *
  31840. * @type {UniformNode<vec3>}
  31841. */
  31842. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31843. /**
  31844. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31845. * relies on `viewMatrix` which might vary per render call.
  31846. *
  31847. * @type {String}
  31848. * @default 'render'
  31849. */
  31850. this.updateType = NodeUpdateType.RENDER;
  31851. }
  31852. /**
  31853. * Overwritten to updated rect area light specific uniforms.
  31854. *
  31855. * @param {NodeFrame} frame - A reference to the current node frame.
  31856. */
  31857. update( frame ) {
  31858. super.update( frame );
  31859. const { light } = this;
  31860. const viewMatrix = frame.camera.matrixWorldInverse;
  31861. _matrix42.identity();
  31862. _matrix41.copy( light.matrixWorld );
  31863. _matrix41.premultiply( viewMatrix );
  31864. _matrix42.extractRotation( _matrix41 );
  31865. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31866. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31867. this.halfWidth.value.applyMatrix4( _matrix42 );
  31868. this.halfHeight.value.applyMatrix4( _matrix42 );
  31869. }
  31870. setup( builder ) {
  31871. super.setup( builder );
  31872. let ltc_1, ltc_2;
  31873. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31874. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31875. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31876. } else {
  31877. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31878. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31879. }
  31880. const { colorNode, light } = this;
  31881. const lightingModel = builder.context.lightingModel;
  31882. const lightPosition = lightViewPosition( light );
  31883. const reflectedLight = builder.context.reflectedLight;
  31884. lightingModel.directRectArea( {
  31885. lightColor: colorNode,
  31886. lightPosition,
  31887. halfWidth: this.halfWidth,
  31888. halfHeight: this.halfHeight,
  31889. reflectedLight,
  31890. ltc_1,
  31891. ltc_2
  31892. }, builder.stack, builder );
  31893. }
  31894. /**
  31895. * Used to configure the internal BRDF approximation texture data.
  31896. *
  31897. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31898. */
  31899. static setLTC( ltc ) {
  31900. _ltcLib = ltc;
  31901. }
  31902. }
  31903. /**
  31904. * Module for representing spot lights as nodes.
  31905. *
  31906. * @augments AnalyticLightNode
  31907. */
  31908. class SpotLightNode extends AnalyticLightNode {
  31909. static get type() {
  31910. return 'SpotLightNode';
  31911. }
  31912. /**
  31913. * Constructs a new spot light node.
  31914. *
  31915. * @param {SpotLight?} [light=null] - The spot light source.
  31916. */
  31917. constructor( light = null ) {
  31918. super( light );
  31919. /**
  31920. * Uniform node representing the cone cosine.
  31921. *
  31922. * @type {UniformNode<float>}
  31923. */
  31924. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31925. /**
  31926. * Uniform node representing the penumbra cosine.
  31927. *
  31928. * @type {UniformNode<float>}
  31929. */
  31930. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31931. /**
  31932. * Uniform node representing the cutoff distance.
  31933. *
  31934. * @type {UniformNode<float>}
  31935. */
  31936. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31937. /**
  31938. * Uniform node representing the decay exponent.
  31939. *
  31940. * @type {UniformNode<float>}
  31941. */
  31942. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31943. }
  31944. /**
  31945. * Overwritten to updated spot light specific uniforms.
  31946. *
  31947. * @param {NodeFrame} frame - A reference to the current node frame.
  31948. */
  31949. update( frame ) {
  31950. super.update( frame );
  31951. const { light } = this;
  31952. this.coneCosNode.value = Math.cos( light.angle );
  31953. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31954. this.cutoffDistanceNode.value = light.distance;
  31955. this.decayExponentNode.value = light.decay;
  31956. }
  31957. /**
  31958. * Computes the spot attenuation for the given angle.
  31959. *
  31960. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31961. * @return {Node<float>} The spot attenuation.
  31962. */
  31963. getSpotAttenuation( angleCosine ) {
  31964. const { coneCosNode, penumbraCosNode } = this;
  31965. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31966. }
  31967. setup( builder ) {
  31968. super.setup( builder );
  31969. const lightingModel = builder.context.lightingModel;
  31970. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31971. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31972. const lightDirection = lVector.normalize();
  31973. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31974. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31975. const lightDistance = lVector.length();
  31976. const lightAttenuation = getDistanceAttenuation( {
  31977. lightDistance,
  31978. cutoffDistance: cutoffDistanceNode,
  31979. decayExponent: decayExponentNode
  31980. } );
  31981. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31982. if ( light.map ) {
  31983. const spotLightCoord = lightProjectionUV( light );
  31984. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31985. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31986. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31987. }
  31988. const reflectedLight = builder.context.reflectedLight;
  31989. lightingModel.direct( {
  31990. lightDirection,
  31991. lightColor,
  31992. reflectedLight
  31993. }, builder.stack, builder );
  31994. }
  31995. }
  31996. /**
  31997. * An IES version of the default spot light node.
  31998. *
  31999. * @augments SpotLightNode
  32000. */
  32001. class IESSpotLightNode extends SpotLightNode {
  32002. static get type() {
  32003. return 'IESSpotLightNode';
  32004. }
  32005. /**
  32006. * Overwrites the default implementation to compute an IES conform spot attenuation.
  32007. *
  32008. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32009. * @return {Node<float>} The spot attenuation.
  32010. */
  32011. getSpotAttenuation( angleCosine ) {
  32012. const iesMap = this.light.iesMap;
  32013. let spotAttenuation = null;
  32014. if ( iesMap && iesMap.isTexture === true ) {
  32015. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32016. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32017. } else {
  32018. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32019. }
  32020. return spotAttenuation;
  32021. }
  32022. }
  32023. /**
  32024. * Module for representing ambient lights as nodes.
  32025. *
  32026. * @augments AnalyticLightNode
  32027. */
  32028. class AmbientLightNode extends AnalyticLightNode {
  32029. static get type() {
  32030. return 'AmbientLightNode';
  32031. }
  32032. /**
  32033. * Constructs a new ambient light node.
  32034. *
  32035. * @param {AmbientLight?} [light=null] - The ambient light source.
  32036. */
  32037. constructor( light = null ) {
  32038. super( light );
  32039. }
  32040. setup( { context } ) {
  32041. context.irradiance.addAssign( this.colorNode );
  32042. }
  32043. }
  32044. /**
  32045. * Module for representing hemisphere lights as nodes.
  32046. *
  32047. * @augments AnalyticLightNode
  32048. */
  32049. class HemisphereLightNode extends AnalyticLightNode {
  32050. static get type() {
  32051. return 'HemisphereLightNode';
  32052. }
  32053. /**
  32054. * Constructs a new hemisphere light node.
  32055. *
  32056. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  32057. */
  32058. constructor( light = null ) {
  32059. super( light );
  32060. /**
  32061. * Uniform node representing the light's position.
  32062. *
  32063. * @type {UniformNode<vec3>}
  32064. */
  32065. this.lightPositionNode = lightPosition( light );
  32066. /**
  32067. * A node representing the light's direction.
  32068. *
  32069. * @type {Node<vec3>}
  32070. */
  32071. this.lightDirectionNode = this.lightPositionNode.normalize();
  32072. /**
  32073. * Uniform node representing the light's ground color.
  32074. *
  32075. * @type {UniformNode<vec3>}
  32076. */
  32077. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  32078. }
  32079. /**
  32080. * Overwritten to updated hemisphere light specific uniforms.
  32081. *
  32082. * @param {NodeFrame} frame - A reference to the current node frame.
  32083. */
  32084. update( frame ) {
  32085. const { light } = this;
  32086. super.update( frame );
  32087. this.lightPositionNode.object3d = light;
  32088. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32089. }
  32090. setup( builder ) {
  32091. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32092. const dotNL = normalView.dot( lightDirectionNode );
  32093. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32094. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32095. builder.context.irradiance.addAssign( irradiance );
  32096. }
  32097. }
  32098. /**
  32099. * Module for representing light probes as nodes.
  32100. *
  32101. * @augments AnalyticLightNode
  32102. */
  32103. class LightProbeNode extends AnalyticLightNode {
  32104. static get type() {
  32105. return 'LightProbeNode';
  32106. }
  32107. /**
  32108. * Constructs a new light probe node.
  32109. *
  32110. * @param {LightProbe?} [light=null] - The light probe.
  32111. */
  32112. constructor( light = null ) {
  32113. super( light );
  32114. const array = [];
  32115. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  32116. /**
  32117. * Light probe represented as a uniform of spherical harmonics.
  32118. *
  32119. * @type {UniformArrayNode}
  32120. */
  32121. this.lightProbe = uniformArray( array );
  32122. }
  32123. /**
  32124. * Overwritten to updated light probe specific uniforms.
  32125. *
  32126. * @param {NodeFrame} frame - A reference to the current node frame.
  32127. */
  32128. update( frame ) {
  32129. const { light } = this;
  32130. super.update( frame );
  32131. //
  32132. for ( let i = 0; i < 9; i ++ ) {
  32133. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  32134. }
  32135. }
  32136. setup( builder ) {
  32137. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  32138. builder.context.irradiance.addAssign( irradiance );
  32139. }
  32140. }
  32141. /**
  32142. * Base class for node parsers. A derived parser must be implemented
  32143. * for each supported native shader language.
  32144. */
  32145. class NodeParser {
  32146. /**
  32147. * The method parses the given native code an returns a node function.
  32148. *
  32149. * @abstract
  32150. * @param {String} source - The native shader code.
  32151. * @return {NodeFunction} A node function.
  32152. */
  32153. parseFunction( /*source*/ ) {
  32154. console.warn( 'Abstract function.' );
  32155. }
  32156. }
  32157. /**
  32158. * Base class for node functions. A derived module must be implemented
  32159. * for each supported native shader language. Similar to other `Node*` modules,
  32160. * this class is only relevant during the building process and not used
  32161. * in user-level code.
  32162. */
  32163. class NodeFunction {
  32164. /**
  32165. * Constructs a new node function.
  32166. *
  32167. * @param {String} type - The node type. This type is the return type of the node function.
  32168. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  32169. * @param {String} [name=''] - The function's name.
  32170. * @param {String} [precision=''] - The precision qualifier.
  32171. */
  32172. constructor( type, inputs, name = '', precision = '' ) {
  32173. /**
  32174. * The node type. This type is the return type of the node function.
  32175. *
  32176. * @type {String}
  32177. */
  32178. this.type = type;
  32179. /**
  32180. * The function's inputs.
  32181. *
  32182. * @type {Array<NodeFunctionInput>}
  32183. */
  32184. this.inputs = inputs;
  32185. /**
  32186. * The name of the uniform.
  32187. *
  32188. * @type {String}
  32189. * @default ''
  32190. */
  32191. this.name = name;
  32192. /**
  32193. * The precision qualifier.
  32194. *
  32195. * @type {String}
  32196. * @default ''
  32197. */
  32198. this.precision = precision;
  32199. }
  32200. /**
  32201. * This method returns the native code of the node function.
  32202. *
  32203. * @abstract
  32204. * @param {String} name - The function's name.
  32205. * @return {String} A shader code.
  32206. */
  32207. getCode( /*name = this.name*/ ) {
  32208. console.warn( 'Abstract function.' );
  32209. }
  32210. }
  32211. NodeFunction.isNodeFunction = true;
  32212. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  32213. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  32214. const pragmaMain = '#pragma main';
  32215. const parse$1 = ( source ) => {
  32216. source = source.trim();
  32217. const pragmaMainIndex = source.indexOf( pragmaMain );
  32218. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  32219. const declaration = mainCode.match( declarationRegexp$1 );
  32220. if ( declaration !== null && declaration.length === 5 ) {
  32221. // tokenizer
  32222. const inputsCode = declaration[ 4 ];
  32223. const propsMatches = [];
  32224. let nameMatch = null;
  32225. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  32226. propsMatches.push( nameMatch );
  32227. }
  32228. // parser
  32229. const inputs = [];
  32230. let i = 0;
  32231. while ( i < propsMatches.length ) {
  32232. const isConst = propsMatches[ i ][ 0 ] === 'const';
  32233. if ( isConst === true ) {
  32234. i ++;
  32235. }
  32236. let qualifier = propsMatches[ i ][ 0 ];
  32237. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  32238. i ++;
  32239. } else {
  32240. qualifier = '';
  32241. }
  32242. const type = propsMatches[ i ++ ][ 0 ];
  32243. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  32244. if ( Number.isNaN( count ) === false ) i ++;
  32245. else count = null;
  32246. const name = propsMatches[ i ++ ][ 0 ];
  32247. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  32248. }
  32249. //
  32250. const blockCode = mainCode.substring( declaration[ 0 ].length );
  32251. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  32252. const type = declaration[ 2 ];
  32253. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  32254. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  32255. return {
  32256. type,
  32257. inputs,
  32258. name,
  32259. precision,
  32260. inputsCode,
  32261. blockCode,
  32262. headerCode
  32263. };
  32264. } else {
  32265. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  32266. }
  32267. };
  32268. /**
  32269. * This class represents a GLSL node function.
  32270. *
  32271. * @augments NodeFunction
  32272. */
  32273. class GLSLNodeFunction extends NodeFunction {
  32274. /**
  32275. * Constructs a new GLSL node function.
  32276. *
  32277. * @param {String} source - The GLSL source.
  32278. */
  32279. constructor( source ) {
  32280. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32281. super( type, inputs, name, precision );
  32282. this.inputsCode = inputsCode;
  32283. this.blockCode = blockCode;
  32284. this.headerCode = headerCode;
  32285. }
  32286. /**
  32287. * This method returns the GLSL code of the node function.
  32288. *
  32289. * @param {String} [name=this.name] - The function's name.
  32290. * @return {String} The shader code.
  32291. */
  32292. getCode( name = this.name ) {
  32293. let code;
  32294. const blockCode = this.blockCode;
  32295. if ( blockCode !== '' ) {
  32296. const { type, inputsCode, headerCode, precision } = this;
  32297. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32298. if ( precision !== '' ) {
  32299. declarationCode = `${ precision } ${ declarationCode }`;
  32300. }
  32301. code = headerCode + declarationCode + blockCode;
  32302. } else {
  32303. // interface function
  32304. code = '';
  32305. }
  32306. return code;
  32307. }
  32308. }
  32309. /**
  32310. * A GLSL node parser.
  32311. *
  32312. * @augments NodeParser
  32313. */
  32314. class GLSLNodeParser extends NodeParser {
  32315. /**
  32316. * The method parses the given GLSL code an returns a node function.
  32317. *
  32318. * @param {String} source - The GLSL code.
  32319. * @return {GLSLNodeFunction} A node function.
  32320. */
  32321. parseFunction( source ) {
  32322. return new GLSLNodeFunction( source );
  32323. }
  32324. }
  32325. const _outputNodeMap = new WeakMap();
  32326. const _chainKeys$2 = [];
  32327. const _cacheKeyValues = [];
  32328. /**
  32329. * This renderer module manages node-related objects and is the
  32330. * primary interface between the renderer and the node system.
  32331. *
  32332. * @private
  32333. * @augments DataMap
  32334. */
  32335. class Nodes extends DataMap {
  32336. /**
  32337. * Constructs a new nodes management component.
  32338. *
  32339. * @param {Renderer} renderer - The renderer.
  32340. * @param {Backend} backend - The renderer's backend.
  32341. */
  32342. constructor( renderer, backend ) {
  32343. super();
  32344. /**
  32345. * The renderer.
  32346. *
  32347. * @type {Renderer}
  32348. */
  32349. this.renderer = renderer;
  32350. /**
  32351. * The renderer's backend.
  32352. *
  32353. * @type {Backend}
  32354. */
  32355. this.backend = backend;
  32356. /**
  32357. * The node frame.
  32358. *
  32359. * @type {Renderer}
  32360. */
  32361. this.nodeFrame = new NodeFrame();
  32362. /**
  32363. * A cache for managing node builder states.
  32364. *
  32365. * @type {Map<Number,NodeBuilderState>}
  32366. */
  32367. this.nodeBuilderCache = new Map();
  32368. /**
  32369. * A cache for managing data cache key data.
  32370. *
  32371. * @type {ChainMap}
  32372. */
  32373. this.callHashCache = new ChainMap();
  32374. /**
  32375. * A cache for managing node uniforms group data.
  32376. *
  32377. * @type {ChainMap}
  32378. */
  32379. this.groupsData = new ChainMap();
  32380. /**
  32381. * A cache for managing node objects of
  32382. * scene properties like fog or environments.
  32383. *
  32384. * @type {Object<String,WeakMap>}
  32385. */
  32386. this.cacheLib = {};
  32387. }
  32388. /**
  32389. * Returns `true` if the given node uniforms group must be updated or not.
  32390. *
  32391. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  32392. * @return {Boolean} Whether the node uniforms group requires an update or not.
  32393. */
  32394. updateGroup( nodeUniformsGroup ) {
  32395. const groupNode = nodeUniformsGroup.groupNode;
  32396. const name = groupNode.name;
  32397. // objectGroup is always updated
  32398. if ( name === objectGroup.name ) return true;
  32399. // renderGroup is updated once per render/compute call
  32400. if ( name === renderGroup.name ) {
  32401. const uniformsGroupData = this.get( nodeUniformsGroup );
  32402. const renderId = this.nodeFrame.renderId;
  32403. if ( uniformsGroupData.renderId !== renderId ) {
  32404. uniformsGroupData.renderId = renderId;
  32405. return true;
  32406. }
  32407. return false;
  32408. }
  32409. // frameGroup is updated once per frame
  32410. if ( name === frameGroup.name ) {
  32411. const uniformsGroupData = this.get( nodeUniformsGroup );
  32412. const frameId = this.nodeFrame.frameId;
  32413. if ( uniformsGroupData.frameId !== frameId ) {
  32414. uniformsGroupData.frameId = frameId;
  32415. return true;
  32416. }
  32417. return false;
  32418. }
  32419. // other groups are updated just when groupNode.needsUpdate is true
  32420. _chainKeys$2[ 0 ] = groupNode;
  32421. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  32422. let groupData = this.groupsData.get( _chainKeys$2 );
  32423. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  32424. _chainKeys$2.length = 0;
  32425. if ( groupData.version !== groupNode.version ) {
  32426. groupData.version = groupNode.version;
  32427. return true;
  32428. }
  32429. return false;
  32430. }
  32431. /**
  32432. * Returns the cache key for the given render object.
  32433. *
  32434. * @param {RenderObject} renderObject - The render object.
  32435. * @return {Number} The cache key.
  32436. */
  32437. getForRenderCacheKey( renderObject ) {
  32438. return renderObject.initialCacheKey;
  32439. }
  32440. /**
  32441. * Returns a node builder state for the given render object.
  32442. *
  32443. * @param {RenderObject} renderObject - The render object.
  32444. * @return {NodeBuilderState} The node builder state.
  32445. */
  32446. getForRender( renderObject ) {
  32447. const renderObjectData = this.get( renderObject );
  32448. let nodeBuilderState = renderObjectData.nodeBuilderState;
  32449. if ( nodeBuilderState === undefined ) {
  32450. const { nodeBuilderCache } = this;
  32451. const cacheKey = this.getForRenderCacheKey( renderObject );
  32452. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  32453. if ( nodeBuilderState === undefined ) {
  32454. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  32455. nodeBuilder.scene = renderObject.scene;
  32456. nodeBuilder.material = renderObject.material;
  32457. nodeBuilder.camera = renderObject.camera;
  32458. nodeBuilder.context.material = renderObject.material;
  32459. nodeBuilder.lightsNode = renderObject.lightsNode;
  32460. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  32461. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  32462. nodeBuilder.clippingContext = renderObject.clippingContext;
  32463. nodeBuilder.build();
  32464. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32465. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  32466. }
  32467. nodeBuilderState.usedTimes ++;
  32468. renderObjectData.nodeBuilderState = nodeBuilderState;
  32469. }
  32470. return nodeBuilderState;
  32471. }
  32472. /**
  32473. * Deletes the given object from the internal data map
  32474. *
  32475. * @param {Any} object - The object to delete.
  32476. * @return {Object?} The deleted dictionary.
  32477. */
  32478. delete( object ) {
  32479. if ( object.isRenderObject ) {
  32480. const nodeBuilderState = this.get( object ).nodeBuilderState;
  32481. nodeBuilderState.usedTimes --;
  32482. if ( nodeBuilderState.usedTimes === 0 ) {
  32483. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  32484. }
  32485. }
  32486. return super.delete( object );
  32487. }
  32488. /**
  32489. * Returns a node builder state for the given compute node.
  32490. *
  32491. * @param {Node} computeNode - The compute node.
  32492. * @return {NodeBuilderState} The node builder state.
  32493. */
  32494. getForCompute( computeNode ) {
  32495. const computeData = this.get( computeNode );
  32496. let nodeBuilderState = computeData.nodeBuilderState;
  32497. if ( nodeBuilderState === undefined ) {
  32498. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  32499. nodeBuilder.build();
  32500. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32501. computeData.nodeBuilderState = nodeBuilderState;
  32502. }
  32503. return nodeBuilderState;
  32504. }
  32505. /**
  32506. * Creates a node builder state for the given node builder.
  32507. *
  32508. * @private
  32509. * @param {NodeBuilder} nodeBuilder - The node builder.
  32510. * @return {NodeBuilderState} The node builder state.
  32511. */
  32512. _createNodeBuilderState( nodeBuilder ) {
  32513. return new NodeBuilderState(
  32514. nodeBuilder.vertexShader,
  32515. nodeBuilder.fragmentShader,
  32516. nodeBuilder.computeShader,
  32517. nodeBuilder.getAttributesArray(),
  32518. nodeBuilder.getBindings(),
  32519. nodeBuilder.updateNodes,
  32520. nodeBuilder.updateBeforeNodes,
  32521. nodeBuilder.updateAfterNodes,
  32522. nodeBuilder.observer,
  32523. nodeBuilder.transforms
  32524. );
  32525. }
  32526. /**
  32527. * Returns an environment node for the current configured
  32528. * scene environment.
  32529. *
  32530. * @param {Scene} scene - The scene.
  32531. * @return {Node} A node representing the current scene environment.
  32532. */
  32533. getEnvironmentNode( scene ) {
  32534. this.updateEnvironment( scene );
  32535. let environmentNode = null;
  32536. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  32537. environmentNode = scene.environmentNode;
  32538. } else {
  32539. const sceneData = this.get( scene );
  32540. if ( sceneData.environmentNode ) {
  32541. environmentNode = sceneData.environmentNode;
  32542. }
  32543. }
  32544. return environmentNode;
  32545. }
  32546. /**
  32547. * Returns a background node for the current configured
  32548. * scene background.
  32549. *
  32550. * @param {Scene} scene - The scene.
  32551. * @return {Node} A node representing the current scene background.
  32552. */
  32553. getBackgroundNode( scene ) {
  32554. this.updateBackground( scene );
  32555. let backgroundNode = null;
  32556. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  32557. backgroundNode = scene.backgroundNode;
  32558. } else {
  32559. const sceneData = this.get( scene );
  32560. if ( sceneData.backgroundNode ) {
  32561. backgroundNode = sceneData.backgroundNode;
  32562. }
  32563. }
  32564. return backgroundNode;
  32565. }
  32566. /**
  32567. * Returns a fog node for the current configured scene fog.
  32568. *
  32569. * @param {Scene} scene - The scene.
  32570. * @return {Node} A node representing the current scene fog.
  32571. */
  32572. getFogNode( scene ) {
  32573. this.updateFog( scene );
  32574. return scene.fogNode || this.get( scene ).fogNode || null;
  32575. }
  32576. /**
  32577. * Returns a cache key for the given scene and lights node.
  32578. * This key is used by `RenderObject` as a part of the dynamic
  32579. * cache key (a key that must be checked every time the render
  32580. * objects is drawn).
  32581. *
  32582. * @param {Scene} scene - The scene.
  32583. * @param {LightsNode} lightsNode - The lights node.
  32584. * @return {Number} The cache key.
  32585. */
  32586. getCacheKey( scene, lightsNode ) {
  32587. _chainKeys$2[ 0 ] = scene;
  32588. _chainKeys$2[ 1 ] = lightsNode;
  32589. const callId = this.renderer.info.calls;
  32590. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  32591. if ( cacheKeyData.callId !== callId ) {
  32592. const environmentNode = this.getEnvironmentNode( scene );
  32593. const fogNode = this.getFogNode( scene );
  32594. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  32595. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  32596. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  32597. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  32598. cacheKeyData.callId = callId;
  32599. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  32600. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  32601. _cacheKeyValues.length = 0;
  32602. }
  32603. _chainKeys$2.length = 0;
  32604. return cacheKeyData.cacheKey;
  32605. }
  32606. /**
  32607. * A boolean that indicates whether tone mapping should be enabled
  32608. * or not.
  32609. *
  32610. * @type {Boolean}
  32611. */
  32612. get isToneMappingState() {
  32613. return this.renderer.getRenderTarget() ? false : true;
  32614. }
  32615. /**
  32616. * If a scene background is configured, this method makes sure to
  32617. * represent the background with a corresponding node-based implementation.
  32618. *
  32619. * @param {Scene} scene - The scene.
  32620. */
  32621. updateBackground( scene ) {
  32622. const sceneData = this.get( scene );
  32623. const background = scene.background;
  32624. if ( background ) {
  32625. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  32626. if ( sceneData.background !== background || forceUpdate ) {
  32627. const backgroundNode = this.getCacheNode( 'background', background, () => {
  32628. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  32629. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  32630. return pmremTexture( background );
  32631. } else {
  32632. let envMap;
  32633. if ( background.isCubeTexture === true ) {
  32634. envMap = cubeTexture( background );
  32635. } else {
  32636. envMap = texture( background );
  32637. }
  32638. return cubeMapNode( envMap );
  32639. }
  32640. } else if ( background.isTexture === true ) {
  32641. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  32642. } else if ( background.isColor !== true ) {
  32643. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  32644. }
  32645. }, forceUpdate );
  32646. sceneData.backgroundNode = backgroundNode;
  32647. sceneData.background = background;
  32648. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  32649. }
  32650. } else if ( sceneData.backgroundNode ) {
  32651. delete sceneData.backgroundNode;
  32652. delete sceneData.background;
  32653. }
  32654. }
  32655. /**
  32656. * This method is part of the caching of nodes which are used to represents the
  32657. * scene's background, fog or environment.
  32658. *
  32659. * @param {String} type - The type of object to cache.
  32660. * @param {Object} object - The object.
  32661. * @param {Function} callback - A callback that produces a node representation for the given object.
  32662. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  32663. * @return {Node} The node representation.
  32664. */
  32665. getCacheNode( type, object, callback, forceUpdate = false ) {
  32666. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  32667. let node = nodeCache.get( object );
  32668. if ( node === undefined || forceUpdate ) {
  32669. node = callback();
  32670. nodeCache.set( object, node );
  32671. }
  32672. return node;
  32673. }
  32674. /**
  32675. * If a scene fog is configured, this method makes sure to
  32676. * represent the fog with a corresponding node-based implementation.
  32677. *
  32678. * @param {Scene} scene - The scene.
  32679. */
  32680. updateFog( scene ) {
  32681. const sceneData = this.get( scene );
  32682. const sceneFog = scene.fog;
  32683. if ( sceneFog ) {
  32684. if ( sceneData.fog !== sceneFog ) {
  32685. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  32686. if ( sceneFog.isFogExp2 ) {
  32687. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32688. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  32689. return fog( color, densityFogFactor( density ) );
  32690. } else if ( sceneFog.isFog ) {
  32691. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32692. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  32693. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  32694. return fog( color, rangeFogFactor( near, far ) );
  32695. } else {
  32696. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32697. }
  32698. } );
  32699. sceneData.fogNode = fogNode;
  32700. sceneData.fog = sceneFog;
  32701. }
  32702. } else {
  32703. delete sceneData.fogNode;
  32704. delete sceneData.fog;
  32705. }
  32706. }
  32707. /**
  32708. * If a scene environment is configured, this method makes sure to
  32709. * represent the environment with a corresponding node-based implementation.
  32710. *
  32711. * @param {Scene} scene - The scene.
  32712. */
  32713. updateEnvironment( scene ) {
  32714. const sceneData = this.get( scene );
  32715. const environment = scene.environment;
  32716. if ( environment ) {
  32717. if ( sceneData.environment !== environment ) {
  32718. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32719. if ( environment.isCubeTexture === true ) {
  32720. return cubeTexture( environment );
  32721. } else if ( environment.isTexture === true ) {
  32722. return texture( environment );
  32723. } else {
  32724. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32725. }
  32726. } );
  32727. sceneData.environmentNode = environmentNode;
  32728. sceneData.environment = environment;
  32729. }
  32730. } else if ( sceneData.environmentNode ) {
  32731. delete sceneData.environmentNode;
  32732. delete sceneData.environment;
  32733. }
  32734. }
  32735. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32736. const nodeFrame = this.nodeFrame;
  32737. nodeFrame.renderer = renderer;
  32738. nodeFrame.scene = scene;
  32739. nodeFrame.object = object;
  32740. nodeFrame.camera = camera;
  32741. nodeFrame.material = material;
  32742. return nodeFrame;
  32743. }
  32744. getNodeFrameForRender( renderObject ) {
  32745. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32746. }
  32747. /**
  32748. * Returns the current output cache key.
  32749. *
  32750. * @return {String} The output cache key.
  32751. */
  32752. getOutputCacheKey() {
  32753. const renderer = this.renderer;
  32754. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32755. }
  32756. /**
  32757. * Checks if the output configuration (tone mapping and color space) for
  32758. * the given target has changed.
  32759. *
  32760. * @param {Texture} outputTarget - The output target.
  32761. * @return {Boolean} Whether the output configuration has changed or not.
  32762. */
  32763. hasOutputChange( outputTarget ) {
  32764. const cacheKey = _outputNodeMap.get( outputTarget );
  32765. return cacheKey !== this.getOutputCacheKey();
  32766. }
  32767. /**
  32768. * Returns a node that represents the output configuration (tone mapping and
  32769. * color space) for the current target.
  32770. *
  32771. * @param {Texture} outputTarget - The output target.
  32772. * @return {Node} The output node.
  32773. */
  32774. getOutputNode( outputTarget ) {
  32775. const renderer = this.renderer;
  32776. const cacheKey = this.getOutputCacheKey();
  32777. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32778. _outputNodeMap.set( outputTarget, cacheKey );
  32779. return output;
  32780. }
  32781. /**
  32782. * Triggers the call of `updateBefore()` methods
  32783. * for all nodes of the given render object.
  32784. *
  32785. * @param {RenderObject} renderObject - The render object.
  32786. */
  32787. updateBefore( renderObject ) {
  32788. const nodeBuilder = renderObject.getNodeBuilderState();
  32789. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32790. // update frame state for each node
  32791. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32792. }
  32793. }
  32794. /**
  32795. * Triggers the call of `updateAfter()` methods
  32796. * for all nodes of the given render object.
  32797. *
  32798. * @param {RenderObject} renderObject - The render object.
  32799. */
  32800. updateAfter( renderObject ) {
  32801. const nodeBuilder = renderObject.getNodeBuilderState();
  32802. for ( const node of nodeBuilder.updateAfterNodes ) {
  32803. // update frame state for each node
  32804. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32805. }
  32806. }
  32807. /**
  32808. * Triggers the call of `update()` methods
  32809. * for all nodes of the given compute node.
  32810. *
  32811. * @param {Node} computeNode - The compute node.
  32812. */
  32813. updateForCompute( computeNode ) {
  32814. const nodeFrame = this.getNodeFrame();
  32815. const nodeBuilder = this.getForCompute( computeNode );
  32816. for ( const node of nodeBuilder.updateNodes ) {
  32817. nodeFrame.updateNode( node );
  32818. }
  32819. }
  32820. /**
  32821. * Triggers the call of `update()` methods
  32822. * for all nodes of the given compute node.
  32823. *
  32824. * @param {RenderObject} renderObject - The render object.
  32825. */
  32826. updateForRender( renderObject ) {
  32827. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32828. const nodeBuilder = renderObject.getNodeBuilderState();
  32829. for ( const node of nodeBuilder.updateNodes ) {
  32830. nodeFrame.updateNode( node );
  32831. }
  32832. }
  32833. /**
  32834. * Returns `true` if the given render object requires a refresh.
  32835. *
  32836. * @param {RenderObject} renderObject - The render object.
  32837. * @return {Boolean} Whether the given render object requires a refresh or not.
  32838. */
  32839. needsRefresh( renderObject ) {
  32840. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32841. const monitor = renderObject.getMonitor();
  32842. return monitor.needsRefresh( renderObject, nodeFrame );
  32843. }
  32844. /**
  32845. * Frees the internal resources.
  32846. */
  32847. dispose() {
  32848. super.dispose();
  32849. this.nodeFrame = new NodeFrame();
  32850. this.nodeBuilderCache = new Map();
  32851. this.cacheLib = {};
  32852. }
  32853. }
  32854. const _plane = /*@__PURE__*/ new Plane();
  32855. /**
  32856. * Represents the state that is used to perform clipping via clipping planes.
  32857. * There is a default clipping context for each render context. When the
  32858. * scene holds instances of `ClippingGroup`, there will be a context for each
  32859. * group.
  32860. *
  32861. * @private
  32862. */
  32863. class ClippingContext {
  32864. /**
  32865. * Constructs a new clipping context.
  32866. *
  32867. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32868. */
  32869. constructor( parentContext = null ) {
  32870. /**
  32871. * The clipping context's version.
  32872. *
  32873. * @type {Number}
  32874. * @readonly
  32875. */
  32876. this.version = 0;
  32877. /**
  32878. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32879. *
  32880. * @type {Boolean?}
  32881. * @default null
  32882. */
  32883. this.clipIntersection = null;
  32884. /**
  32885. * The clipping context's cache key.
  32886. *
  32887. * @type {String}
  32888. */
  32889. this.cacheKey = '';
  32890. /**
  32891. * Whether the shadow pass is active or not.
  32892. *
  32893. * @type {Boolean}
  32894. * @default false
  32895. */
  32896. this.shadowPass = false;
  32897. /**
  32898. * The view normal matrix.
  32899. *
  32900. * @type {Matrix3}
  32901. */
  32902. this.viewNormalMatrix = new Matrix3();
  32903. /**
  32904. * Internal cache for maintaining clipping contexts.
  32905. *
  32906. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32907. */
  32908. this.clippingGroupContexts = new WeakMap();
  32909. /**
  32910. * The intersection planes.
  32911. *
  32912. * @type {Array<Vector4>}
  32913. */
  32914. this.intersectionPlanes = [];
  32915. /**
  32916. * The intersection planes.
  32917. *
  32918. * @type {Array<Vector4>}
  32919. */
  32920. this.unionPlanes = [];
  32921. /**
  32922. * The version of the clipping context's parent context.
  32923. *
  32924. * @type {Number?}
  32925. * @readonly
  32926. */
  32927. this.parentVersion = null;
  32928. if ( parentContext !== null ) {
  32929. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32930. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32931. this.shadowPass = parentContext.shadowPass;
  32932. this.viewMatrix = parentContext.viewMatrix;
  32933. }
  32934. }
  32935. /**
  32936. * Projects the given source clipping planes and writes the result into the
  32937. * destination array.
  32938. *
  32939. * @param {Array<Plane>} source - The source clipping planes.
  32940. * @param {Array<Vector4>} destination - The destination.
  32941. * @param {Number} offset - The offset.
  32942. */
  32943. projectPlanes( source, destination, offset ) {
  32944. const l = source.length;
  32945. for ( let i = 0; i < l; i ++ ) {
  32946. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32947. const v = destination[ offset + i ];
  32948. const normal = _plane.normal;
  32949. v.x = - normal.x;
  32950. v.y = - normal.y;
  32951. v.z = - normal.z;
  32952. v.w = _plane.constant;
  32953. }
  32954. }
  32955. /**
  32956. * Updates the root clipping context of a scene.
  32957. *
  32958. * @param {Scene} scene - The scene.
  32959. * @param {Camera} camera - The camera that is used to render the scene.
  32960. */
  32961. updateGlobal( scene, camera ) {
  32962. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  32963. this.viewMatrix = camera.matrixWorldInverse;
  32964. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32965. }
  32966. /**
  32967. * Updates the clipping context.
  32968. *
  32969. * @param {ClippingContext} parentContext - The parent context.
  32970. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32971. */
  32972. update( parentContext, clippingGroup ) {
  32973. let update = false;
  32974. if ( parentContext.version !== this.parentVersion ) {
  32975. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32976. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32977. this.parentVersion = parentContext.version;
  32978. }
  32979. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32980. this.clipIntersection = clippingGroup.clipIntersection;
  32981. if ( this.clipIntersection ) {
  32982. this.unionPlanes.length = parentContext.unionPlanes.length;
  32983. } else {
  32984. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32985. }
  32986. }
  32987. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32988. const l = srcClippingPlanes.length;
  32989. let dstClippingPlanes;
  32990. let offset;
  32991. if ( this.clipIntersection ) {
  32992. dstClippingPlanes = this.intersectionPlanes;
  32993. offset = parentContext.intersectionPlanes.length;
  32994. } else {
  32995. dstClippingPlanes = this.unionPlanes;
  32996. offset = parentContext.unionPlanes.length;
  32997. }
  32998. if ( dstClippingPlanes.length !== offset + l ) {
  32999. dstClippingPlanes.length = offset + l;
  33000. for ( let i = 0; i < l; i ++ ) {
  33001. dstClippingPlanes[ offset + i ] = new Vector4();
  33002. }
  33003. update = true;
  33004. }
  33005. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  33006. if ( update ) {
  33007. this.version ++;
  33008. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  33009. }
  33010. }
  33011. /**
  33012. * Returns a clipping context for the given clipping group.
  33013. *
  33014. * @param {ClippingGroup} clippingGroup - The clipping group.
  33015. * @return {ClippingContext} The clipping context.
  33016. */
  33017. getGroupContext( clippingGroup ) {
  33018. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  33019. let context = this.clippingGroupContexts.get( clippingGroup );
  33020. if ( context === undefined ) {
  33021. context = new ClippingContext( this );
  33022. this.clippingGroupContexts.set( clippingGroup, context );
  33023. }
  33024. context.update( this, clippingGroup );
  33025. return context;
  33026. }
  33027. /**
  33028. * The count of union clipping planes.
  33029. *
  33030. * @type {Number}
  33031. * @readonly
  33032. */
  33033. get unionClippingCount() {
  33034. return this.unionPlanes.length;
  33035. }
  33036. }
  33037. /**
  33038. * This module is used to represent render bundles inside the renderer
  33039. * for further processing.
  33040. *
  33041. * @private
  33042. */
  33043. class RenderBundle {
  33044. /**
  33045. * Constructs a new bundle group.
  33046. *
  33047. * @param {BundleGroup} bundleGroup - The bundle group.
  33048. * @param {Camera} camera - The camera the bundle group is rendered with.
  33049. */
  33050. constructor( bundleGroup, camera ) {
  33051. this.bundleGroup = bundleGroup;
  33052. this.camera = camera;
  33053. }
  33054. }
  33055. const _chainKeys$1 = [];
  33056. /**
  33057. * This renderer module manages render bundles.
  33058. *
  33059. * @private
  33060. */
  33061. class RenderBundles {
  33062. /**
  33063. * Constructs a new render bundle management component.
  33064. */
  33065. constructor() {
  33066. /**
  33067. * A chain map for maintaining the render bundles.
  33068. *
  33069. * @type {ChainMap}
  33070. */
  33071. this.bundles = new ChainMap();
  33072. }
  33073. /**
  33074. * Returns a render bundle for the given bundle group and camera.
  33075. *
  33076. * @param {BundleGroup} bundleGroup - The bundle group.
  33077. * @param {Camera} camera - The camera the bundle group is rendered with.
  33078. * @return {RenderBundle} The render bundle.
  33079. */
  33080. get( bundleGroup, camera ) {
  33081. const bundles = this.bundles;
  33082. _chainKeys$1[ 0 ] = bundleGroup;
  33083. _chainKeys$1[ 1 ] = camera;
  33084. let bundle = bundles.get( _chainKeys$1 );
  33085. if ( bundle === undefined ) {
  33086. bundle = new RenderBundle( bundleGroup, camera );
  33087. bundles.set( _chainKeys$1, bundle );
  33088. }
  33089. _chainKeys$1.length = 0;
  33090. return bundle;
  33091. }
  33092. /**
  33093. * Frees all internal resources.
  33094. */
  33095. dispose() {
  33096. this.bundles = new ChainMap();
  33097. }
  33098. }
  33099. /**
  33100. * The purpose of a node library is to assign node implementations
  33101. * to existing library features. In `WebGPURenderer` lights, materials
  33102. * which are not based on `NodeMaterial` as well as tone mapping techniques
  33103. * are implemented with node-based modules.
  33104. *
  33105. * @private
  33106. */
  33107. class NodeLibrary {
  33108. /**
  33109. * Constructs a new node library.
  33110. */
  33111. constructor() {
  33112. /**
  33113. * A weak map that maps lights to light nodes.
  33114. *
  33115. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  33116. */
  33117. this.lightNodes = new WeakMap();
  33118. /**
  33119. * A map that maps materials to node materials.
  33120. *
  33121. * @type {Map<String,NodeMaterial.constructor>}
  33122. */
  33123. this.materialNodes = new Map();
  33124. /**
  33125. * A map that maps tone mapping techniques (constants)
  33126. * to tone mapping node functions.
  33127. *
  33128. * @type {Map<Number,Function>}
  33129. */
  33130. this.toneMappingNodes = new Map();
  33131. }
  33132. /**
  33133. * Returns a matching node material instance for the given material object.
  33134. *
  33135. * This method also assigns/copies the properties of the given material object
  33136. * to the node material. This is done to make sure the current material
  33137. * configuration carries over to the node version.
  33138. *
  33139. * @param {Material} material - A material.
  33140. * @return {NodeMaterial} The corresponding node material.
  33141. */
  33142. fromMaterial( material ) {
  33143. if ( material.isNodeMaterial ) return material;
  33144. let nodeMaterial = null;
  33145. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  33146. if ( nodeMaterialClass !== null ) {
  33147. nodeMaterial = new nodeMaterialClass();
  33148. for ( const key in material ) {
  33149. nodeMaterial[ key ] = material[ key ];
  33150. }
  33151. }
  33152. return nodeMaterial;
  33153. }
  33154. /**
  33155. * Adds a tone mapping node function for a tone mapping technique (constant).
  33156. *
  33157. * @param {Function} toneMappingNode - The tone mapping node function.
  33158. * @param {Number} toneMapping - The tone mapping.
  33159. */
  33160. addToneMapping( toneMappingNode, toneMapping ) {
  33161. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  33162. }
  33163. /**
  33164. * Returns a tone mapping node function for a tone mapping technique (constant).
  33165. *
  33166. * @param {Number} toneMapping - The tone mapping.
  33167. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  33168. */
  33169. getToneMappingFunction( toneMapping ) {
  33170. return this.toneMappingNodes.get( toneMapping ) || null;
  33171. }
  33172. /**
  33173. * Returns a node material class definition for a material type.
  33174. *
  33175. * @param {String} materialType - The material type.
  33176. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  33177. */
  33178. getMaterialNodeClass( materialType ) {
  33179. return this.materialNodes.get( materialType ) || null;
  33180. }
  33181. /**
  33182. * Adds a node material class definition for a given material type.
  33183. *
  33184. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  33185. * @param {String} materialClassType - The material type.
  33186. */
  33187. addMaterial( materialNodeClass, materialClassType ) {
  33188. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  33189. }
  33190. /**
  33191. * Returns a light node class definition for a light class definition.
  33192. *
  33193. * @param {Light.constructor} light - The light class definition.
  33194. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  33195. */
  33196. getLightNodeClass( light ) {
  33197. return this.lightNodes.get( light ) || null;
  33198. }
  33199. /**
  33200. * Adds a light node class definition for a given light class definition.
  33201. *
  33202. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  33203. * @param {Light.constructor} lightClass - The light class definition.
  33204. */
  33205. addLight( lightNodeClass, lightClass ) {
  33206. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  33207. }
  33208. /**
  33209. * Adds a node class definition for the given type to the provided type library.
  33210. *
  33211. * @param {Any} nodeClass - The node class definition.
  33212. * @param {Number|String} type - The object type.
  33213. * @param {Map} library - The type library.
  33214. */
  33215. addType( nodeClass, type, library ) {
  33216. if ( library.has( type ) ) {
  33217. console.warn( `Redefinition of node ${ type }` );
  33218. return;
  33219. }
  33220. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33221. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  33222. library.set( type, nodeClass );
  33223. }
  33224. /**
  33225. * Adds a node class definition for the given class definition to the provided type library.
  33226. *
  33227. * @param {Any} nodeClass - The node class definition.
  33228. * @param {Any} baseClass - The class definition.
  33229. * @param {WeakMap} library - The type library.
  33230. */
  33231. addClass( nodeClass, baseClass, library ) {
  33232. if ( library.has( baseClass ) ) {
  33233. console.warn( `Redefinition of node ${ baseClass.name }` );
  33234. return;
  33235. }
  33236. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33237. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  33238. library.set( baseClass, nodeClass );
  33239. }
  33240. }
  33241. const _defaultLights = /*@__PURE__*/ new LightsNode();
  33242. const _chainKeys = [];
  33243. /**
  33244. * This renderer module manages the lights nodes which are unique
  33245. * per scene and camera combination.
  33246. *
  33247. * The lights node itself is later configured in the render list
  33248. * with the actual lights from the scene.
  33249. *
  33250. * @private
  33251. * @augments ChainMap
  33252. */
  33253. class Lighting extends ChainMap {
  33254. /**
  33255. * Constructs a lighting management component.
  33256. */
  33257. constructor() {
  33258. super();
  33259. }
  33260. /**
  33261. * Creates a new lights node for the given array of lights.
  33262. *
  33263. * @param {Array<Light>} lights - The render object.
  33264. * @return {LightsNode} The lights node.
  33265. */
  33266. createNode( lights = [] ) {
  33267. return new LightsNode().setLights( lights );
  33268. }
  33269. /**
  33270. * Returns a lights node for the given scene and camera.
  33271. *
  33272. * @param {Scene} scene - The scene.
  33273. * @param {Camera} camera - The camera.
  33274. * @return {LightsNode} The lights node.
  33275. */
  33276. getNode( scene, camera ) {
  33277. // ignore post-processing
  33278. if ( scene.isQuadMesh ) return _defaultLights;
  33279. _chainKeys[ 0 ] = scene;
  33280. _chainKeys[ 1 ] = camera;
  33281. let node = this.get( _chainKeys );
  33282. if ( node === undefined ) {
  33283. node = this.createNode();
  33284. this.set( _chainKeys, node );
  33285. }
  33286. _chainKeys.length = 0;
  33287. return node;
  33288. }
  33289. }
  33290. /**
  33291. * A special type of render target that is used when rendering
  33292. * with the WebXR Device API.
  33293. *
  33294. * @private
  33295. * @augments RenderTarget
  33296. */
  33297. class XRRenderTarget extends RenderTarget {
  33298. /**
  33299. * Constructs a new XR render target.
  33300. *
  33301. * @param {Number} [width=1] - The width of the render target.
  33302. * @param {Number} [height=1] - The height of the render target.
  33303. * @param {Object} [options={}] - The configuration options.
  33304. */
  33305. constructor( width = 1, height = 1, options = {} ) {
  33306. super( width, height, options );
  33307. /**
  33308. * This flag can be used for type testing.
  33309. *
  33310. * @type {Boolean}
  33311. * @readonly
  33312. * @default true
  33313. */
  33314. this.isXRRenderTarget = true;
  33315. /**
  33316. * Whether the attachments of the render target
  33317. * are defined by external textures. This flag is
  33318. * set to `true` when using the WebXR Layers API.
  33319. *
  33320. * @type {Boolean}
  33321. * @default false
  33322. */
  33323. this.hasExternalTextures = false;
  33324. /**
  33325. * Whether a depth buffer should automatically be allocated
  33326. * for this XR render target or not.
  33327. *
  33328. * Allocating a depth buffer is the default behavior of XR render
  33329. * targets. However, when using the WebXR Layers API, this flag
  33330. * must be set to `false` when the `ignoreDepthValues` property of
  33331. * the projection layers evaluates to `true`.
  33332. *
  33333. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  33334. *
  33335. * @type {Boolean}
  33336. * @default true
  33337. */
  33338. this.autoAllocateDepthBuffer = true;
  33339. }
  33340. copy( source ) {
  33341. super.copy( source );
  33342. this.hasExternalTextures = source.hasExternalTextures;
  33343. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  33344. return this;
  33345. }
  33346. }
  33347. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33348. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33349. /**
  33350. * The XR manager is built on top of the WebXR Device API to
  33351. * manage XR sessions with `WebGPURenderer`.
  33352. *
  33353. * XR is currently only supported with a WebGL 2 backend.
  33354. *
  33355. * @augments EventDispatcher
  33356. */
  33357. class XRManager extends EventDispatcher {
  33358. /**
  33359. * Constructs a new XR manager.
  33360. *
  33361. * @param {Renderer} renderer - The renderer.
  33362. */
  33363. constructor( renderer ) {
  33364. super();
  33365. /**
  33366. * This flag globally enables XR rendering.
  33367. *
  33368. * @type {Boolean}
  33369. * @default false
  33370. */
  33371. this.enabled = false;
  33372. /**
  33373. * Whether the XR device is currently presenting or not.
  33374. *
  33375. * @type {Boolean}
  33376. * @default false
  33377. * @readonly
  33378. */
  33379. this.isPresenting = false;
  33380. /**
  33381. * Whether the XR camera should automatically be updated or not.
  33382. *
  33383. * @type {Boolean}
  33384. * @default true
  33385. */
  33386. this.cameraAutoUpdate = true;
  33387. /**
  33388. * The renderer.
  33389. *
  33390. * @private
  33391. * @type {Renderer}
  33392. */
  33393. this._renderer = renderer;
  33394. // camera
  33395. /**
  33396. * Represents the camera for the left eye.
  33397. *
  33398. * @private
  33399. * @type {PerspectiveCamera}
  33400. */
  33401. this._cameraL = new PerspectiveCamera();
  33402. this._cameraL.viewport = new Vector4();
  33403. /**
  33404. * Represents the camera for the right eye.
  33405. *
  33406. * @private
  33407. * @type {PerspectiveCamera}
  33408. */
  33409. this._cameraR = new PerspectiveCamera();
  33410. this._cameraR.viewport = new Vector4();
  33411. /**
  33412. * A list of cameras used for rendering the XR views.
  33413. *
  33414. * @private
  33415. * @type {Array<Camera>}
  33416. */
  33417. this._cameras = [ this._cameraL, this._cameraR ];
  33418. /**
  33419. * The main XR camera.
  33420. *
  33421. * @private
  33422. * @type {ArrayCamera}
  33423. */
  33424. this._cameraXR = new ArrayCamera();
  33425. /**
  33426. * The current near value of the XR camera.
  33427. *
  33428. * @private
  33429. * @type {Number?}
  33430. * @default null
  33431. */
  33432. this._currentDepthNear = null;
  33433. /**
  33434. * The current far value of the XR camera.
  33435. *
  33436. * @private
  33437. * @type {Number?}
  33438. * @default null
  33439. */
  33440. this._currentDepthFar = null;
  33441. /**
  33442. * A list of WebXR controllers requested by the application.
  33443. *
  33444. * @private
  33445. * @type {Array<WebXRController>}
  33446. */
  33447. this._controllers = [];
  33448. /**
  33449. * A list of XR input source. Each input source belongs to
  33450. * an instance of WebXRController.
  33451. *
  33452. * @private
  33453. * @type {Array<XRInputSource?>}
  33454. */
  33455. this._controllerInputSources = [];
  33456. /**
  33457. * The current render target of the renderer.
  33458. *
  33459. * @private
  33460. * @type {RenderTarget?}
  33461. * @default null
  33462. */
  33463. this._currentRenderTarget = null;
  33464. /**
  33465. * The XR render target that represents the rendering destination
  33466. * during an active XR session.
  33467. *
  33468. * @private
  33469. * @type {RenderTarget?}
  33470. * @default null
  33471. */
  33472. this._xrRenderTarget = null;
  33473. /**
  33474. * The current animation context.
  33475. *
  33476. * @private
  33477. * @type {Window?}
  33478. * @default null
  33479. */
  33480. this._currentAnimationContext = null;
  33481. /**
  33482. * The current animation loop.
  33483. *
  33484. * @private
  33485. * @type {Function?}
  33486. * @default null
  33487. */
  33488. this._currentAnimationLoop = null;
  33489. /**
  33490. * The current pixel ratio.
  33491. *
  33492. * @private
  33493. * @type {Number?}
  33494. * @default null
  33495. */
  33496. this._currentPixelRatio = null;
  33497. /**
  33498. * The current size of the renderer's canvas
  33499. * in logical pixel unit.
  33500. *
  33501. * @private
  33502. * @type {Vector2}
  33503. */
  33504. this._currentSize = new Vector2();
  33505. /**
  33506. * The default event listener for handling events inside a XR session.
  33507. *
  33508. * @private
  33509. * @type {Function}
  33510. */
  33511. this._onSessionEvent = onSessionEvent.bind( this );
  33512. /**
  33513. * The event listener for handling the end of a XR session.
  33514. *
  33515. * @private
  33516. * @type {Function}
  33517. */
  33518. this._onSessionEnd = onSessionEnd.bind( this );
  33519. /**
  33520. * The event listener for handling the `inputsourceschange` event.
  33521. *
  33522. * @private
  33523. * @type {Function}
  33524. */
  33525. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  33526. /**
  33527. * The animation loop which is used as a replacement for the default
  33528. * animation loop of the applicatio. It is only used when a XR session
  33529. * is active.
  33530. *
  33531. * @private
  33532. * @type {Function}
  33533. */
  33534. this._onAnimationFrame = onAnimationFrame.bind( this );
  33535. /**
  33536. * The current XR reference space.
  33537. *
  33538. * @private
  33539. * @type {XRReferenceSpace?}
  33540. * @default null
  33541. */
  33542. this._referenceSpace = null;
  33543. /**
  33544. * The current XR reference space type.
  33545. *
  33546. * @private
  33547. * @type {String}
  33548. * @default 'local-floor'
  33549. */
  33550. this._referenceSpaceType = 'local-floor';
  33551. /**
  33552. * A custom reference space defined by the application.
  33553. *
  33554. * @private
  33555. * @type {XRReferenceSpace?}
  33556. * @default null
  33557. */
  33558. this._customReferenceSpace = null;
  33559. /**
  33560. * The framebuffer scale factor.
  33561. *
  33562. * @private
  33563. * @type {Number}
  33564. * @default 1
  33565. */
  33566. this._framebufferScaleFactor = 1;
  33567. /**
  33568. * The foveation factor.
  33569. *
  33570. * @private
  33571. * @type {Number}
  33572. * @default 1
  33573. */
  33574. this._foveation = 1.0;
  33575. /**
  33576. * A reference to the current XR session.
  33577. *
  33578. * @private
  33579. * @type {XRSession?}
  33580. * @default null
  33581. */
  33582. this._session = null;
  33583. /**
  33584. * A reference to the current XR base layer.
  33585. *
  33586. * @private
  33587. * @type {XRWebGLLayer?}
  33588. * @default null
  33589. */
  33590. this._glBaseLayer = null;
  33591. /**
  33592. * A reference to the current XR binding.
  33593. *
  33594. * @private
  33595. * @type {XRWebGLBinding?}
  33596. * @default null
  33597. */
  33598. this._glBinding = null;
  33599. /**
  33600. * A reference to the current XR projection layer.
  33601. *
  33602. * @private
  33603. * @type {XRProjectionLayer?}
  33604. * @default null
  33605. */
  33606. this._glProjLayer = null;
  33607. /**
  33608. * A reference to the current XR frame.
  33609. *
  33610. * @private
  33611. * @type {XRFrame?}
  33612. * @default null
  33613. */
  33614. this._xrFrame = null;
  33615. /**
  33616. * Whether to use the WebXR Layers API or not.
  33617. *
  33618. * @private
  33619. * @type {Boolean}
  33620. * @readonly
  33621. */
  33622. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  33623. }
  33624. /**
  33625. * Returns an instance of `THREE.Group` that represents the transformation
  33626. * of a XR controller in target ray space. The requested controller is defined
  33627. * by the given index.
  33628. *
  33629. * @param {Number} index - The index of the XR controller.
  33630. * @return {Group} A group that represents the controller's transformation.
  33631. */
  33632. getController( index ) {
  33633. const controller = this._getController( index );
  33634. return controller.getTargetRaySpace();
  33635. }
  33636. /**
  33637. * Returns an instance of `THREE.Group` that represents the transformation
  33638. * of a XR controller in grip space. The requested controller is defined
  33639. * by the given index.
  33640. *
  33641. * @param {Number} index - The index of the XR controller.
  33642. * @return {Group} A group that represents the controller's transformation.
  33643. */
  33644. getControllerGrip( index ) {
  33645. const controller = this._getController( index );
  33646. return controller.getGripSpace();
  33647. }
  33648. /**
  33649. * Returns an instance of `THREE.Group` that represents the transformation
  33650. * of a XR controller in hand space. The requested controller is defined
  33651. * by the given index.
  33652. *
  33653. * @param {Number} index - The index of the XR controller.
  33654. * @return {Group} A group that represents the controller's transformation.
  33655. */
  33656. getHand( index ) {
  33657. const controller = this._getController( index );
  33658. return controller.getHandSpace();
  33659. }
  33660. /**
  33661. * Returns the foveation value.
  33662. *
  33663. * @return {Number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  33664. */
  33665. getFoveation() {
  33666. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  33667. return undefined;
  33668. }
  33669. return this._foveation;
  33670. }
  33671. /**
  33672. * Sets the foveation value.
  33673. *
  33674. * @param {Number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  33675. * and `1` means maximum foveation (the edges render at lower resolution).
  33676. */
  33677. setFoveation( foveation ) {
  33678. this._foveation = foveation;
  33679. if ( this._glProjLayer !== null ) {
  33680. this._glProjLayer.fixedFoveation = foveation;
  33681. }
  33682. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  33683. this._glBaseLayer.fixedFoveation = foveation;
  33684. }
  33685. }
  33686. /**
  33687. * Returns the framebuffer scale factor.
  33688. *
  33689. * @return {Number} The framebuffer scale factor.
  33690. */
  33691. getFramebufferScaleFactor() {
  33692. return this._framebufferScaleFactor;
  33693. }
  33694. /**
  33695. * Sets the framebuffer scale factor.
  33696. *
  33697. * This method can not be used during a XR session.
  33698. *
  33699. * @param {Number} factor - The framebuffer scale factor.
  33700. */
  33701. setFramebufferScaleFactor( factor ) {
  33702. this._framebufferScaleFactor = factor;
  33703. if ( this.isPresenting === true ) {
  33704. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  33705. }
  33706. }
  33707. /**
  33708. * Returns the reference space type.
  33709. *
  33710. * @return {String} The reference space type.
  33711. */
  33712. getReferenceSpaceType() {
  33713. return this._referenceSpaceType;
  33714. }
  33715. /**
  33716. * Sets the reference space type.
  33717. *
  33718. * This method can not be used during a XR session.
  33719. *
  33720. * @param {String} type - The reference space type.
  33721. */
  33722. setReferenceSpaceType( type ) {
  33723. this._referenceSpaceType = type;
  33724. if ( this.isPresenting === true ) {
  33725. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  33726. }
  33727. }
  33728. /**
  33729. * Returns the XR reference space.
  33730. *
  33731. * @return {XRReferenceSpace} The XR reference space.
  33732. */
  33733. getReferenceSpace() {
  33734. return this._customReferenceSpace || this._referenceSpace;
  33735. }
  33736. /**
  33737. * Sets a custom XR reference space.
  33738. *
  33739. * @param {XRReferenceSpace} space - The XR reference space.
  33740. */
  33741. setReferenceSpace( space ) {
  33742. this._customReferenceSpace = space;
  33743. }
  33744. /**
  33745. * Returns the XR camera.
  33746. *
  33747. * @return {ArrayCamera} The XR camera.
  33748. */
  33749. getCamera() {
  33750. return this._cameraXR;
  33751. }
  33752. /**
  33753. * Returns the environment blend mode from the current XR session.
  33754. *
  33755. * @return {('opaque'|'additive'|'alpha-blend')?} The environment blend mode. Returns `null` when used outside of a XR session.
  33756. */
  33757. getEnvironmentBlendMode() {
  33758. if ( this._session !== null ) {
  33759. return this._session.environmentBlendMode;
  33760. }
  33761. }
  33762. /**
  33763. * Returns the current XR frame.
  33764. *
  33765. * @return {XRFrame?} The XR frame. Returns `null` when used outside a XR session.
  33766. */
  33767. getFrame() {
  33768. return this._xrFrame;
  33769. }
  33770. /**
  33771. * Returns the current XR session.
  33772. *
  33773. * @return {XRSession?} The XR session. Returns `null` when used outside a XR session.
  33774. */
  33775. getSession() {
  33776. return this._session;
  33777. }
  33778. /**
  33779. * After a XR session has been requested usually with one of the `*Button` modules, it
  33780. * is injected into the renderer with this method. This method triggers the start of
  33781. * the actual XR rendering.
  33782. *
  33783. * @async
  33784. * @param {XRSession} session - The XR session to set.
  33785. * @return {Promise} A Promise that resolves when the session has been set.
  33786. */
  33787. async setSession( session ) {
  33788. const renderer = this._renderer;
  33789. const backend = renderer.backend;
  33790. const gl = renderer.getContext();
  33791. this._session = session;
  33792. if ( session !== null ) {
  33793. 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.' );
  33794. this._currentRenderTarget = renderer.getRenderTarget();
  33795. session.addEventListener( 'select', this._onSessionEvent );
  33796. session.addEventListener( 'selectstart', this._onSessionEvent );
  33797. session.addEventListener( 'selectend', this._onSessionEvent );
  33798. session.addEventListener( 'squeeze', this._onSessionEvent );
  33799. session.addEventListener( 'squeezestart', this._onSessionEvent );
  33800. session.addEventListener( 'squeezeend', this._onSessionEvent );
  33801. session.addEventListener( 'end', this._onSessionEnd );
  33802. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33803. await backend.makeXRCompatible();
  33804. this._currentPixelRatio = renderer.getPixelRatio();
  33805. renderer.getSize( this._currentSize );
  33806. this._currentAnimationContext = renderer._animation.getContext();
  33807. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  33808. renderer._animation.stop();
  33809. //
  33810. const attributes = gl.getContextAttributes();
  33811. if ( this._useLayers === true ) {
  33812. // default path using XRWebGLBinding/XRProjectionLayer
  33813. let depthFormat = null;
  33814. let depthType = null;
  33815. let glDepthFormat = null;
  33816. if ( attributes.depth ) {
  33817. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  33818. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  33819. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  33820. }
  33821. const projectionlayerInit = {
  33822. colorFormat: gl.RGBA8,
  33823. depthFormat: glDepthFormat,
  33824. scaleFactor: this._framebufferScaleFactor
  33825. };
  33826. const glBinding = new XRWebGLBinding( session, gl );
  33827. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  33828. this._glBinding = glBinding;
  33829. this._glProjLayer = glProjLayer;
  33830. session.updateRenderState( { layers: [ glProjLayer ] } );
  33831. renderer.setPixelRatio( 1 );
  33832. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  33833. this._xrRenderTarget = new XRRenderTarget(
  33834. glProjLayer.textureWidth,
  33835. glProjLayer.textureHeight,
  33836. {
  33837. format: RGBAFormat,
  33838. type: UnsignedByteType,
  33839. colorSpace: renderer.outputColorSpace,
  33840. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  33841. stencilBuffer: attributes.stencil,
  33842. samples: attributes.antialias ? 4 : 0
  33843. } );
  33844. this._xrRenderTarget.hasExternalTextures = true;
  33845. } else {
  33846. // fallback to XRWebGLLayer
  33847. const layerInit = {
  33848. antialias: attributes.antialias,
  33849. alpha: true,
  33850. depth: attributes.depth,
  33851. stencil: attributes.stencil,
  33852. framebufferScaleFactor: this.getFramebufferScaleFactor()
  33853. };
  33854. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  33855. this._glBaseLayer = glBaseLayer;
  33856. session.updateRenderState( { baseLayer: glBaseLayer } );
  33857. renderer.setPixelRatio( 1 );
  33858. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  33859. this._xrRenderTarget = new XRRenderTarget(
  33860. glBaseLayer.framebufferWidth,
  33861. glBaseLayer.framebufferHeight,
  33862. {
  33863. format: RGBAFormat,
  33864. type: UnsignedByteType,
  33865. colorSpace: renderer.outputColorSpace,
  33866. stencilBuffer: attributes.stencil
  33867. }
  33868. );
  33869. }
  33870. //
  33871. this.setFoveation( this.getFoveation() );
  33872. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  33873. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  33874. renderer._animation.setContext( session );
  33875. renderer._animation.start();
  33876. this.isPresenting = true;
  33877. this.dispatchEvent( { type: 'sessionstart' } );
  33878. }
  33879. }
  33880. /**
  33881. * This method is called by the renderer per frame and updates the XR camera
  33882. * and it sub cameras based on the given camera. The given camera is the "user"
  33883. * camera created on application level and used for non-XR rendering.
  33884. *
  33885. * @param {PerspectiveCamera} camera - The camera.
  33886. */
  33887. updateCamera( camera ) {
  33888. const session = this._session;
  33889. if ( session === null ) return;
  33890. const depthNear = camera.near;
  33891. const depthFar = camera.far;
  33892. const cameraXR = this._cameraXR;
  33893. const cameraL = this._cameraL;
  33894. const cameraR = this._cameraR;
  33895. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  33896. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  33897. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  33898. // Note that the new renderState won't apply until the next frame. See #18320
  33899. session.updateRenderState( {
  33900. depthNear: cameraXR.near,
  33901. depthFar: cameraXR.far
  33902. } );
  33903. this._currentDepthNear = cameraXR.near;
  33904. this._currentDepthFar = cameraXR.far;
  33905. }
  33906. cameraL.layers.mask = camera.layers.mask | 0b010;
  33907. cameraR.layers.mask = camera.layers.mask | 0b100;
  33908. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  33909. const parent = camera.parent;
  33910. const cameras = cameraXR.cameras;
  33911. updateCamera( cameraXR, parent );
  33912. for ( let i = 0; i < cameras.length; i ++ ) {
  33913. updateCamera( cameras[ i ], parent );
  33914. }
  33915. // update projection matrix for proper view frustum culling
  33916. if ( cameras.length === 2 ) {
  33917. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  33918. } else {
  33919. // assume single camera setup (AR)
  33920. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  33921. }
  33922. // update user camera and its children
  33923. updateUserCamera( camera, cameraXR, parent );
  33924. }
  33925. /**
  33926. * Returns a WebXR controller for the given controller index.
  33927. *
  33928. * @private
  33929. * @param {Number} index - The controller index.
  33930. * @return {WebXRController} The XR controller.
  33931. */
  33932. _getController( index ) {
  33933. let controller = this._controllers[ index ];
  33934. if ( controller === undefined ) {
  33935. controller = new WebXRController();
  33936. this._controllers[ index ] = controller;
  33937. }
  33938. return controller;
  33939. }
  33940. }
  33941. /**
  33942. * Assumes 2 cameras that are parallel and share an X-axis, and that
  33943. * the cameras' projection and world matrices have already been set.
  33944. * And that near and far planes are identical for both cameras.
  33945. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  33946. *
  33947. * @param {ArrayCamera} camera - The camera to update.
  33948. * @param {PerspectiveCamera} cameraL - The left camera.
  33949. * @param {PerspectiveCamera} cameraR - The right camera.
  33950. */
  33951. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  33952. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  33953. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  33954. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  33955. const projL = cameraL.projectionMatrix.elements;
  33956. const projR = cameraR.projectionMatrix.elements;
  33957. // VR systems will have identical far and near planes, and
  33958. // most likely identical top and bottom frustum extents.
  33959. // Use the left camera for these values.
  33960. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  33961. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  33962. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  33963. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  33964. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  33965. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  33966. const left = near * leftFov;
  33967. const right = near * rightFov;
  33968. // Calculate the new camera's position offset from the
  33969. // left camera. xOffset should be roughly half `ipd`.
  33970. const zOffset = ipd / ( - leftFov + rightFov );
  33971. const xOffset = zOffset * - leftFov;
  33972. // TODO: Better way to apply this offset?
  33973. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  33974. camera.translateX( xOffset );
  33975. camera.translateZ( zOffset );
  33976. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  33977. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33978. // Check if the projection uses an infinite far plane.
  33979. if ( projL[ 10 ] === -1 ) {
  33980. // Use the projection matrix from the left eye.
  33981. // The camera offset is sufficient to include the view volumes
  33982. // of both eyes (assuming symmetric projections).
  33983. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  33984. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  33985. } else {
  33986. // Find the union of the frustum values of the cameras and scale
  33987. // the values so that the near plane's position does not change in world space,
  33988. // although must now be relative to the new union camera.
  33989. const near2 = near + zOffset;
  33990. const far2 = far + zOffset;
  33991. const left2 = left - xOffset;
  33992. const right2 = right + ( ipd - xOffset );
  33993. const top2 = topFov * far / far2 * near2;
  33994. const bottom2 = bottomFov * far / far2 * near2;
  33995. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  33996. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33997. }
  33998. }
  33999. /**
  34000. * Updates the world matrices for the given camera based on the parent 3D object.
  34001. *
  34002. * @inner
  34003. * @param {Camera} camera - The camera to update.
  34004. * @param {Object3D} parent - The parent 3D object.
  34005. */
  34006. function updateCamera( camera, parent ) {
  34007. if ( parent === null ) {
  34008. camera.matrixWorld.copy( camera.matrix );
  34009. } else {
  34010. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  34011. }
  34012. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34013. }
  34014. /**
  34015. * Updates the given camera with the transfomration of the XR camera and parent object.
  34016. *
  34017. * @inner
  34018. * @param {Camera} camera - The camera to update.
  34019. * @param {ArrayCamera} cameraXR - The XR camera.
  34020. * @param {Object3D} parent - The parent 3D object.
  34021. */
  34022. function updateUserCamera( camera, cameraXR, parent ) {
  34023. if ( parent === null ) {
  34024. camera.matrix.copy( cameraXR.matrixWorld );
  34025. } else {
  34026. camera.matrix.copy( parent.matrixWorld );
  34027. camera.matrix.invert();
  34028. camera.matrix.multiply( cameraXR.matrixWorld );
  34029. }
  34030. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34031. camera.updateMatrixWorld( true );
  34032. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  34033. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  34034. if ( camera.isPerspectiveCamera ) {
  34035. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  34036. camera.zoom = 1;
  34037. }
  34038. }
  34039. function onSessionEvent( event ) {
  34040. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  34041. if ( controllerIndex === -1 ) {
  34042. return;
  34043. }
  34044. const controller = this._controllers[ controllerIndex ];
  34045. if ( controller !== undefined ) {
  34046. const referenceSpace = this.getReferenceSpace();
  34047. controller.update( event.inputSource, event.frame, referenceSpace );
  34048. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  34049. }
  34050. }
  34051. function onSessionEnd() {
  34052. const session = this._session;
  34053. const renderer = this._renderer;
  34054. session.removeEventListener( 'select', this._onSessionEvent );
  34055. session.removeEventListener( 'selectstart', this._onSessionEvent );
  34056. session.removeEventListener( 'selectend', this._onSessionEvent );
  34057. session.removeEventListener( 'squeeze', this._onSessionEvent );
  34058. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  34059. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  34060. session.removeEventListener( 'end', this._onSessionEnd );
  34061. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34062. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34063. const inputSource = this._controllerInputSources[ i ];
  34064. if ( inputSource === null ) continue;
  34065. this._controllerInputSources[ i ] = null;
  34066. this._controllers[ i ].disconnect( inputSource );
  34067. }
  34068. this._currentDepthNear = null;
  34069. this._currentDepthFar = null;
  34070. // restore framebuffer/rendering state
  34071. renderer.backend.setXRTarget( null );
  34072. renderer.setRenderTarget( this._currentRenderTarget );
  34073. this._session = null;
  34074. this._xrRenderTarget = null;
  34075. //
  34076. this.isPresenting = false;
  34077. renderer._animation.stop();
  34078. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  34079. renderer._animation.setContext( this._currentAnimationContext );
  34080. renderer._animation.start();
  34081. renderer.setPixelRatio( this._currentPixelRatio );
  34082. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  34083. this.dispatchEvent( { type: 'sessionend' } );
  34084. }
  34085. function onInputSourcesChange( event ) {
  34086. const controllers = this._controllers;
  34087. const controllerInputSources = this._controllerInputSources;
  34088. // Notify disconnected
  34089. for ( let i = 0; i < event.removed.length; i ++ ) {
  34090. const inputSource = event.removed[ i ];
  34091. const index = controllerInputSources.indexOf( inputSource );
  34092. if ( index >= 0 ) {
  34093. controllerInputSources[ index ] = null;
  34094. controllers[ index ].disconnect( inputSource );
  34095. }
  34096. }
  34097. // Notify connected
  34098. for ( let i = 0; i < event.added.length; i ++ ) {
  34099. const inputSource = event.added[ i ];
  34100. let controllerIndex = controllerInputSources.indexOf( inputSource );
  34101. if ( controllerIndex === -1 ) {
  34102. // Assign input source a controller that currently has no input source
  34103. for ( let i = 0; i < controllers.length; i ++ ) {
  34104. if ( i >= controllerInputSources.length ) {
  34105. controllerInputSources.push( inputSource );
  34106. controllerIndex = i;
  34107. break;
  34108. } else if ( controllerInputSources[ i ] === null ) {
  34109. controllerInputSources[ i ] = inputSource;
  34110. controllerIndex = i;
  34111. break;
  34112. }
  34113. }
  34114. // If all controllers do currently receive input we ignore new ones
  34115. if ( controllerIndex === -1 ) break;
  34116. }
  34117. const controller = controllers[ controllerIndex ];
  34118. if ( controller ) {
  34119. controller.connect( inputSource );
  34120. }
  34121. }
  34122. }
  34123. function onAnimationFrame( time, frame ) {
  34124. if ( frame === undefined ) return;
  34125. const cameraXR = this._cameraXR;
  34126. const renderer = this._renderer;
  34127. const backend = renderer.backend;
  34128. const glBaseLayer = this._glBaseLayer;
  34129. const referenceSpace = this.getReferenceSpace();
  34130. const pose = frame.getViewerPose( referenceSpace );
  34131. this._xrFrame = frame;
  34132. if ( pose !== null ) {
  34133. const views = pose.views;
  34134. if ( this._glBaseLayer !== null ) {
  34135. backend.setXRTarget( glBaseLayer.framebuffer );
  34136. }
  34137. let cameraXRNeedsUpdate = false;
  34138. // check if it's necessary to rebuild cameraXR's camera list
  34139. if ( views.length !== cameraXR.cameras.length ) {
  34140. cameraXR.cameras.length = 0;
  34141. cameraXRNeedsUpdate = true;
  34142. }
  34143. for ( let i = 0; i < views.length; i ++ ) {
  34144. const view = views[ i ];
  34145. let viewport;
  34146. if ( this._useLayers === true ) {
  34147. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  34148. viewport = glSubImage.viewport;
  34149. // For side-by-side projection, we only produce a single texture for both eyes.
  34150. if ( i === 0 ) {
  34151. backend.setXRRenderTargetTextures(
  34152. this._xrRenderTarget,
  34153. glSubImage.colorTexture,
  34154. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  34155. );
  34156. }
  34157. } else {
  34158. viewport = glBaseLayer.getViewport( view );
  34159. }
  34160. let camera = this._cameras[ i ];
  34161. if ( camera === undefined ) {
  34162. camera = new PerspectiveCamera();
  34163. camera.layers.enable( i );
  34164. camera.viewport = new Vector4();
  34165. this._cameras[ i ] = camera;
  34166. }
  34167. camera.matrix.fromArray( view.transform.matrix );
  34168. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34169. camera.projectionMatrix.fromArray( view.projectionMatrix );
  34170. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34171. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  34172. if ( i === 0 ) {
  34173. cameraXR.matrix.copy( camera.matrix );
  34174. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  34175. }
  34176. if ( cameraXRNeedsUpdate === true ) {
  34177. cameraXR.cameras.push( camera );
  34178. }
  34179. }
  34180. renderer.setRenderTarget( this._xrRenderTarget );
  34181. }
  34182. //
  34183. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34184. const inputSource = this._controllerInputSources[ i ];
  34185. const controller = this._controllers[ i ];
  34186. if ( inputSource !== null && controller !== undefined ) {
  34187. controller.update( inputSource, frame, referenceSpace );
  34188. }
  34189. }
  34190. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  34191. if ( frame.detectedPlanes ) {
  34192. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  34193. }
  34194. this._xrFrame = null;
  34195. }
  34196. /** @module Renderer **/
  34197. const _scene = /*@__PURE__*/ new Scene();
  34198. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  34199. const _screen = /*@__PURE__*/ new Vector4();
  34200. const _frustum = /*@__PURE__*/ new Frustum();
  34201. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  34202. const _vector4 = /*@__PURE__*/ new Vector4();
  34203. /**
  34204. * Base class for renderers.
  34205. */
  34206. class Renderer {
  34207. /**
  34208. * Constructs a new renderer.
  34209. *
  34210. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  34211. * @param {Object} parameters - The configuration parameter.
  34212. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  34213. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  34214. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  34215. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  34216. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  34217. * @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
  34218. * to overwrite the default.
  34219. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34220. */
  34221. constructor( backend, parameters = {} ) {
  34222. /**
  34223. * This flag can be used for type testing.
  34224. *
  34225. * @type {Boolean}
  34226. * @readonly
  34227. * @default true
  34228. */
  34229. this.isRenderer = true;
  34230. //
  34231. const {
  34232. logarithmicDepthBuffer = false,
  34233. alpha = true,
  34234. depth = true,
  34235. stencil = false,
  34236. antialias = false,
  34237. samples = 0,
  34238. getFallback = null
  34239. } = parameters;
  34240. /**
  34241. * A reference to the canvas element the renderer is drawing to.
  34242. * This value of this property will automatically be created by
  34243. * the renderer.
  34244. *
  34245. * @type {HTMLCanvasElement|OffscreenCanvas}
  34246. */
  34247. this.domElement = backend.getDomElement();
  34248. /**
  34249. * A reference to the current backend.
  34250. *
  34251. * @type {Backend}
  34252. */
  34253. this.backend = backend;
  34254. /**
  34255. * The number of MSAA samples.
  34256. *
  34257. * @type {Number}
  34258. * @default 0
  34259. */
  34260. this.samples = samples || ( antialias === true ) ? 4 : 0;
  34261. /**
  34262. * Whether the renderer should automatically clear the current rendering target
  34263. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  34264. * or the current bound render target (custom framebuffer).
  34265. *
  34266. * @type {Boolean}
  34267. * @default true
  34268. */
  34269. this.autoClear = true;
  34270. /**
  34271. * When `autoClear` is set to `true`, this property defines whether the renderer
  34272. * should clear the color buffer.
  34273. *
  34274. * @type {Boolean}
  34275. * @default true
  34276. */
  34277. this.autoClearColor = true;
  34278. /**
  34279. * When `autoClear` is set to `true`, this property defines whether the renderer
  34280. * should clear the depth buffer.
  34281. *
  34282. * @type {Boolean}
  34283. * @default true
  34284. */
  34285. this.autoClearDepth = true;
  34286. /**
  34287. * When `autoClear` is set to `true`, this property defines whether the renderer
  34288. * should clear the stencil buffer.
  34289. *
  34290. * @type {Boolean}
  34291. * @default true
  34292. */
  34293. this.autoClearStencil = true;
  34294. /**
  34295. * Whether the default framebuffer should be transparent or opaque.
  34296. *
  34297. * @type {Boolean}
  34298. * @default true
  34299. */
  34300. this.alpha = alpha;
  34301. /**
  34302. * Whether logarithmic depth buffer is enabled or not.
  34303. *
  34304. * @type {Boolean}
  34305. * @default false
  34306. */
  34307. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  34308. /**
  34309. * Defines the output color space of the renderer.
  34310. *
  34311. * @type {String}
  34312. * @default SRGBColorSpace
  34313. */
  34314. this.outputColorSpace = SRGBColorSpace;
  34315. /**
  34316. * Defines the tone mapping of the renderer.
  34317. *
  34318. * @type {Number}
  34319. * @default NoToneMapping
  34320. */
  34321. this.toneMapping = NoToneMapping;
  34322. /**
  34323. * Defines the tone mapping exposure.
  34324. *
  34325. * @type {Number}
  34326. * @default 1
  34327. */
  34328. this.toneMappingExposure = 1.0;
  34329. /**
  34330. * Whether the renderer should sort its render lists or not.
  34331. *
  34332. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  34333. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  34334. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  34335. * e.g. manually determining each object's rendering order.
  34336. *
  34337. * @type {Boolean}
  34338. * @default true
  34339. */
  34340. this.sortObjects = true;
  34341. /**
  34342. * Whether the default framebuffer should have a depth buffer or not.
  34343. *
  34344. * @type {Boolean}
  34345. * @default true
  34346. */
  34347. this.depth = depth;
  34348. /**
  34349. * Whether the default framebuffer should have a stencil buffer or not.
  34350. *
  34351. * @type {Boolean}
  34352. * @default false
  34353. */
  34354. this.stencil = stencil;
  34355. /**
  34356. * Holds a series of statistical information about the GPU memory
  34357. * and the rendering process. Useful for debugging and monitoring.
  34358. *
  34359. * @type {Info}
  34360. */
  34361. this.info = new Info();
  34362. this.nodes = {
  34363. modelViewMatrix: null,
  34364. modelNormalViewMatrix: null
  34365. };
  34366. /**
  34367. * The node library defines how certain library objects like materials, lights
  34368. * or tone mapping functions are mapped to node types. This is required since
  34369. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  34370. * be part of the scene graph, they are internally represented as nodes for
  34371. * further processing.
  34372. *
  34373. * @type {NodeLibrary}
  34374. */
  34375. this.library = new NodeLibrary();
  34376. /**
  34377. * A map-like data structure for managing lights.
  34378. *
  34379. * @type {Lighting}
  34380. */
  34381. this.lighting = new Lighting();
  34382. // internals
  34383. /**
  34384. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34385. *
  34386. * @private
  34387. * @type {Function}
  34388. */
  34389. this._getFallback = getFallback;
  34390. /**
  34391. * The renderer's pixel ration.
  34392. *
  34393. * @private
  34394. * @type {Number}
  34395. * @default 1
  34396. */
  34397. this._pixelRatio = 1;
  34398. /**
  34399. * The width of the renderer's default framebuffer in logical pixel unit.
  34400. *
  34401. * @private
  34402. * @type {Number}
  34403. */
  34404. this._width = this.domElement.width;
  34405. /**
  34406. * The height of the renderer's default framebuffer in logical pixel unit.
  34407. *
  34408. * @private
  34409. * @type {Number}
  34410. */
  34411. this._height = this.domElement.height;
  34412. /**
  34413. * The viewport of the renderer in logical pixel unit.
  34414. *
  34415. * @private
  34416. * @type {Vector4}
  34417. */
  34418. this._viewport = new Vector4( 0, 0, this._width, this._height );
  34419. /**
  34420. * The scissor rectangle of the renderer in logical pixel unit.
  34421. *
  34422. * @private
  34423. * @type {Vector4}
  34424. */
  34425. this._scissor = new Vector4( 0, 0, this._width, this._height );
  34426. /**
  34427. * Whether the scissor test should be enabled or not.
  34428. *
  34429. * @private
  34430. * @type {Boolean}
  34431. */
  34432. this._scissorTest = false;
  34433. /**
  34434. * A reference to a renderer module for managing shader attributes.
  34435. *
  34436. * @private
  34437. * @type {Attributes?}
  34438. * @default null
  34439. */
  34440. this._attributes = null;
  34441. /**
  34442. * A reference to a renderer module for managing geometries.
  34443. *
  34444. * @private
  34445. * @type {Geometries?}
  34446. * @default null
  34447. */
  34448. this._geometries = null;
  34449. /**
  34450. * A reference to a renderer module for managing node related logic.
  34451. *
  34452. * @private
  34453. * @type {Nodes?}
  34454. * @default null
  34455. */
  34456. this._nodes = null;
  34457. /**
  34458. * A reference to a renderer module for managing the internal animation loop.
  34459. *
  34460. * @private
  34461. * @type {Animation?}
  34462. * @default null
  34463. */
  34464. this._animation = null;
  34465. /**
  34466. * A reference to a renderer module for managing shader program bindings.
  34467. *
  34468. * @private
  34469. * @type {Bindings?}
  34470. * @default null
  34471. */
  34472. this._bindings = null;
  34473. /**
  34474. * A reference to a renderer module for managing render objects.
  34475. *
  34476. * @private
  34477. * @type {RenderObjects?}
  34478. * @default null
  34479. */
  34480. this._objects = null;
  34481. /**
  34482. * A reference to a renderer module for managing render and compute pipelines.
  34483. *
  34484. * @private
  34485. * @type {Pipelines?}
  34486. * @default null
  34487. */
  34488. this._pipelines = null;
  34489. /**
  34490. * A reference to a renderer module for managing render bundles.
  34491. *
  34492. * @private
  34493. * @type {RenderBundles?}
  34494. * @default null
  34495. */
  34496. this._bundles = null;
  34497. /**
  34498. * A reference to a renderer module for managing render lists.
  34499. *
  34500. * @private
  34501. * @type {RenderLists?}
  34502. * @default null
  34503. */
  34504. this._renderLists = null;
  34505. /**
  34506. * A reference to a renderer module for managing render contexts.
  34507. *
  34508. * @private
  34509. * @type {RenderContexts?}
  34510. * @default null
  34511. */
  34512. this._renderContexts = null;
  34513. /**
  34514. * A reference to a renderer module for managing textures.
  34515. *
  34516. * @private
  34517. * @type {Textures?}
  34518. * @default null
  34519. */
  34520. this._textures = null;
  34521. /**
  34522. * A reference to a renderer module for backgrounds.
  34523. *
  34524. * @private
  34525. * @type {Background?}
  34526. * @default null
  34527. */
  34528. this._background = null;
  34529. /**
  34530. * This fullscreen quad is used for internal render passes
  34531. * like the tone mapping and color space output pass.
  34532. *
  34533. * @private
  34534. * @type {QuadMesh}
  34535. */
  34536. this._quad = new QuadMesh( new NodeMaterial() );
  34537. this._quad.material.name = 'Renderer_output';
  34538. /**
  34539. * A reference to the current render context.
  34540. *
  34541. * @private
  34542. * @type {RenderContext?}
  34543. * @default null
  34544. */
  34545. this._currentRenderContext = null;
  34546. /**
  34547. * A custom sort function for the opaque render list.
  34548. *
  34549. * @private
  34550. * @type {Function?}
  34551. * @default null
  34552. */
  34553. this._opaqueSort = null;
  34554. /**
  34555. * A custom sort function for the transparent render list.
  34556. *
  34557. * @private
  34558. * @type {Function?}
  34559. * @default null
  34560. */
  34561. this._transparentSort = null;
  34562. /**
  34563. * The framebuffer target.
  34564. *
  34565. * @private
  34566. * @type {RenderTarget?}
  34567. * @default null
  34568. */
  34569. this._frameBufferTarget = null;
  34570. const alphaClear = this.alpha === true ? 0 : 1;
  34571. /**
  34572. * The clear color value.
  34573. *
  34574. * @private
  34575. * @type {Color4}
  34576. */
  34577. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  34578. /**
  34579. * The clear depth value.
  34580. *
  34581. * @private
  34582. * @type {Number}
  34583. * @default 1
  34584. */
  34585. this._clearDepth = 1;
  34586. /**
  34587. * The clear stencil value.
  34588. *
  34589. * @private
  34590. * @type {Number}
  34591. * @default 0
  34592. */
  34593. this._clearStencil = 0;
  34594. /**
  34595. * The current render target.
  34596. *
  34597. * @private
  34598. * @type {RenderTarget?}
  34599. * @default null
  34600. */
  34601. this._renderTarget = null;
  34602. /**
  34603. * The active cube face.
  34604. *
  34605. * @private
  34606. * @type {Number}
  34607. * @default 0
  34608. */
  34609. this._activeCubeFace = 0;
  34610. /**
  34611. * The active mipmap level.
  34612. *
  34613. * @private
  34614. * @type {Number}
  34615. * @default 0
  34616. */
  34617. this._activeMipmapLevel = 0;
  34618. /**
  34619. * The MRT setting.
  34620. *
  34621. * @private
  34622. * @type {MRTNode?}
  34623. * @default null
  34624. */
  34625. this._mrt = null;
  34626. /**
  34627. * This function defines how a render object is going
  34628. * to be rendered.
  34629. *
  34630. * @private
  34631. * @type {Function?}
  34632. * @default null
  34633. */
  34634. this._renderObjectFunction = null;
  34635. /**
  34636. * Used to keep track of the current render object function.
  34637. *
  34638. * @private
  34639. * @type {Function?}
  34640. * @default null
  34641. */
  34642. this._currentRenderObjectFunction = null;
  34643. /**
  34644. * Used to keep track of the current render bundle.
  34645. *
  34646. * @private
  34647. * @type {RenderBundle?}
  34648. * @default null
  34649. */
  34650. this._currentRenderBundle = null;
  34651. /**
  34652. * Next to `_renderObjectFunction()`, this function provides another hook
  34653. * for influencing the render process of a render object. It is meant for internal
  34654. * use and only relevant for `compileAsync()` right now. Instead of using
  34655. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  34656. * a different function might be used which performs no draw but just the node
  34657. * and pipeline updates.
  34658. *
  34659. * @private
  34660. * @type {Function?}
  34661. * @default null
  34662. */
  34663. this._handleObjectFunction = this._renderObjectDirect;
  34664. /**
  34665. * Indicates whether the device has been lost or not. In WebGL terms, the device
  34666. * lost is considered as a context lost. When this is set to `true`, rendering
  34667. * isn't possible anymore.
  34668. *
  34669. * @private
  34670. * @type {Boolean}
  34671. * @default false
  34672. */
  34673. this._isDeviceLost = false;
  34674. /**
  34675. * A callback function that defines what should happen when a device/context lost occurs.
  34676. *
  34677. * @type {Function}
  34678. */
  34679. this.onDeviceLost = this._onDeviceLost;
  34680. /**
  34681. * Whether the renderer has been initialized or not.
  34682. *
  34683. * @private
  34684. * @type {Boolean}
  34685. * @default false
  34686. */
  34687. this._initialized = false;
  34688. /**
  34689. * A reference to the promise which initializes the renderer.
  34690. *
  34691. * @private
  34692. * @type {Promise?}
  34693. * @default null
  34694. */
  34695. this._initPromise = null;
  34696. /**
  34697. * An array of compilation promises which are used in `compileAsync()`.
  34698. *
  34699. * @private
  34700. * @type {Array<Promise>?}
  34701. * @default null
  34702. */
  34703. this._compilationPromises = null;
  34704. /**
  34705. * Whether the renderer should render transparent render objects or not.
  34706. *
  34707. * @type {Boolean}
  34708. * @default true
  34709. */
  34710. this.transparent = true;
  34711. /**
  34712. * Whether the renderer should render opaque render objects or not.
  34713. *
  34714. * @type {Boolean}
  34715. * @default true
  34716. */
  34717. this.opaque = true;
  34718. /**
  34719. * Shadow map configuration
  34720. * @typedef {Object} ShadowMapConfig
  34721. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  34722. * @property {Number} type - The shadow map type.
  34723. */
  34724. /**
  34725. * The renderer's shadow configuration.
  34726. *
  34727. * @type {module:Renderer~ShadowMapConfig}
  34728. */
  34729. this.shadowMap = {
  34730. enabled: false,
  34731. type: PCFShadowMap
  34732. };
  34733. /**
  34734. * XR configuration.
  34735. * @typedef {Object} XRConfig
  34736. * @property {Boolean} enabled - Whether to globally enable XR or not.
  34737. */
  34738. /**
  34739. * The renderer's XR manager.
  34740. *
  34741. * @type {XRManager}
  34742. */
  34743. this.xr = new XRManager( this );
  34744. /**
  34745. * Debug configuration.
  34746. * @typedef {Object} DebugConfig
  34747. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  34748. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  34749. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  34750. */
  34751. /**
  34752. * The renderer's debug configuration.
  34753. *
  34754. * @type {module:Renderer~DebugConfig}
  34755. */
  34756. this.debug = {
  34757. checkShaderErrors: true,
  34758. onShaderError: null,
  34759. getShaderAsync: async ( scene, camera, object ) => {
  34760. await this.compileAsync( scene, camera );
  34761. const renderList = this._renderLists.get( scene, camera );
  34762. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  34763. const material = scene.overrideMaterial || object.material;
  34764. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  34765. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  34766. return { fragmentShader, vertexShader };
  34767. }
  34768. };
  34769. }
  34770. /**
  34771. * Initializes the renderer so it is ready for usage.
  34772. *
  34773. * @async
  34774. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  34775. */
  34776. async init() {
  34777. if ( this._initialized ) {
  34778. throw new Error( 'Renderer: Backend has already been initialized.' );
  34779. }
  34780. if ( this._initPromise !== null ) {
  34781. return this._initPromise;
  34782. }
  34783. this._initPromise = new Promise( async ( resolve, reject ) => {
  34784. let backend = this.backend;
  34785. try {
  34786. await backend.init( this );
  34787. } catch ( error ) {
  34788. if ( this._getFallback !== null ) {
  34789. // try the fallback
  34790. try {
  34791. this.backend = backend = this._getFallback( error );
  34792. await backend.init( this );
  34793. } catch ( error ) {
  34794. reject( error );
  34795. return;
  34796. }
  34797. } else {
  34798. reject( error );
  34799. return;
  34800. }
  34801. }
  34802. this._nodes = new Nodes( this, backend );
  34803. this._animation = new Animation( this._nodes, this.info );
  34804. this._attributes = new Attributes( backend );
  34805. this._background = new Background( this, this._nodes );
  34806. this._geometries = new Geometries( this._attributes, this.info );
  34807. this._textures = new Textures( this, backend, this.info );
  34808. this._pipelines = new Pipelines( backend, this._nodes );
  34809. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  34810. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  34811. this._renderLists = new RenderLists( this.lighting );
  34812. this._bundles = new RenderBundles();
  34813. this._renderContexts = new RenderContexts();
  34814. //
  34815. this._animation.start();
  34816. this._initialized = true;
  34817. resolve();
  34818. } );
  34819. return this._initPromise;
  34820. }
  34821. /**
  34822. * The coordinate system of the renderer. The value of this property
  34823. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  34824. * `THREE.WebGPUCoordinateSystem`.
  34825. *
  34826. * @readonly
  34827. * @type {Number}
  34828. */
  34829. get coordinateSystem() {
  34830. return this.backend.coordinateSystem;
  34831. }
  34832. /**
  34833. * Compiles all materials in the given scene. This can be useful to avoid a
  34834. * phenomenon which is called "shader compilation stutter", which occurs when
  34835. * rendering an object with a new shader for the first time.
  34836. *
  34837. * If you want to add a 3D object to an existing scene, use the third optional
  34838. * parameter for applying the target scene. Note that the (target) scene's lighting
  34839. * and environment must be configured before calling this method.
  34840. *
  34841. * @async
  34842. * @param {Object3D} scene - The scene or 3D object to precompile.
  34843. * @param {Camera} camera - The camera that is used to render the scene.
  34844. * @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.
  34845. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  34846. */
  34847. async compileAsync( scene, camera, targetScene = null ) {
  34848. if ( this._isDeviceLost === true ) return;
  34849. if ( this._initialized === false ) await this.init();
  34850. // preserve render tree
  34851. const nodeFrame = this._nodes.nodeFrame;
  34852. const previousRenderId = nodeFrame.renderId;
  34853. const previousRenderContext = this._currentRenderContext;
  34854. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34855. const previousCompilationPromises = this._compilationPromises;
  34856. //
  34857. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34858. if ( targetScene === null ) targetScene = scene;
  34859. const renderTarget = this._renderTarget;
  34860. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  34861. const activeMipmapLevel = this._activeMipmapLevel;
  34862. const compilationPromises = [];
  34863. this._currentRenderContext = renderContext;
  34864. this._currentRenderObjectFunction = this.renderObject;
  34865. this._handleObjectFunction = this._createObjectPipeline;
  34866. this._compilationPromises = compilationPromises;
  34867. nodeFrame.renderId ++;
  34868. //
  34869. nodeFrame.update();
  34870. //
  34871. renderContext.depth = this.depth;
  34872. renderContext.stencil = this.stencil;
  34873. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34874. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34875. //
  34876. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34877. //
  34878. const renderList = this._renderLists.get( scene, camera );
  34879. renderList.begin();
  34880. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34881. // include lights from target scene
  34882. if ( targetScene !== scene ) {
  34883. targetScene.traverseVisible( function ( object ) {
  34884. if ( object.isLight && object.layers.test( camera.layers ) ) {
  34885. renderList.pushLight( object );
  34886. }
  34887. } );
  34888. }
  34889. renderList.finish();
  34890. //
  34891. if ( renderTarget !== null ) {
  34892. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34893. const renderTargetData = this._textures.get( renderTarget );
  34894. renderContext.textures = renderTargetData.textures;
  34895. renderContext.depthTexture = renderTargetData.depthTexture;
  34896. } else {
  34897. renderContext.textures = null;
  34898. renderContext.depthTexture = null;
  34899. }
  34900. //
  34901. this._background.update( sceneRef, renderList, renderContext );
  34902. // process render lists
  34903. const opaqueObjects = renderList.opaque;
  34904. const transparentObjects = renderList.transparent;
  34905. const transparentDoublePassObjects = renderList.transparentDoublePass;
  34906. const lightsNode = renderList.lightsNode;
  34907. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34908. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34909. // restore render tree
  34910. nodeFrame.renderId = previousRenderId;
  34911. this._currentRenderContext = previousRenderContext;
  34912. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34913. this._compilationPromises = previousCompilationPromises;
  34914. this._handleObjectFunction = this._renderObjectDirect;
  34915. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  34916. await Promise.all( compilationPromises );
  34917. }
  34918. /**
  34919. * Renders the scene in an async fashion.
  34920. *
  34921. * @async
  34922. * @param {Object3D} scene - The scene or 3D object to render.
  34923. * @param {Camera} camera - The camera.
  34924. * @return {Promise} A Promise that resolves when the render has been finished.
  34925. */
  34926. async renderAsync( scene, camera ) {
  34927. if ( this._initialized === false ) await this.init();
  34928. this._renderScene( scene, camera );
  34929. }
  34930. /**
  34931. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  34932. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  34933. *
  34934. * @async
  34935. * @return {Promise} A Promise that resolves when synchronization has been finished.
  34936. */
  34937. async waitForGPU() {
  34938. await this.backend.waitForGPU();
  34939. }
  34940. /**
  34941. * Sets the given MRT configuration.
  34942. *
  34943. * @param {MRTNode} mrt - The MRT node to set.
  34944. * @return {Renderer} A reference to this renderer.
  34945. */
  34946. setMRT( mrt ) {
  34947. this._mrt = mrt;
  34948. return this;
  34949. }
  34950. /**
  34951. * Returns the MRT configuration.
  34952. *
  34953. * @return {MRTNode} The MRT configuration.
  34954. */
  34955. getMRT() {
  34956. return this._mrt;
  34957. }
  34958. /**
  34959. * Default implementation of the device lost callback.
  34960. *
  34961. * @private
  34962. * @param {Object} info - Information about the context lost.
  34963. */
  34964. _onDeviceLost( info ) {
  34965. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  34966. if ( info.reason ) {
  34967. errorMessage += `\nReason: ${info.reason}`;
  34968. }
  34969. console.error( errorMessage );
  34970. this._isDeviceLost = true;
  34971. }
  34972. /**
  34973. * Renders the given render bundle.
  34974. *
  34975. * @private
  34976. * @param {Object} bundle - Render bundle data.
  34977. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  34978. * @param {LightsNode} lightsNode - The current lights node.
  34979. */
  34980. _renderBundle( bundle, sceneRef, lightsNode ) {
  34981. const { bundleGroup, camera, renderList } = bundle;
  34982. const renderContext = this._currentRenderContext;
  34983. //
  34984. const renderBundle = this._bundles.get( bundleGroup, camera );
  34985. const renderBundleData = this.backend.get( renderBundle );
  34986. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  34987. //
  34988. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  34989. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  34990. renderBundleData.renderContexts.add( renderContext );
  34991. if ( renderBundleNeedsUpdate ) {
  34992. this.backend.beginBundle( renderContext );
  34993. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  34994. renderBundleData.renderObjects = [];
  34995. }
  34996. this._currentRenderBundle = renderBundle;
  34997. const opaqueObjects = renderList.opaque;
  34998. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34999. this._currentRenderBundle = null;
  35000. //
  35001. this.backend.finishBundle( renderContext, renderBundle );
  35002. renderBundleData.version = bundleGroup.version;
  35003. } else {
  35004. const { renderObjects } = renderBundleData;
  35005. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  35006. const renderObject = renderObjects[ i ];
  35007. if ( this._nodes.needsRefresh( renderObject ) ) {
  35008. this._nodes.updateBefore( renderObject );
  35009. this._nodes.updateForRender( renderObject );
  35010. this._bindings.updateForRender( renderObject );
  35011. this._nodes.updateAfter( renderObject );
  35012. }
  35013. }
  35014. }
  35015. this.backend.addBundle( renderContext, renderBundle );
  35016. }
  35017. /**
  35018. * Renders the scene or 3D object with the given camera. This method can only be called
  35019. * if the renderer has been initialized.
  35020. *
  35021. * The target of the method is the default framebuffer (meaning the canvas)
  35022. * or alternatively a render target when specified via `setRenderTarget()`.
  35023. *
  35024. * @param {Object3D} scene - The scene or 3D object to render.
  35025. * @param {Camera} camera - The camera to render the scene with.
  35026. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  35027. * Only returned when the renderer has not been initialized.
  35028. */
  35029. render( scene, camera ) {
  35030. if ( this._initialized === false ) {
  35031. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35032. return this.renderAsync( scene, camera );
  35033. }
  35034. this._renderScene( scene, camera );
  35035. }
  35036. /**
  35037. * Returns an internal render target which is used when computing the output tone mapping
  35038. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  35039. * pass and not inline to achieve more correct results.
  35040. *
  35041. * @private
  35042. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  35043. */
  35044. _getFrameBufferTarget() {
  35045. const { currentToneMapping, currentColorSpace } = this;
  35046. const useToneMapping = currentToneMapping !== NoToneMapping;
  35047. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  35048. if ( useToneMapping === false && useColorSpace === false ) return null;
  35049. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35050. const { depth, stencil } = this;
  35051. let frameBufferTarget = this._frameBufferTarget;
  35052. if ( frameBufferTarget === null ) {
  35053. frameBufferTarget = new RenderTarget( width, height, {
  35054. depthBuffer: depth,
  35055. stencilBuffer: stencil,
  35056. type: HalfFloatType, // FloatType
  35057. format: RGBAFormat,
  35058. colorSpace: LinearSRGBColorSpace,
  35059. generateMipmaps: false,
  35060. minFilter: LinearFilter,
  35061. magFilter: LinearFilter,
  35062. samples: this.samples
  35063. } );
  35064. frameBufferTarget.isPostProcessingRenderTarget = true;
  35065. this._frameBufferTarget = frameBufferTarget;
  35066. }
  35067. frameBufferTarget.depthBuffer = depth;
  35068. frameBufferTarget.stencilBuffer = stencil;
  35069. frameBufferTarget.setSize( width, height );
  35070. frameBufferTarget.viewport.copy( this._viewport );
  35071. frameBufferTarget.scissor.copy( this._scissor );
  35072. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35073. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35074. frameBufferTarget.scissorTest = this._scissorTest;
  35075. return frameBufferTarget;
  35076. }
  35077. /**
  35078. * Renders the scene or 3D object with the given camera.
  35079. *
  35080. * @private
  35081. * @param {Object3D} scene - The scene or 3D object to render.
  35082. * @param {Camera} camera - The camera to render the scene with.
  35083. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  35084. * @return {RenderContext} The current render context.
  35085. */
  35086. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35087. if ( this._isDeviceLost === true ) return;
  35088. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35089. // preserve render tree
  35090. const nodeFrame = this._nodes.nodeFrame;
  35091. const previousRenderId = nodeFrame.renderId;
  35092. const previousRenderContext = this._currentRenderContext;
  35093. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35094. //
  35095. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35096. const outputRenderTarget = this._renderTarget;
  35097. const activeCubeFace = this._activeCubeFace;
  35098. const activeMipmapLevel = this._activeMipmapLevel;
  35099. //
  35100. let renderTarget;
  35101. if ( frameBufferTarget !== null ) {
  35102. renderTarget = frameBufferTarget;
  35103. this.setRenderTarget( renderTarget );
  35104. } else {
  35105. renderTarget = outputRenderTarget;
  35106. }
  35107. //
  35108. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35109. this._currentRenderContext = renderContext;
  35110. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35111. //
  35112. this.info.calls ++;
  35113. this.info.render.calls ++;
  35114. this.info.render.frameCalls ++;
  35115. nodeFrame.renderId = this.info.calls;
  35116. //
  35117. const coordinateSystem = this.coordinateSystem;
  35118. const xr = this.xr;
  35119. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  35120. camera.coordinateSystem = coordinateSystem;
  35121. camera.updateProjectionMatrix();
  35122. if ( camera.isArrayCamera ) {
  35123. for ( const subCamera of camera.cameras ) {
  35124. subCamera.coordinateSystem = coordinateSystem;
  35125. subCamera.updateProjectionMatrix();
  35126. }
  35127. }
  35128. }
  35129. //
  35130. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35131. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35132. if ( xr.enabled === true && xr.isPresenting === true ) {
  35133. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  35134. camera = xr.getCamera(); // use XR camera for rendering
  35135. }
  35136. //
  35137. let viewport = this._viewport;
  35138. let scissor = this._scissor;
  35139. let pixelRatio = this._pixelRatio;
  35140. if ( renderTarget !== null ) {
  35141. viewport = renderTarget.viewport;
  35142. scissor = renderTarget.scissor;
  35143. pixelRatio = 1;
  35144. }
  35145. this.getDrawingBufferSize( _drawingBufferSize );
  35146. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35147. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35148. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35149. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35150. renderContext.viewportValue.width >>= activeMipmapLevel;
  35151. renderContext.viewportValue.height >>= activeMipmapLevel;
  35152. renderContext.viewportValue.minDepth = minDepth;
  35153. renderContext.viewportValue.maxDepth = maxDepth;
  35154. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35155. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35156. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35157. renderContext.scissorValue.width >>= activeMipmapLevel;
  35158. renderContext.scissorValue.height >>= activeMipmapLevel;
  35159. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35160. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35161. //
  35162. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35163. //
  35164. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35165. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35166. const renderList = this._renderLists.get( scene, camera );
  35167. renderList.begin();
  35168. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35169. renderList.finish();
  35170. if ( this.sortObjects === true ) {
  35171. renderList.sort( this._opaqueSort, this._transparentSort );
  35172. }
  35173. //
  35174. if ( renderTarget !== null ) {
  35175. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35176. const renderTargetData = this._textures.get( renderTarget );
  35177. renderContext.textures = renderTargetData.textures;
  35178. renderContext.depthTexture = renderTargetData.depthTexture;
  35179. renderContext.width = renderTargetData.width;
  35180. renderContext.height = renderTargetData.height;
  35181. renderContext.renderTarget = renderTarget;
  35182. renderContext.depth = renderTarget.depthBuffer;
  35183. renderContext.stencil = renderTarget.stencilBuffer;
  35184. } else {
  35185. renderContext.textures = null;
  35186. renderContext.depthTexture = null;
  35187. renderContext.width = this.domElement.width;
  35188. renderContext.height = this.domElement.height;
  35189. renderContext.depth = this.depth;
  35190. renderContext.stencil = this.stencil;
  35191. }
  35192. renderContext.width >>= activeMipmapLevel;
  35193. renderContext.height >>= activeMipmapLevel;
  35194. renderContext.activeCubeFace = activeCubeFace;
  35195. renderContext.activeMipmapLevel = activeMipmapLevel;
  35196. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35197. //
  35198. this._background.update( sceneRef, renderList, renderContext );
  35199. //
  35200. this.backend.beginRender( renderContext );
  35201. // process render lists
  35202. const {
  35203. bundles,
  35204. lightsNode,
  35205. transparentDoublePass: transparentDoublePassObjects,
  35206. transparent: transparentObjects,
  35207. opaque: opaqueObjects
  35208. } = renderList;
  35209. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35210. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35211. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35212. // finish render pass
  35213. this.backend.finishRender( renderContext );
  35214. // restore render tree
  35215. nodeFrame.renderId = previousRenderId;
  35216. this._currentRenderContext = previousRenderContext;
  35217. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35218. //
  35219. if ( frameBufferTarget !== null ) {
  35220. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  35221. const quad = this._quad;
  35222. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35223. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35224. quad.material.needsUpdate = true;
  35225. }
  35226. this._renderScene( quad, quad.camera, false );
  35227. }
  35228. //
  35229. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  35230. //
  35231. return renderContext;
  35232. }
  35233. /**
  35234. * Returns the maximum available anisotropy for texture filtering.
  35235. *
  35236. * @return {Number} The maximum available anisotropy.
  35237. */
  35238. getMaxAnisotropy() {
  35239. return this.backend.getMaxAnisotropy();
  35240. }
  35241. /**
  35242. * Returns the active cube face.
  35243. *
  35244. * @return {Number} The active cube face.
  35245. */
  35246. getActiveCubeFace() {
  35247. return this._activeCubeFace;
  35248. }
  35249. /**
  35250. * Returns the active mipmap level.
  35251. *
  35252. * @return {Number} The active mipmap level.
  35253. */
  35254. getActiveMipmapLevel() {
  35255. return this._activeMipmapLevel;
  35256. }
  35257. /**
  35258. * Applications are advised to always define the animation loop
  35259. * with this method and not manually with `requestAnimationFrame()`
  35260. * for best compatibility.
  35261. *
  35262. * @async
  35263. * @param {Function} callback - The application's animation loop.
  35264. * @return {Promise} A Promise that resolves when the set has been executed.
  35265. */
  35266. async setAnimationLoop( callback ) {
  35267. if ( this._initialized === false ) await this.init();
  35268. this._animation.setAnimationLoop( callback );
  35269. }
  35270. /**
  35271. * Can be used to transfer buffer data from a storage buffer attribute
  35272. * from the GPU to the CPU in context of compute shaders.
  35273. *
  35274. * @async
  35275. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  35276. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  35277. */
  35278. async getArrayBufferAsync( attribute ) {
  35279. return await this.backend.getArrayBufferAsync( attribute );
  35280. }
  35281. /**
  35282. * Returns the rendering context.
  35283. *
  35284. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  35285. */
  35286. getContext() {
  35287. return this.backend.getContext();
  35288. }
  35289. /**
  35290. * Returns the pixel ratio.
  35291. *
  35292. * @return {Number} The pixel ratio.
  35293. */
  35294. getPixelRatio() {
  35295. return this._pixelRatio;
  35296. }
  35297. /**
  35298. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  35299. *
  35300. * @param {Vector2} target - The method writes the result in this target object.
  35301. * @return {Vector2} The drawing buffer size.
  35302. */
  35303. getDrawingBufferSize( target ) {
  35304. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  35305. }
  35306. /**
  35307. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  35308. *
  35309. * @param {Vector2} target - The method writes the result in this target object.
  35310. * @return {Vector2} The drawing buffer size.
  35311. */
  35312. getSize( target ) {
  35313. return target.set( this._width, this._height );
  35314. }
  35315. /**
  35316. * Sets the given pixel ration and resizes the canvas if necessary.
  35317. *
  35318. * @param {Number} [value=1] - The pixel ratio.
  35319. */
  35320. setPixelRatio( value = 1 ) {
  35321. if ( this._pixelRatio === value ) return;
  35322. this._pixelRatio = value;
  35323. this.setSize( this._width, this._height, false );
  35324. }
  35325. /**
  35326. * This method allows to define the drawing buffer size by specifying
  35327. * width, height and pixel ratio all at once. The size of the drawing
  35328. * buffer is computed with this formula:
  35329. * ````
  35330. * size.x = width * pixelRatio;
  35331. * size.y = height * pixelRatio;
  35332. *```
  35333. *
  35334. * @param {Number} width - The width in logical pixels.
  35335. * @param {Number} height - The height in logical pixels.
  35336. * @param {Number} pixelRatio - The pixel ratio.
  35337. */
  35338. setDrawingBufferSize( width, height, pixelRatio ) {
  35339. this._width = width;
  35340. this._height = height;
  35341. this._pixelRatio = pixelRatio;
  35342. this.domElement.width = Math.floor( width * pixelRatio );
  35343. this.domElement.height = Math.floor( height * pixelRatio );
  35344. this.setViewport( 0, 0, width, height );
  35345. if ( this._initialized ) this.backend.updateSize();
  35346. }
  35347. /**
  35348. * Sets the size of the renderer.
  35349. *
  35350. * @param {Number} width - The width in logical pixels.
  35351. * @param {Number} height - The height in logical pixels.
  35352. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  35353. */
  35354. setSize( width, height, updateStyle = true ) {
  35355. this._width = width;
  35356. this._height = height;
  35357. this.domElement.width = Math.floor( width * this._pixelRatio );
  35358. this.domElement.height = Math.floor( height * this._pixelRatio );
  35359. if ( updateStyle === true ) {
  35360. this.domElement.style.width = width + 'px';
  35361. this.domElement.style.height = height + 'px';
  35362. }
  35363. this.setViewport( 0, 0, width, height );
  35364. if ( this._initialized ) this.backend.updateSize();
  35365. }
  35366. /**
  35367. * Defines a manual sort function for the opaque render list.
  35368. * Pass `null` to use the default sort.
  35369. *
  35370. * @param {Function} method - The sort function.
  35371. */
  35372. setOpaqueSort( method ) {
  35373. this._opaqueSort = method;
  35374. }
  35375. /**
  35376. * Defines a manual sort function for the transparent render list.
  35377. * Pass `null` to use the default sort.
  35378. *
  35379. * @param {Function} method - The sort function.
  35380. */
  35381. setTransparentSort( method ) {
  35382. this._transparentSort = method;
  35383. }
  35384. /**
  35385. * Returns the scissor rectangle.
  35386. *
  35387. * @param {Vector4} target - The method writes the result in this target object.
  35388. * @return {Vector4} The scissor rectangle.
  35389. */
  35390. getScissor( target ) {
  35391. const scissor = this._scissor;
  35392. target.x = scissor.x;
  35393. target.y = scissor.y;
  35394. target.width = scissor.width;
  35395. target.height = scissor.height;
  35396. return target;
  35397. }
  35398. /**
  35399. * Defines the scissor rectangle.
  35400. *
  35401. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  35402. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  35403. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  35404. * @param {Number} width - The width of the scissor box in logical pixel unit.
  35405. * @param {Number} height - The height of the scissor box in logical pixel unit.
  35406. */
  35407. setScissor( x, y, width, height ) {
  35408. const scissor = this._scissor;
  35409. if ( x.isVector4 ) {
  35410. scissor.copy( x );
  35411. } else {
  35412. scissor.set( x, y, width, height );
  35413. }
  35414. }
  35415. /**
  35416. * Returns the scissor test value.
  35417. *
  35418. * @return {Boolean} Whether the scissor test should be enabled or not.
  35419. */
  35420. getScissorTest() {
  35421. return this._scissorTest;
  35422. }
  35423. /**
  35424. * Defines the scissor test.
  35425. *
  35426. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  35427. */
  35428. setScissorTest( boolean ) {
  35429. this._scissorTest = boolean;
  35430. this.backend.setScissorTest( boolean );
  35431. }
  35432. /**
  35433. * Returns the viewport definition.
  35434. *
  35435. * @param {Vector4} target - The method writes the result in this target object.
  35436. * @return {Vector4} The viewport definition.
  35437. */
  35438. getViewport( target ) {
  35439. return target.copy( this._viewport );
  35440. }
  35441. /**
  35442. * Defines the viewport.
  35443. *
  35444. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35445. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35446. * @param {Number} width - The width of the viewport in logical pixel unit.
  35447. * @param {Number} height - The height of the viewport in logical pixel unit.
  35448. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  35449. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  35450. */
  35451. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  35452. const viewport = this._viewport;
  35453. if ( x.isVector4 ) {
  35454. viewport.copy( x );
  35455. } else {
  35456. viewport.set( x, y, width, height );
  35457. }
  35458. viewport.minDepth = minDepth;
  35459. viewport.maxDepth = maxDepth;
  35460. }
  35461. /**
  35462. * Returns the clear color.
  35463. *
  35464. * @param {Color} target - The method writes the result in this target object.
  35465. * @return {Color} The clear color.
  35466. */
  35467. getClearColor( target ) {
  35468. return target.copy( this._clearColor );
  35469. }
  35470. /**
  35471. * Defines the clear color and optionally the clear alpha.
  35472. *
  35473. * @param {Color} color - The clear color.
  35474. * @param {Number} [alpha=1] - The clear alpha.
  35475. */
  35476. setClearColor( color, alpha = 1 ) {
  35477. this._clearColor.set( color );
  35478. this._clearColor.a = alpha;
  35479. }
  35480. /**
  35481. * Returns the clear alpha.
  35482. *
  35483. * @return {Number} The clear alpha.
  35484. */
  35485. getClearAlpha() {
  35486. return this._clearColor.a;
  35487. }
  35488. /**
  35489. * Defines the clear alpha.
  35490. *
  35491. * @param {Number} alpha - The clear alpha.
  35492. */
  35493. setClearAlpha( alpha ) {
  35494. this._clearColor.a = alpha;
  35495. }
  35496. /**
  35497. * Returns the clear depth.
  35498. *
  35499. * @return {Number} The clear depth.
  35500. */
  35501. getClearDepth() {
  35502. return this._clearDepth;
  35503. }
  35504. /**
  35505. * Defines the clear depth.
  35506. *
  35507. * @param {Number} depth - The clear depth.
  35508. */
  35509. setClearDepth( depth ) {
  35510. this._clearDepth = depth;
  35511. }
  35512. /**
  35513. * Returns the clear stencil.
  35514. *
  35515. * @return {Number} The clear stencil.
  35516. */
  35517. getClearStencil() {
  35518. return this._clearStencil;
  35519. }
  35520. /**
  35521. * Defines the clear stencil.
  35522. *
  35523. * @param {Number} stencil - The clear stencil.
  35524. */
  35525. setClearStencil( stencil ) {
  35526. this._clearStencil = stencil;
  35527. }
  35528. /**
  35529. * This method performs an occlusion query for the given 3D object.
  35530. * It returns `true` if the given 3D object is fully occluded by other
  35531. * 3D objects in the scene.
  35532. *
  35533. * @param {Object3D} object - The 3D object to test.
  35534. * @return {Boolean} Whether the 3D object is fully occluded or not.
  35535. */
  35536. isOccluded( object ) {
  35537. const renderContext = this._currentRenderContext;
  35538. return renderContext && this.backend.isOccluded( renderContext, object );
  35539. }
  35540. /**
  35541. * Performs a manual clear operation. This method ignores `autoClear` properties.
  35542. *
  35543. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35544. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35545. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35546. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35547. * Only returned when the renderer has not been initialized.
  35548. */
  35549. clear( color = true, depth = true, stencil = true ) {
  35550. if ( this._initialized === false ) {
  35551. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  35552. return this.clearAsync( color, depth, stencil );
  35553. }
  35554. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35555. let renderContext = null;
  35556. if ( renderTarget !== null ) {
  35557. this._textures.updateRenderTarget( renderTarget );
  35558. const renderTargetData = this._textures.get( renderTarget );
  35559. renderContext = this._renderContexts.getForClear( renderTarget );
  35560. renderContext.textures = renderTargetData.textures;
  35561. renderContext.depthTexture = renderTargetData.depthTexture;
  35562. renderContext.width = renderTargetData.width;
  35563. renderContext.height = renderTargetData.height;
  35564. renderContext.renderTarget = renderTarget;
  35565. renderContext.depth = renderTarget.depthBuffer;
  35566. renderContext.stencil = renderTarget.stencilBuffer;
  35567. }
  35568. // #30329
  35569. renderContext.clearColorValue = this._clearColor;
  35570. this.backend.clear( color, depth, stencil, renderContext );
  35571. if ( renderTarget !== null && this._renderTarget === null ) {
  35572. // If a color space transform or tone mapping is required,
  35573. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  35574. const quad = this._quad;
  35575. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35576. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35577. quad.material.needsUpdate = true;
  35578. }
  35579. this._renderScene( quad, quad.camera, false );
  35580. }
  35581. }
  35582. /**
  35583. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  35584. *
  35585. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35586. * Only returned when the renderer has not been initialized.
  35587. */
  35588. clearColor() {
  35589. return this.clear( true, false, false );
  35590. }
  35591. /**
  35592. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  35593. *
  35594. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35595. * Only returned when the renderer has not been initialized.
  35596. */
  35597. clearDepth() {
  35598. return this.clear( false, true, false );
  35599. }
  35600. /**
  35601. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  35602. *
  35603. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35604. * Only returned when the renderer has not been initialized.
  35605. */
  35606. clearStencil() {
  35607. return this.clear( false, false, true );
  35608. }
  35609. /**
  35610. * Async version of {@link module:Renderer~Renderer#clear}.
  35611. *
  35612. * @async
  35613. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35614. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35615. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35616. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35617. */
  35618. async clearAsync( color = true, depth = true, stencil = true ) {
  35619. if ( this._initialized === false ) await this.init();
  35620. this.clear( color, depth, stencil );
  35621. }
  35622. /**
  35623. * Async version of {@link module:Renderer~Renderer#clearColor}.
  35624. *
  35625. * @async
  35626. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35627. */
  35628. async clearColorAsync() {
  35629. this.clearAsync( true, false, false );
  35630. }
  35631. /**
  35632. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  35633. *
  35634. * @async
  35635. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35636. */
  35637. async clearDepthAsync() {
  35638. this.clearAsync( false, true, false );
  35639. }
  35640. /**
  35641. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  35642. *
  35643. * @async
  35644. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35645. */
  35646. async clearStencilAsync() {
  35647. this.clearAsync( false, false, true );
  35648. }
  35649. /**
  35650. * The current output tone mapping of the renderer. When a render target is set,
  35651. * the output tone mapping is always `NoToneMapping`.
  35652. *
  35653. * @type {Number}
  35654. */
  35655. get currentToneMapping() {
  35656. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  35657. }
  35658. /**
  35659. * The current output color space of the renderer. When a render target is set,
  35660. * the output color space is always `LinearSRGBColorSpace`.
  35661. *
  35662. * @type {String}
  35663. */
  35664. get currentColorSpace() {
  35665. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  35666. }
  35667. /**
  35668. * Frees all internal resources of the renderer. Call this method if the renderer
  35669. * is no longer in use by your app.
  35670. */
  35671. dispose() {
  35672. this.info.dispose();
  35673. this.backend.dispose();
  35674. this._animation.dispose();
  35675. this._objects.dispose();
  35676. this._pipelines.dispose();
  35677. this._nodes.dispose();
  35678. this._bindings.dispose();
  35679. this._renderLists.dispose();
  35680. this._renderContexts.dispose();
  35681. this._textures.dispose();
  35682. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  35683. if ( queryPool !== null ) queryPool.dispose();
  35684. } );
  35685. this.setRenderTarget( null );
  35686. this.setAnimationLoop( null );
  35687. }
  35688. /**
  35689. * Sets the given render target. Calling this method means the renderer does not
  35690. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  35691. * Use `null` as the first argument to reset the state.
  35692. *
  35693. * @param {RenderTarget?} renderTarget - The render target to set.
  35694. * @param {Number} [activeCubeFace=0] - The active cube face.
  35695. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  35696. */
  35697. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  35698. this._renderTarget = renderTarget;
  35699. this._activeCubeFace = activeCubeFace;
  35700. this._activeMipmapLevel = activeMipmapLevel;
  35701. }
  35702. /**
  35703. * Returns the current render target.
  35704. *
  35705. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  35706. */
  35707. getRenderTarget() {
  35708. return this._renderTarget;
  35709. }
  35710. /**
  35711. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  35712. *
  35713. * @callback renderObjectFunction
  35714. * @param {Object3D} object - The 3D object.
  35715. * @param {Scene} scene - The scene the 3D object belongs to.
  35716. * @param {Camera} camera - The camera the object should be rendered with.
  35717. * @param {BufferGeometry} geometry - The object's geometry.
  35718. * @param {Material} material - The object's material.
  35719. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35720. * @param {LightsNode} lightsNode - The current lights node.
  35721. * @param {ClippingContext} clippingContext - The clipping context.
  35722. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35723. */
  35724. /**
  35725. * Sets the given render object function. Calling this method overwrites the default implementation
  35726. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  35727. * if you want to modify the way objects are rendered. For example you can define things like "every
  35728. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  35729. * The custom function must always call `renderObject()` in its implementation.
  35730. *
  35731. * Use `null` as the first argument to reset the state.
  35732. *
  35733. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  35734. */
  35735. setRenderObjectFunction( renderObjectFunction ) {
  35736. this._renderObjectFunction = renderObjectFunction;
  35737. }
  35738. /**
  35739. * Returns the current render object function.
  35740. *
  35741. * @return {Function?} The current render object function. Returns `null` if no function is set.
  35742. */
  35743. getRenderObjectFunction() {
  35744. return this._renderObjectFunction;
  35745. }
  35746. /**
  35747. * Execute a single or an array of compute nodes. This method can only be called
  35748. * if the renderer has been initialized.
  35749. *
  35750. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35751. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  35752. */
  35753. compute( computeNodes ) {
  35754. if ( this._isDeviceLost === true ) return;
  35755. if ( this._initialized === false ) {
  35756. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  35757. return this.computeAsync( computeNodes );
  35758. }
  35759. //
  35760. const nodeFrame = this._nodes.nodeFrame;
  35761. const previousRenderId = nodeFrame.renderId;
  35762. //
  35763. this.info.calls ++;
  35764. this.info.compute.calls ++;
  35765. this.info.compute.frameCalls ++;
  35766. nodeFrame.renderId = this.info.calls;
  35767. //
  35768. const backend = this.backend;
  35769. const pipelines = this._pipelines;
  35770. const bindings = this._bindings;
  35771. const nodes = this._nodes;
  35772. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  35773. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  35774. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  35775. }
  35776. backend.beginCompute( computeNodes );
  35777. for ( const computeNode of computeList ) {
  35778. // onInit
  35779. if ( pipelines.has( computeNode ) === false ) {
  35780. const dispose = () => {
  35781. computeNode.removeEventListener( 'dispose', dispose );
  35782. pipelines.delete( computeNode );
  35783. bindings.delete( computeNode );
  35784. nodes.delete( computeNode );
  35785. };
  35786. computeNode.addEventListener( 'dispose', dispose );
  35787. //
  35788. const onInitFn = computeNode.onInitFunction;
  35789. if ( onInitFn !== null ) {
  35790. onInitFn.call( computeNode, { renderer: this } );
  35791. }
  35792. }
  35793. nodes.updateForCompute( computeNode );
  35794. bindings.updateForCompute( computeNode );
  35795. const computeBindings = bindings.getForCompute( computeNode );
  35796. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  35797. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  35798. }
  35799. backend.finishCompute( computeNodes );
  35800. //
  35801. nodeFrame.renderId = previousRenderId;
  35802. }
  35803. /**
  35804. * Execute a single or an array of compute nodes.
  35805. *
  35806. * @async
  35807. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35808. * @return {Promise} A Promise that resolve when the compute has finished.
  35809. */
  35810. async computeAsync( computeNodes ) {
  35811. if ( this._initialized === false ) await this.init();
  35812. this.compute( computeNodes );
  35813. }
  35814. /**
  35815. * Checks if the given feature is supported by the selected backend.
  35816. *
  35817. * @async
  35818. * @param {String} name - The feature's name.
  35819. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  35820. */
  35821. async hasFeatureAsync( name ) {
  35822. if ( this._initialized === false ) await this.init();
  35823. return this.backend.hasFeature( name );
  35824. }
  35825. async resolveTimestampsAsync( type = 'render' ) {
  35826. if ( this._initialized === false ) await this.init();
  35827. return this.backend.resolveTimestampsAsync( type );
  35828. }
  35829. /**
  35830. * Checks if the given feature is supported by the selected backend. If the
  35831. * renderer has not been initialized, this method always returns `false`.
  35832. *
  35833. * @param {String} name - The feature's name.
  35834. * @return {Boolean} Whether the feature is supported or not.
  35835. */
  35836. hasFeature( name ) {
  35837. if ( this._initialized === false ) {
  35838. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  35839. return false;
  35840. }
  35841. return this.backend.hasFeature( name );
  35842. }
  35843. /**
  35844. * Returns `true` when the renderer has been initialized.
  35845. *
  35846. * @return {Boolean} Whether the renderer has been initialized or not.
  35847. */
  35848. hasInitialized() {
  35849. return this._initialized;
  35850. }
  35851. /**
  35852. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35853. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35854. *
  35855. * @async
  35856. * @param {Texture} texture - The texture.
  35857. * @return {Promise} A Promise that resolves when the texture has been initialized.
  35858. */
  35859. async initTextureAsync( texture ) {
  35860. if ( this._initialized === false ) await this.init();
  35861. this._textures.updateTexture( texture );
  35862. }
  35863. /**
  35864. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35865. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35866. *
  35867. * This method can only be used if the renderer has been initialized.
  35868. *
  35869. * @param {Texture} texture - The texture.
  35870. */
  35871. initTexture( texture ) {
  35872. if ( this._initialized === false ) {
  35873. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  35874. }
  35875. this._textures.updateTexture( texture );
  35876. }
  35877. /**
  35878. * Copies the current bound framebuffer into the given texture.
  35879. *
  35880. * @param {FramebufferTexture} framebufferTexture - The texture.
  35881. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  35882. */
  35883. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  35884. if ( rectangle !== null ) {
  35885. if ( rectangle.isVector2 ) {
  35886. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  35887. } else if ( rectangle.isVector4 ) {
  35888. rectangle = _vector4.copy( rectangle ).floor();
  35889. } else {
  35890. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  35891. return;
  35892. }
  35893. } else {
  35894. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  35895. }
  35896. //
  35897. let renderContext = this._currentRenderContext;
  35898. let renderTarget;
  35899. if ( renderContext !== null ) {
  35900. renderTarget = renderContext.renderTarget;
  35901. } else {
  35902. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35903. if ( renderTarget !== null ) {
  35904. this._textures.updateRenderTarget( renderTarget );
  35905. renderContext = this._textures.get( renderTarget );
  35906. }
  35907. }
  35908. //
  35909. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  35910. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  35911. }
  35912. /**
  35913. * Copies data of source texture into a destination texture.
  35914. *
  35915. * @param {Texture} srcTexture - The source texture.
  35916. * @param {Texture} dstTexture - The destination texture.
  35917. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  35918. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  35919. * @param {Number} level - The mipmap level to copy.
  35920. */
  35921. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  35922. this._textures.updateTexture( srcTexture );
  35923. this._textures.updateTexture( dstTexture );
  35924. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  35925. }
  35926. /**
  35927. * Reads pixel data from the given render target.
  35928. *
  35929. * @async
  35930. * @param {RenderTarget} renderTarget - The render target to read from.
  35931. * @param {Number} x - The `x` coordinate of the copy region's origin.
  35932. * @param {Number} y - The `y` coordinate of the copy region's origin.
  35933. * @param {Number} width - The width of the copy region.
  35934. * @param {Number} height - The height of the copy region.
  35935. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  35936. * @param {Number} [faceIndex=0] - The active cube face index.
  35937. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  35938. */
  35939. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  35940. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  35941. }
  35942. /**
  35943. * Analyzes the given 3D object's hierarchy and builds render lists from the
  35944. * processed hierarchy.
  35945. *
  35946. * @param {Object3D} object - The 3D object to process (usually a scene).
  35947. * @param {Camera} camera - The camera the object is rendered with.
  35948. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  35949. * @param {RenderList} renderList - The current render list.
  35950. * @param {ClippingContext} clippingContext - The current clipping context.
  35951. */
  35952. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  35953. if ( object.visible === false ) return;
  35954. const visible = object.layers.test( camera.layers );
  35955. if ( visible ) {
  35956. if ( object.isGroup ) {
  35957. groupOrder = object.renderOrder;
  35958. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  35959. } else if ( object.isLOD ) {
  35960. if ( object.autoUpdate === true ) object.update( camera );
  35961. } else if ( object.isLight ) {
  35962. renderList.pushLight( object );
  35963. } else if ( object.isSprite ) {
  35964. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  35965. if ( this.sortObjects === true ) {
  35966. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  35967. }
  35968. const { geometry, material } = object;
  35969. if ( material.visible ) {
  35970. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35971. }
  35972. }
  35973. } else if ( object.isLineLoop ) {
  35974. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  35975. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  35976. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  35977. const { geometry, material } = object;
  35978. if ( this.sortObjects === true ) {
  35979. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  35980. _vector4
  35981. .copy( geometry.boundingSphere.center )
  35982. .applyMatrix4( object.matrixWorld )
  35983. .applyMatrix4( _projScreenMatrix );
  35984. }
  35985. if ( Array.isArray( material ) ) {
  35986. const groups = geometry.groups;
  35987. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  35988. const group = groups[ i ];
  35989. const groupMaterial = material[ group.materialIndex ];
  35990. if ( groupMaterial && groupMaterial.visible ) {
  35991. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  35992. }
  35993. }
  35994. } else if ( material.visible ) {
  35995. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35996. }
  35997. }
  35998. }
  35999. }
  36000. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  36001. const baseRenderList = renderList;
  36002. // replace render list
  36003. renderList = this._renderLists.get( object, camera );
  36004. renderList.begin();
  36005. baseRenderList.pushBundle( {
  36006. bundleGroup: object,
  36007. camera,
  36008. renderList,
  36009. } );
  36010. renderList.finish();
  36011. }
  36012. const children = object.children;
  36013. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36014. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  36015. }
  36016. }
  36017. /**
  36018. * Renders the given render bundles.
  36019. *
  36020. * @private
  36021. * @param {Array<Object>} bundles - Array with render bundle data.
  36022. * @param {Scene} sceneRef - The scene the render bundles belong to.
  36023. * @param {LightsNode} lightsNode - The current lights node.
  36024. */
  36025. _renderBundles( bundles, sceneRef, lightsNode ) {
  36026. for ( const bundle of bundles ) {
  36027. this._renderBundle( bundle, sceneRef, lightsNode );
  36028. }
  36029. }
  36030. /**
  36031. * Renders the transparent objects from the given render lists.
  36032. *
  36033. * @private
  36034. * @param {Array<Object>} renderList - The transparent render list.
  36035. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  36036. * @param {Camera} camera - The camera the render list should be rendered with.
  36037. * @param {Scene} scene - The scene the render list belongs to.
  36038. * @param {LightsNode} lightsNode - The current lights node.
  36039. */
  36040. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  36041. if ( doublePassList.length > 0 ) {
  36042. // render back side
  36043. for ( const { material } of doublePassList ) {
  36044. material.side = BackSide;
  36045. }
  36046. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  36047. // render front side
  36048. for ( const { material } of doublePassList ) {
  36049. material.side = FrontSide;
  36050. }
  36051. this._renderObjects( renderList, camera, scene, lightsNode );
  36052. // restore
  36053. for ( const { material } of doublePassList ) {
  36054. material.side = DoubleSide;
  36055. }
  36056. } else {
  36057. this._renderObjects( renderList, camera, scene, lightsNode );
  36058. }
  36059. }
  36060. /**
  36061. * Renders the objects from the given render list.
  36062. *
  36063. * @private
  36064. * @param {Array<Object>} renderList - The render list.
  36065. * @param {Camera} camera - The camera the render list should be rendered with.
  36066. * @param {Scene} scene - The scene the render list belongs to.
  36067. * @param {LightsNode} lightsNode - The current lights node.
  36068. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36069. */
  36070. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  36071. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36072. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  36073. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  36074. }
  36075. }
  36076. /**
  36077. * This method represents the default render object function that manages the render lifecycle
  36078. * of the object.
  36079. *
  36080. * @param {Object3D} object - The 3D object.
  36081. * @param {Scene} scene - The scene the 3D object belongs to.
  36082. * @param {Camera} camera - The camera the object should be rendered with.
  36083. * @param {BufferGeometry} geometry - The object's geometry.
  36084. * @param {Material} material - The object's material.
  36085. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36086. * @param {LightsNode} lightsNode - The current lights node.
  36087. * @param {ClippingContext} clippingContext - The clipping context.
  36088. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36089. */
  36090. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  36091. let overridePositionNode;
  36092. let overrideColorNode;
  36093. let overrideDepthNode;
  36094. //
  36095. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36096. //
  36097. if ( scene.overrideMaterial !== null ) {
  36098. const overrideMaterial = scene.overrideMaterial;
  36099. if ( material.positionNode && material.positionNode.isNode ) {
  36100. overridePositionNode = overrideMaterial.positionNode;
  36101. overrideMaterial.positionNode = material.positionNode;
  36102. }
  36103. overrideMaterial.alphaTest = material.alphaTest;
  36104. overrideMaterial.alphaMap = material.alphaMap;
  36105. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  36106. if ( overrideMaterial.isShadowPassMaterial ) {
  36107. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36108. if ( material.depthNode && material.depthNode.isNode ) {
  36109. overrideDepthNode = overrideMaterial.depthNode;
  36110. overrideMaterial.depthNode = material.depthNode;
  36111. }
  36112. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  36113. overrideColorNode = overrideMaterial.colorNode;
  36114. overrideMaterial.colorNode = material.castShadowNode;
  36115. }
  36116. }
  36117. material = overrideMaterial;
  36118. }
  36119. //
  36120. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36121. material.side = BackSide;
  36122. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  36123. material.side = FrontSide;
  36124. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  36125. material.side = DoubleSide;
  36126. } else {
  36127. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  36128. }
  36129. //
  36130. if ( overridePositionNode !== undefined ) {
  36131. scene.overrideMaterial.positionNode = overridePositionNode;
  36132. }
  36133. if ( overrideDepthNode !== undefined ) {
  36134. scene.overrideMaterial.depthNode = overrideDepthNode;
  36135. }
  36136. if ( overrideColorNode !== undefined ) {
  36137. scene.overrideMaterial.colorNode = overrideColorNode;
  36138. }
  36139. //
  36140. object.onAfterRender( this, scene, camera, geometry, material, group );
  36141. }
  36142. /**
  36143. * This method represents the default `_handleObjectFunction` implementation which creates
  36144. * a render object from the given data and performs the draw command with the selected backend.
  36145. *
  36146. * @private
  36147. * @param {Object3D} object - The 3D object.
  36148. * @param {Material} material - The object's material.
  36149. * @param {Scene} scene - The scene the 3D object belongs to.
  36150. * @param {Camera} camera - The camera the object should be rendered with.
  36151. * @param {LightsNode} lightsNode - The current lights node.
  36152. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36153. * @param {ClippingContext} clippingContext - The clipping context.
  36154. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36155. */
  36156. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36157. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36158. renderObject.drawRange = object.geometry.drawRange;
  36159. renderObject.group = group;
  36160. //
  36161. const needsRefresh = this._nodes.needsRefresh( renderObject );
  36162. if ( needsRefresh ) {
  36163. this._nodes.updateBefore( renderObject );
  36164. this._geometries.updateForRender( renderObject );
  36165. this._nodes.updateForRender( renderObject );
  36166. this._bindings.updateForRender( renderObject );
  36167. }
  36168. this._pipelines.updateForRender( renderObject );
  36169. //
  36170. if ( this._currentRenderBundle !== null ) {
  36171. const renderBundleData = this.backend.get( this._currentRenderBundle );
  36172. renderBundleData.renderObjects.push( renderObject );
  36173. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  36174. }
  36175. this.backend.draw( renderObject, this.info );
  36176. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  36177. }
  36178. /**
  36179. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  36180. * Used in `compileAsync()`.
  36181. *
  36182. * @private
  36183. * @param {Object3D} object - The 3D object.
  36184. * @param {Material} material - The object's material.
  36185. * @param {Scene} scene - The scene the 3D object belongs to.
  36186. * @param {Camera} camera - The camera the object should be rendered with.
  36187. * @param {LightsNode} lightsNode - The current lights node.
  36188. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36189. * @param {ClippingContext} clippingContext - The clipping context.
  36190. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36191. */
  36192. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36193. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36194. renderObject.drawRange = object.geometry.drawRange;
  36195. renderObject.group = group;
  36196. //
  36197. this._nodes.updateBefore( renderObject );
  36198. this._geometries.updateForRender( renderObject );
  36199. this._nodes.updateForRender( renderObject );
  36200. this._bindings.updateForRender( renderObject );
  36201. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36202. this._nodes.updateAfter( renderObject );
  36203. }
  36204. /**
  36205. * Alias for `compileAsync()`.
  36206. *
  36207. * @method
  36208. * @param {Object3D} scene - The scene or 3D object to precompile.
  36209. * @param {Camera} camera - The camera that is used to render the scene.
  36210. * @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.
  36211. * @return {Promise} A Promise that resolves when the compile has been finished.
  36212. */
  36213. get compile() {
  36214. return this.compileAsync;
  36215. }
  36216. }
  36217. /**
  36218. * A binding represents the connection between a resource (like a texture, sampler
  36219. * or uniform buffer) and the resource definition in a shader stage.
  36220. *
  36221. * This module is an abstract base class for all concrete bindings types.
  36222. *
  36223. * @abstract
  36224. * @private
  36225. */
  36226. class Binding {
  36227. /**
  36228. * Constructs a new binding.
  36229. *
  36230. * @param {String} [name=''] - The binding's name.
  36231. */
  36232. constructor( name = '' ) {
  36233. /**
  36234. * The binding's name.
  36235. *
  36236. * @type {String}
  36237. */
  36238. this.name = name;
  36239. /**
  36240. * A bitmask that defines in what shader stages the
  36241. * binding's resource is accessible.
  36242. *
  36243. * @type {Number}
  36244. */
  36245. this.visibility = 0;
  36246. }
  36247. /**
  36248. * Makes sure binding's resource is visible for the given shader stage.
  36249. *
  36250. * @param {Number} visibility - The shader stage.
  36251. */
  36252. setVisibility( visibility ) {
  36253. this.visibility |= visibility;
  36254. }
  36255. /**
  36256. * Clones the binding.
  36257. *
  36258. * @return {Binding} The cloned binding.
  36259. */
  36260. clone() {
  36261. return Object.assign( new this.constructor(), this );
  36262. }
  36263. }
  36264. /** @module BufferUtils **/
  36265. /**
  36266. * This function is usually called with the length in bytes of an array buffer.
  36267. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  36268. *
  36269. * @function
  36270. * @param {Number} floatLength - The buffer length.
  36271. * @return {Number} The padded length.
  36272. */
  36273. function getFloatLength( floatLength ) {
  36274. // ensure chunk size alignment (STD140 layout)
  36275. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36276. }
  36277. /**
  36278. * Represents a buffer binding type.
  36279. *
  36280. * @private
  36281. * @abstract
  36282. * @augments Binding
  36283. */
  36284. class Buffer extends Binding {
  36285. /**
  36286. * Constructs a new buffer.
  36287. *
  36288. * @param {String} name - The buffer's name.
  36289. * @param {TypedArray} [buffer=null] - The buffer.
  36290. */
  36291. constructor( name, buffer = null ) {
  36292. super( name );
  36293. /**
  36294. * This flag can be used for type testing.
  36295. *
  36296. * @type {Boolean}
  36297. * @readonly
  36298. * @default true
  36299. */
  36300. this.isBuffer = true;
  36301. /**
  36302. * The bytes per element.
  36303. *
  36304. * @type {Number}
  36305. */
  36306. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36307. /**
  36308. * A reference to the internal buffer.
  36309. *
  36310. * @private
  36311. * @type {TypedArray}
  36312. */
  36313. this._buffer = buffer;
  36314. }
  36315. /**
  36316. * The buffer's byte length.
  36317. *
  36318. * @type {Number}
  36319. * @readonly
  36320. */
  36321. get byteLength() {
  36322. return getFloatLength( this._buffer.byteLength );
  36323. }
  36324. /**
  36325. * A reference to the internal buffer.
  36326. *
  36327. * @type {Float32Array}
  36328. * @readonly
  36329. */
  36330. get buffer() {
  36331. return this._buffer;
  36332. }
  36333. /**
  36334. * Updates the binding.
  36335. *
  36336. * @return {Boolean} Whether the buffer has been updated and must be
  36337. * uploaded to the GPU.
  36338. */
  36339. update() {
  36340. return true;
  36341. }
  36342. }
  36343. /**
  36344. * Represents a uniform buffer binding type.
  36345. *
  36346. * @private
  36347. * @augments Buffer
  36348. */
  36349. class UniformBuffer extends Buffer {
  36350. /**
  36351. * Constructs a new uniform buffer.
  36352. *
  36353. * @param {String} name - The buffer's name.
  36354. * @param {TypedArray} [buffer=null] - The buffer.
  36355. */
  36356. constructor( name, buffer = null ) {
  36357. super( name, buffer );
  36358. /**
  36359. * This flag can be used for type testing.
  36360. *
  36361. * @type {Boolean}
  36362. * @readonly
  36363. * @default true
  36364. */
  36365. this.isUniformBuffer = true;
  36366. }
  36367. }
  36368. let _id$4 = 0;
  36369. /**
  36370. * A special form of uniform buffer binding type.
  36371. * It's buffer value is managed by a node object.
  36372. *
  36373. * @private
  36374. * @augments UniformBuffer
  36375. */
  36376. class NodeUniformBuffer extends UniformBuffer {
  36377. /**
  36378. * Constructs a new node-based uniform buffer.
  36379. *
  36380. * @param {BufferNode} nodeUniform - The uniform buffer node.
  36381. * @param {UniformGroupNode} groupNode - The uniform group node.
  36382. */
  36383. constructor( nodeUniform, groupNode ) {
  36384. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  36385. /**
  36386. * The uniform buffer node.
  36387. *
  36388. * @type {BufferNode}
  36389. */
  36390. this.nodeUniform = nodeUniform;
  36391. /**
  36392. * The uniform group node.
  36393. *
  36394. * @type {UniformGroupNode}
  36395. */
  36396. this.groupNode = groupNode;
  36397. }
  36398. /**
  36399. * The uniform buffer.
  36400. *
  36401. * @type {Float32Array}
  36402. */
  36403. get buffer() {
  36404. return this.nodeUniform.value;
  36405. }
  36406. }
  36407. /**
  36408. * This class represents a uniform buffer binding but with
  36409. * an API that allows to maintain individual uniform objects.
  36410. *
  36411. * @private
  36412. * @augments UniformBuffer
  36413. */
  36414. class UniformsGroup extends UniformBuffer {
  36415. /**
  36416. * Constructs a new uniforms group.
  36417. *
  36418. * @param {String} name - The group's name.
  36419. */
  36420. constructor( name ) {
  36421. super( name );
  36422. /**
  36423. * This flag can be used for type testing.
  36424. *
  36425. * @type {Boolean}
  36426. * @readonly
  36427. * @default true
  36428. */
  36429. this.isUniformsGroup = true;
  36430. /**
  36431. * An array with the raw uniform values.
  36432. *
  36433. * @private
  36434. * @type {Array<Number>?}
  36435. * @default null
  36436. */
  36437. this._values = null;
  36438. /**
  36439. * An array of uniform objects.
  36440. *
  36441. * The order of uniforms in this array must match the order of uniforms in the shader.
  36442. *
  36443. * @type {Array<Uniform>}
  36444. */
  36445. this.uniforms = [];
  36446. }
  36447. /**
  36448. * Adds a uniform to this group.
  36449. *
  36450. * @param {Uniform} uniform - The uniform to add.
  36451. * @return {UniformsGroup} A reference to this group.
  36452. */
  36453. addUniform( uniform ) {
  36454. this.uniforms.push( uniform );
  36455. return this;
  36456. }
  36457. /**
  36458. * Removes a uniform from this group.
  36459. *
  36460. * @param {Uniform} uniform - The uniform to remove.
  36461. * @return {UniformsGroup} A reference to this group.
  36462. */
  36463. removeUniform( uniform ) {
  36464. const index = this.uniforms.indexOf( uniform );
  36465. if ( index !== -1 ) {
  36466. this.uniforms.splice( index, 1 );
  36467. }
  36468. return this;
  36469. }
  36470. /**
  36471. * An array with the raw uniform values.
  36472. *
  36473. * @type {Array<Number>}
  36474. */
  36475. get values() {
  36476. if ( this._values === null ) {
  36477. this._values = Array.from( this.buffer );
  36478. }
  36479. return this._values;
  36480. }
  36481. /**
  36482. * A Float32 array buffer with the uniform values.
  36483. *
  36484. * @type {Float32Array}
  36485. */
  36486. get buffer() {
  36487. let buffer = this._buffer;
  36488. if ( buffer === null ) {
  36489. const byteLength = this.byteLength;
  36490. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36491. this._buffer = buffer;
  36492. }
  36493. return buffer;
  36494. }
  36495. /**
  36496. * The byte length of the buffer with correct buffer alignment.
  36497. *
  36498. * @type {Number}
  36499. */
  36500. get byteLength() {
  36501. let offset = 0; // global buffer offset in bytes
  36502. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36503. const uniform = this.uniforms[ i ];
  36504. const { boundary, itemSize } = uniform;
  36505. // offset within a single chunk in bytes
  36506. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36507. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36508. // conformance tests
  36509. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36510. // check for chunk overflow
  36511. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36512. } else if ( chunkOffset % boundary !== 0 ) {
  36513. // check for correct alignment
  36514. offset += ( chunkOffset % boundary );
  36515. }
  36516. uniform.offset = ( offset / this.bytesPerElement );
  36517. offset += ( itemSize * this.bytesPerElement );
  36518. }
  36519. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36520. }
  36521. /**
  36522. * Updates this group by updating each uniform object of
  36523. * the internal uniform list. The uniform objects check if their
  36524. * values has actually changed so this method only returns
  36525. * `true` if there is a real value change.
  36526. *
  36527. * @return {Boolean} Whether the uniforms have been updated and
  36528. * must be uploaded to the GPU.
  36529. */
  36530. update() {
  36531. let updated = false;
  36532. for ( const uniform of this.uniforms ) {
  36533. if ( this.updateByType( uniform ) === true ) {
  36534. updated = true;
  36535. }
  36536. }
  36537. return updated;
  36538. }
  36539. /**
  36540. * Updates a given uniform by calling an update method matching
  36541. * the uniforms type.
  36542. *
  36543. * @param {Uniform} uniform - The uniform to update.
  36544. * @return {Boolean} Whether the uniform has been updated or not.
  36545. */
  36546. updateByType( uniform ) {
  36547. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36548. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36549. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36550. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36551. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36552. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36553. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36554. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36555. }
  36556. /**
  36557. * Updates a given Number uniform.
  36558. *
  36559. * @param {NumberUniform} uniform - The Number uniform.
  36560. * @return {Boolean} Whether the uniform has been updated or not.
  36561. */
  36562. updateNumber( uniform ) {
  36563. let updated = false;
  36564. const a = this.values;
  36565. const v = uniform.getValue();
  36566. const offset = uniform.offset;
  36567. const type = uniform.getType();
  36568. if ( a[ offset ] !== v ) {
  36569. const b = this._getBufferForType( type );
  36570. b[ offset ] = a[ offset ] = v;
  36571. updated = true;
  36572. }
  36573. return updated;
  36574. }
  36575. /**
  36576. * Updates a given Vector2 uniform.
  36577. *
  36578. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  36579. * @return {Boolean} Whether the uniform has been updated or not.
  36580. */
  36581. updateVector2( uniform ) {
  36582. let updated = false;
  36583. const a = this.values;
  36584. const v = uniform.getValue();
  36585. const offset = uniform.offset;
  36586. const type = uniform.getType();
  36587. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36588. const b = this._getBufferForType( type );
  36589. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36590. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36591. updated = true;
  36592. }
  36593. return updated;
  36594. }
  36595. /**
  36596. * Updates a given Vector3 uniform.
  36597. *
  36598. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  36599. * @return {Boolean} Whether the uniform has been updated or not.
  36600. */
  36601. updateVector3( uniform ) {
  36602. let updated = false;
  36603. const a = this.values;
  36604. const v = uniform.getValue();
  36605. const offset = uniform.offset;
  36606. const type = uniform.getType();
  36607. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36608. const b = this._getBufferForType( type );
  36609. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36610. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36611. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36612. updated = true;
  36613. }
  36614. return updated;
  36615. }
  36616. /**
  36617. * Updates a given Vector4 uniform.
  36618. *
  36619. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  36620. * @return {Boolean} Whether the uniform has been updated or not.
  36621. */
  36622. updateVector4( uniform ) {
  36623. let updated = false;
  36624. const a = this.values;
  36625. const v = uniform.getValue();
  36626. const offset = uniform.offset;
  36627. const type = uniform.getType();
  36628. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36629. const b = this._getBufferForType( type );
  36630. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36631. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36632. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36633. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36634. updated = true;
  36635. }
  36636. return updated;
  36637. }
  36638. /**
  36639. * Updates a given Color uniform.
  36640. *
  36641. * @param {ColorUniform} uniform - The Color uniform.
  36642. * @return {Boolean} Whether the uniform has been updated or not.
  36643. */
  36644. updateColor( uniform ) {
  36645. let updated = false;
  36646. const a = this.values;
  36647. const c = uniform.getValue();
  36648. const offset = uniform.offset;
  36649. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36650. const b = this.buffer;
  36651. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36652. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36653. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36654. updated = true;
  36655. }
  36656. return updated;
  36657. }
  36658. /**
  36659. * Updates a given Matrix3 uniform.
  36660. *
  36661. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  36662. * @return {Boolean} Whether the uniform has been updated or not.
  36663. */
  36664. updateMatrix3( uniform ) {
  36665. let updated = false;
  36666. const a = this.values;
  36667. const e = uniform.getValue().elements;
  36668. const offset = uniform.offset;
  36669. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36670. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36671. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36672. const b = this.buffer;
  36673. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36674. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36675. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36676. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36677. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36678. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36679. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36680. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36681. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36682. updated = true;
  36683. }
  36684. return updated;
  36685. }
  36686. /**
  36687. * Updates a given Matrix4 uniform.
  36688. *
  36689. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  36690. * @return {Boolean} Whether the uniform has been updated or not.
  36691. */
  36692. updateMatrix4( uniform ) {
  36693. let updated = false;
  36694. const a = this.values;
  36695. const e = uniform.getValue().elements;
  36696. const offset = uniform.offset;
  36697. if ( arraysEqual( a, e, offset ) === false ) {
  36698. const b = this.buffer;
  36699. b.set( e, offset );
  36700. setArray( a, e, offset );
  36701. updated = true;
  36702. }
  36703. return updated;
  36704. }
  36705. /**
  36706. * Returns a typed array that matches the given data type.
  36707. *
  36708. * @param {String} type - The data type.
  36709. * @return {TypedArray} The typed array.
  36710. */
  36711. _getBufferForType( type ) {
  36712. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  36713. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  36714. return this.buffer;
  36715. }
  36716. }
  36717. /**
  36718. * Sets the values of the second array to the first array.
  36719. *
  36720. * @private
  36721. * @param {TypedArray} a - The first array.
  36722. * @param {TypedArray} b - The second array.
  36723. * @param {Number} offset - An index offset for the first array.
  36724. */
  36725. function setArray( a, b, offset ) {
  36726. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36727. a[ offset + i ] = b[ i ];
  36728. }
  36729. }
  36730. /**
  36731. * Returns `true` if the given arrays are equal.
  36732. *
  36733. * @private
  36734. * @param {TypedArray} a - The first array.
  36735. * @param {TypedArray} b - The second array.
  36736. * @param {Number} offset - An index offset for the first array.
  36737. * @return {Boolean} Whether the given arrays are equal or not.
  36738. */
  36739. function arraysEqual( a, b, offset ) {
  36740. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36741. if ( a[ offset + i ] !== b[ i ] ) return false;
  36742. }
  36743. return true;
  36744. }
  36745. let _id$3 = 0;
  36746. /**
  36747. * A special form of uniforms group that represents
  36748. * the individual uniforms as node-based uniforms.
  36749. *
  36750. * @private
  36751. * @augments UniformsGroup
  36752. */
  36753. class NodeUniformsGroup extends UniformsGroup {
  36754. /**
  36755. * Constructs a new node-based uniforms group.
  36756. *
  36757. * @param {String} name - The group's name.
  36758. * @param {UniformGroupNode} groupNode - The uniform group node.
  36759. */
  36760. constructor( name, groupNode ) {
  36761. super( name );
  36762. /**
  36763. * The group's ID.
  36764. *
  36765. * @type {Number}
  36766. */
  36767. this.id = _id$3 ++;
  36768. /**
  36769. * The uniform group node.
  36770. *
  36771. * @type {UniformGroupNode}
  36772. */
  36773. this.groupNode = groupNode;
  36774. /**
  36775. * This flag can be used for type testing.
  36776. *
  36777. * @type {Boolean}
  36778. * @readonly
  36779. * @default true
  36780. */
  36781. this.isNodeUniformsGroup = true;
  36782. }
  36783. }
  36784. let _id$2 = 0;
  36785. /**
  36786. * Represents a sampled texture binding type.
  36787. *
  36788. * @private
  36789. * @augments Binding
  36790. */
  36791. class SampledTexture extends Binding {
  36792. /**
  36793. * Constructs a new sampled texture.
  36794. *
  36795. * @param {String} name - The sampled texture's name.
  36796. * @param {Texture?} texture - The texture this binding is referring to.
  36797. */
  36798. constructor( name, texture ) {
  36799. super( name );
  36800. /**
  36801. * This identifier.
  36802. *
  36803. * @type {Number}
  36804. */
  36805. this.id = _id$2 ++;
  36806. /**
  36807. * The texture this binding is referring to.
  36808. *
  36809. * @type {Texture?}
  36810. */
  36811. this.texture = texture;
  36812. /**
  36813. * The binding's version.
  36814. *
  36815. * @type {Number}
  36816. */
  36817. this.version = texture ? texture.version : 0;
  36818. /**
  36819. * Whether the texture is a storage texture or not.
  36820. *
  36821. * @type {Boolean}
  36822. * @default false
  36823. */
  36824. this.store = false;
  36825. /**
  36826. * The binding's generation which is an additional version
  36827. * qualifier.
  36828. *
  36829. * @type {Number?}
  36830. * @default null
  36831. */
  36832. this.generation = null;
  36833. /**
  36834. * This flag can be used for type testing.
  36835. *
  36836. * @type {Boolean}
  36837. * @readonly
  36838. * @default true
  36839. */
  36840. this.isSampledTexture = true;
  36841. }
  36842. /**
  36843. * Returns `true` whether this binding requires an update for the
  36844. * given generation.
  36845. *
  36846. * @param {Number} generation - The generation.
  36847. * @return {Boolean} Whether an update is required or not.
  36848. */
  36849. needsBindingsUpdate( generation ) {
  36850. const { texture } = this;
  36851. if ( generation !== this.generation ) {
  36852. this.generation = generation;
  36853. return true;
  36854. }
  36855. return texture.isVideoTexture;
  36856. }
  36857. /**
  36858. * Updates the binding.
  36859. *
  36860. * @return {Boolean} Whether the texture has been updated and must be
  36861. * uploaded to the GPU.
  36862. */
  36863. update() {
  36864. const { texture, version } = this;
  36865. if ( version !== texture.version ) {
  36866. this.version = texture.version;
  36867. return true;
  36868. }
  36869. return false;
  36870. }
  36871. }
  36872. /**
  36873. * A special form of sampled texture binding type.
  36874. * It's texture value is managed by a node object.
  36875. *
  36876. * @private
  36877. * @augments SampledTexture
  36878. */
  36879. class NodeSampledTexture extends SampledTexture {
  36880. /**
  36881. * Constructs a new node-based sampled texture.
  36882. *
  36883. * @param {String} name - The textures's name.
  36884. * @param {TextureNode} textureNode - The texture node.
  36885. * @param {UniformGroupNode} groupNode - The uniform group node.
  36886. * @param {String?} [access=null] - The access type.
  36887. */
  36888. constructor( name, textureNode, groupNode, access = null ) {
  36889. super( name, textureNode ? textureNode.value : null );
  36890. /**
  36891. * The texture node.
  36892. *
  36893. * @type {TextureNode}
  36894. */
  36895. this.textureNode = textureNode;
  36896. /**
  36897. * The uniform group node.
  36898. *
  36899. * @type {UniformGroupNode}
  36900. */
  36901. this.groupNode = groupNode;
  36902. /**
  36903. * The access type.
  36904. *
  36905. * @type {String?}
  36906. * @default null
  36907. */
  36908. this.access = access;
  36909. }
  36910. /**
  36911. * Overwrites the default to additionally check if the node value has changed.
  36912. *
  36913. * @param {Number} generation - The generation.
  36914. * @return {Boolean} Whether an update is required or not.
  36915. */
  36916. needsBindingsUpdate( generation ) {
  36917. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  36918. }
  36919. /**
  36920. * Updates the binding.
  36921. *
  36922. * @return {Boolean} Whether the texture has been updated and must be
  36923. * uploaded to the GPU.
  36924. */
  36925. update() {
  36926. const { textureNode } = this;
  36927. if ( this.texture !== textureNode.value ) {
  36928. this.texture = textureNode.value;
  36929. return true;
  36930. }
  36931. return super.update();
  36932. }
  36933. }
  36934. /**
  36935. * A special form of sampled cube texture binding type.
  36936. * It's texture value is managed by a node object.
  36937. *
  36938. * @private
  36939. * @augments NodeSampledTexture
  36940. */
  36941. class NodeSampledCubeTexture extends NodeSampledTexture {
  36942. /**
  36943. * Constructs a new node-based sampled cube texture.
  36944. *
  36945. * @param {String} name - The textures's name.
  36946. * @param {TextureNode} textureNode - The texture node.
  36947. * @param {UniformGroupNode} groupNode - The uniform group node.
  36948. * @param {String?} [access=null] - The access type.
  36949. */
  36950. constructor( name, textureNode, groupNode, access = null ) {
  36951. super( name, textureNode, groupNode, access );
  36952. /**
  36953. * This flag can be used for type testing.
  36954. *
  36955. * @type {Boolean}
  36956. * @readonly
  36957. * @default true
  36958. */
  36959. this.isSampledCubeTexture = true;
  36960. }
  36961. }
  36962. /**
  36963. * A special form of sampled 3D texture binding type.
  36964. * It's texture value is managed by a node object.
  36965. *
  36966. * @private
  36967. * @augments NodeSampledTexture
  36968. */
  36969. class NodeSampledTexture3D extends NodeSampledTexture {
  36970. /**
  36971. * Constructs a new node-based sampled 3D texture.
  36972. *
  36973. * @param {String} name - The textures's name.
  36974. * @param {TextureNode} textureNode - The texture node.
  36975. * @param {UniformGroupNode} groupNode - The uniform group node.
  36976. * @param {String?} [access=null] - The access type.
  36977. */
  36978. constructor( name, textureNode, groupNode, access = null ) {
  36979. super( name, textureNode, groupNode, access );
  36980. /**
  36981. * This flag can be used for type testing.
  36982. *
  36983. * @type {Boolean}
  36984. * @readonly
  36985. * @default true
  36986. */
  36987. this.isSampledTexture3D = true;
  36988. }
  36989. }
  36990. const glslMethods = {
  36991. textureDimensions: 'textureSize',
  36992. equals: 'equal'
  36993. };
  36994. const precisionLib = {
  36995. low: 'lowp',
  36996. medium: 'mediump',
  36997. high: 'highp'
  36998. };
  36999. const supports$1 = {
  37000. swizzleAssign: true,
  37001. storageBuffer: false
  37002. };
  37003. const defaultPrecisions = `
  37004. precision highp float;
  37005. precision highp int;
  37006. precision highp sampler2D;
  37007. precision highp sampler3D;
  37008. precision highp samplerCube;
  37009. precision highp sampler2DArray;
  37010. precision highp usampler2D;
  37011. precision highp usampler3D;
  37012. precision highp usamplerCube;
  37013. precision highp usampler2DArray;
  37014. precision highp isampler2D;
  37015. precision highp isampler3D;
  37016. precision highp isamplerCube;
  37017. precision highp isampler2DArray;
  37018. precision lowp sampler2DShadow;
  37019. `;
  37020. /**
  37021. * A node builder targeting GLSL.
  37022. *
  37023. * This module generates GLSL shader code from node materials and also
  37024. * generates the respective bindings and vertex buffer definitions. These
  37025. * data are later used by the renderer to create render and compute pipelines
  37026. * for render objects.
  37027. *
  37028. * @augments NodeBuilder
  37029. */
  37030. class GLSLNodeBuilder extends NodeBuilder {
  37031. /**
  37032. * Constructs a new GLSL node builder renderer.
  37033. *
  37034. * @param {Object3D} object - The 3D object.
  37035. * @param {Renderer} renderer - The renderer.
  37036. */
  37037. constructor( object, renderer ) {
  37038. super( object, renderer, new GLSLNodeParser() );
  37039. /**
  37040. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  37041. * another dictionary which manages UBOs per group ('render','frame','object').
  37042. *
  37043. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  37044. */
  37045. this.uniformGroups = {};
  37046. /**
  37047. * An array that holds objects defining the varying and attribute data in
  37048. * context of Transform Feedback.
  37049. *
  37050. * @type {Object<String,Map<String,Object>>}
  37051. */
  37052. this.transforms = [];
  37053. /**
  37054. * A dictionary that holds for each shader stage a Map of used extensions.
  37055. *
  37056. * @type {Object<String,Map<String,Object>>}
  37057. */
  37058. this.extensions = {};
  37059. /**
  37060. * A dictionary that holds for each shader stage an Array of used builtins.
  37061. *
  37062. * @type {Object<String,Array<String>>}
  37063. */
  37064. this.builtins = { vertex: [], fragment: [], compute: [] };
  37065. /**
  37066. * Whether comparison in shader code are generated with methods or not.
  37067. *
  37068. * @type {Boolean}
  37069. * @default true
  37070. */
  37071. this.useComparisonMethod = true;
  37072. }
  37073. /**
  37074. * Checks if the given texture requires a manual conversion to the working color space.
  37075. *
  37076. * @param {Texture} texture - The texture to check.
  37077. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  37078. */
  37079. needsToWorkingColorSpace( texture ) {
  37080. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  37081. }
  37082. /**
  37083. * Returns the native shader method name for a given generic name.
  37084. *
  37085. * @param {String} method - The method name to resolve.
  37086. * @return {String} The resolved GLSL method name.
  37087. */
  37088. getMethod( method ) {
  37089. return glslMethods[ method ] || method;
  37090. }
  37091. /**
  37092. * Returns the output struct name. Not relevant for GLSL.
  37093. *
  37094. * @return {String}
  37095. */
  37096. getOutputStructName() {
  37097. return '';
  37098. }
  37099. /**
  37100. * Builds the given shader node.
  37101. *
  37102. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37103. * @return {String} The GLSL function code.
  37104. */
  37105. buildFunctionCode( shaderNode ) {
  37106. const layout = shaderNode.layout;
  37107. const flowData = this.flowShaderNode( shaderNode );
  37108. const parameters = [];
  37109. for ( const input of layout.inputs ) {
  37110. parameters.push( this.getType( input.type ) + ' ' + input.name );
  37111. }
  37112. //
  37113. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  37114. ${ flowData.vars }
  37115. ${ flowData.code }
  37116. return ${ flowData.result };
  37117. }`;
  37118. //
  37119. return code;
  37120. }
  37121. /**
  37122. * Setups the Pixel Buffer Object (PBO) for the given storage
  37123. * buffer node.
  37124. *
  37125. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  37126. */
  37127. setupPBO( storageBufferNode ) {
  37128. const attribute = storageBufferNode.value;
  37129. if ( attribute.pbo === undefined ) {
  37130. const originalArray = attribute.array;
  37131. const numElements = attribute.count * attribute.itemSize;
  37132. const { itemSize } = attribute;
  37133. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  37134. let format = isInteger ? RedIntegerFormat : RedFormat;
  37135. if ( itemSize === 2 ) {
  37136. format = isInteger ? RGIntegerFormat : RGFormat;
  37137. } else if ( itemSize === 3 ) {
  37138. format = isInteger ? RGBIntegerFormat : RGBFormat;
  37139. } else if ( itemSize === 4 ) {
  37140. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  37141. }
  37142. const typeMap = {
  37143. Float32Array: FloatType,
  37144. Uint8Array: UnsignedByteType,
  37145. Uint16Array: UnsignedShortType,
  37146. Uint32Array: UnsignedIntType,
  37147. Int8Array: ByteType,
  37148. Int16Array: ShortType,
  37149. Int32Array: IntType,
  37150. Uint8ClampedArray: UnsignedByteType,
  37151. };
  37152. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  37153. let height = Math.ceil( ( numElements / itemSize ) / width );
  37154. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  37155. const newSize = width * height * itemSize;
  37156. const newArray = new originalArray.constructor( newSize );
  37157. newArray.set( originalArray, 0 );
  37158. attribute.array = newArray;
  37159. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  37160. pboTexture.needsUpdate = true;
  37161. pboTexture.isPBOTexture = true;
  37162. const pbo = new TextureNode( pboTexture, null, null );
  37163. pbo.setPrecision( 'high' );
  37164. attribute.pboNode = pbo;
  37165. attribute.pbo = pbo.value;
  37166. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37167. }
  37168. }
  37169. /**
  37170. * Returns a GLSL snippet that represents the property name of the given node.
  37171. *
  37172. * @param {Node} node - The node.
  37173. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37174. * @return {String} The property name.
  37175. */
  37176. getPropertyName( node, shaderStage = this.shaderStage ) {
  37177. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  37178. return shaderStage.charAt( 0 ) + '_' + node.name;
  37179. }
  37180. return super.getPropertyName( node, shaderStage );
  37181. }
  37182. /**
  37183. * Setups the Pixel Buffer Object (PBO) for the given storage
  37184. * buffer node.
  37185. *
  37186. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  37187. * @return {String} The property name.
  37188. */
  37189. generatePBO( storageArrayElementNode ) {
  37190. const { node, indexNode } = storageArrayElementNode;
  37191. const attribute = node.value;
  37192. if ( this.renderer.backend.has( attribute ) ) {
  37193. const attributeData = this.renderer.backend.get( attribute );
  37194. attributeData.pbo = attribute.pbo;
  37195. }
  37196. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37197. const textureName = this.getPropertyName( nodeUniform );
  37198. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  37199. const indexSnippet = indexNode.build( this, 'uint' );
  37200. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  37201. let propertyName = elementNodeData.propertyName;
  37202. if ( propertyName === undefined ) {
  37203. // property element
  37204. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  37205. propertyName = this.getPropertyName( nodeVar );
  37206. // property size
  37207. const bufferNodeData = this.getDataFromNode( node );
  37208. let propertySizeName = bufferNodeData.propertySizeName;
  37209. if ( propertySizeName === undefined ) {
  37210. propertySizeName = propertyName + 'Size';
  37211. this.getVarFromNode( node, propertySizeName, 'uint' );
  37212. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  37213. bufferNodeData.propertySizeName = propertySizeName;
  37214. }
  37215. //
  37216. const { itemSize } = attribute;
  37217. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  37218. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  37219. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  37220. //
  37221. let prefix = 'vec4';
  37222. if ( attribute.pbo.type === UnsignedIntType ) {
  37223. prefix = 'uvec4';
  37224. } else if ( attribute.pbo.type === IntType ) {
  37225. prefix = 'ivec4';
  37226. }
  37227. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  37228. elementNodeData.propertyName = propertyName;
  37229. }
  37230. return propertyName;
  37231. }
  37232. /**
  37233. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  37234. *
  37235. * @param {Texture} texture - The texture.
  37236. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37237. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37238. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37239. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37240. * @return {String} The GLSL snippet.
  37241. */
  37242. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  37243. if ( depthSnippet ) {
  37244. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  37245. } else {
  37246. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  37247. }
  37248. }
  37249. /**
  37250. * Generates the GLSL snippet for sampling/loading the given texture.
  37251. *
  37252. * @param {Texture} texture - The texture.
  37253. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37254. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37255. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37256. * @return {String} The GLSL snippet.
  37257. */
  37258. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  37259. if ( texture.isDepthTexture ) {
  37260. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  37261. } else {
  37262. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  37263. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  37264. }
  37265. }
  37266. /**
  37267. * Generates the GLSL snippet when sampling textures with explicit mip level.
  37268. *
  37269. * @param {Texture} texture - The texture.
  37270. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37271. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37272. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37273. * @return {String} The GLSL snippet.
  37274. */
  37275. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  37276. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  37277. }
  37278. /**
  37279. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  37280. *
  37281. * @param {Texture} texture - The texture.
  37282. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37283. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37284. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  37285. * @return {String} The GLSL snippet.
  37286. */
  37287. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  37288. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  37289. }
  37290. /**
  37291. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  37292. *
  37293. * @param {Texture} texture - The texture.
  37294. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37295. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37296. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  37297. * @return {String} The GLSL snippet.
  37298. */
  37299. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  37300. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  37301. }
  37302. /**
  37303. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  37304. * against a reference value.
  37305. *
  37306. * @param {Texture} texture - The texture.
  37307. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37308. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37309. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  37310. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  37311. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37312. * @return {String} The GLSL snippet.
  37313. */
  37314. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37315. if ( shaderStage === 'fragment' ) {
  37316. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37317. } else {
  37318. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37319. }
  37320. }
  37321. /**
  37322. * Returns the variables of the given shader stage as a GLSL string.
  37323. *
  37324. * @param {String} shaderStage - The shader stage.
  37325. * @return {String} The GLSL snippet that defines the variables.
  37326. */
  37327. getVars( shaderStage ) {
  37328. const snippets = [];
  37329. const vars = this.vars[ shaderStage ];
  37330. if ( vars !== undefined ) {
  37331. for ( const variable of vars ) {
  37332. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  37333. }
  37334. }
  37335. return snippets.join( '\n\t' );
  37336. }
  37337. /**
  37338. * Returns the uniforms of the given shader stage as a GLSL string.
  37339. *
  37340. * @param {String} shaderStage - The shader stage.
  37341. * @return {String} The GLSL snippet that defines the uniforms.
  37342. */
  37343. getUniforms( shaderStage ) {
  37344. const uniforms = this.uniforms[ shaderStage ];
  37345. const bindingSnippets = [];
  37346. const uniformGroups = {};
  37347. for ( const uniform of uniforms ) {
  37348. let snippet = null;
  37349. let group = false;
  37350. if ( uniform.type === 'texture' ) {
  37351. const texture = uniform.node.value;
  37352. let typePrefix = '';
  37353. if ( texture.isDataTexture === true ) {
  37354. if ( texture.type === UnsignedIntType ) {
  37355. typePrefix = 'u';
  37356. } else if ( texture.type === IntType ) {
  37357. typePrefix = 'i';
  37358. }
  37359. }
  37360. if ( texture.compareFunction ) {
  37361. snippet = `sampler2DShadow ${ uniform.name };`;
  37362. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  37363. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  37364. } else {
  37365. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  37366. }
  37367. } else if ( uniform.type === 'cubeTexture' ) {
  37368. snippet = `samplerCube ${ uniform.name };`;
  37369. } else if ( uniform.type === 'texture3D' ) {
  37370. snippet = `sampler3D ${ uniform.name };`;
  37371. } else if ( uniform.type === 'buffer' ) {
  37372. const bufferNode = uniform.node;
  37373. const bufferType = this.getType( bufferNode.bufferType );
  37374. const bufferCount = bufferNode.bufferCount;
  37375. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37376. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37377. } else {
  37378. const vectorType = this.getVectorType( uniform.type );
  37379. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37380. group = true;
  37381. }
  37382. const precision = uniform.node.precision;
  37383. if ( precision !== null ) {
  37384. snippet = precisionLib[ precision ] + ' ' + snippet;
  37385. }
  37386. if ( group ) {
  37387. snippet = '\t' + snippet;
  37388. const groupName = uniform.groupNode.name;
  37389. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37390. groupSnippets.push( snippet );
  37391. } else {
  37392. snippet = 'uniform ' + snippet;
  37393. bindingSnippets.push( snippet );
  37394. }
  37395. }
  37396. let output = '';
  37397. for ( const name in uniformGroups ) {
  37398. const groupSnippets = uniformGroups[ name ];
  37399. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37400. }
  37401. output += bindingSnippets.join( '\n' );
  37402. return output;
  37403. }
  37404. /**
  37405. * Returns the type for a given buffer attribute.
  37406. *
  37407. * @param {BufferAttribute} attribute - The buffer attribute.
  37408. * @return {String} The type.
  37409. */
  37410. getTypeFromAttribute( attribute ) {
  37411. let nodeType = super.getTypeFromAttribute( attribute );
  37412. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37413. let dataAttribute = attribute;
  37414. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37415. const array = dataAttribute.array;
  37416. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  37417. nodeType = nodeType.slice( 1 );
  37418. }
  37419. }
  37420. return nodeType;
  37421. }
  37422. /**
  37423. * Returns the shader attributes of the given shader stage as a GLSL string.
  37424. *
  37425. * @param {String} shaderStage - The shader stage.
  37426. * @return {String} The GLSL snippet that defines the shader attributes.
  37427. */
  37428. getAttributes( shaderStage ) {
  37429. let snippet = '';
  37430. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37431. const attributes = this.getAttributesArray();
  37432. let location = 0;
  37433. for ( const attribute of attributes ) {
  37434. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37435. }
  37436. }
  37437. return snippet;
  37438. }
  37439. /**
  37440. * Returns the members of the given struct type node as a GLSL string.
  37441. *
  37442. * @param {StructTypeNode} struct - The struct type node.
  37443. * @return {String} The GLSL snippet that defines the struct members.
  37444. */
  37445. getStructMembers( struct ) {
  37446. const snippets = [];
  37447. const members = struct.getMemberTypes();
  37448. for ( let i = 0; i < members.length; i ++ ) {
  37449. const member = members[ i ];
  37450. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37451. }
  37452. return snippets.join( '\n' );
  37453. }
  37454. /**
  37455. * Returns the structs of the given shader stage as a GLSL string.
  37456. *
  37457. * @param {String} shaderStage - The shader stage.
  37458. * @return {String} The GLSL snippet that defines the structs.
  37459. */
  37460. getStructs( shaderStage ) {
  37461. const snippets = [];
  37462. const structs = this.structs[ shaderStage ];
  37463. if ( structs.length === 0 ) {
  37464. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37465. }
  37466. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37467. const struct = structs[ index ];
  37468. let snippet = '\n';
  37469. snippet += this.getStructMembers( struct );
  37470. snippet += '\n';
  37471. snippets.push( snippet );
  37472. }
  37473. return snippets.join( '\n\n' );
  37474. }
  37475. /**
  37476. * Returns the varyings of the given shader stage as a GLSL string.
  37477. *
  37478. * @param {String} shaderStage - The shader stage.
  37479. * @return {String} The GLSL snippet that defines the varyings.
  37480. */
  37481. getVaryings( shaderStage ) {
  37482. let snippet = '';
  37483. const varyings = this.varyings;
  37484. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37485. for ( const varying of varyings ) {
  37486. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37487. const type = this.getType( varying.type );
  37488. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37489. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37490. }
  37491. } else if ( shaderStage === 'fragment' ) {
  37492. for ( const varying of varyings ) {
  37493. if ( varying.needsInterpolation ) {
  37494. const type = this.getType( varying.type );
  37495. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37496. snippet += `${flat}in ${type} ${varying.name};\n`;
  37497. }
  37498. }
  37499. }
  37500. for ( const builtin of this.builtins[ shaderStage ] ) {
  37501. snippet += `${builtin};\n`;
  37502. }
  37503. return snippet;
  37504. }
  37505. /**
  37506. * Returns the vertex index builtin.
  37507. *
  37508. * @return {String} The vertex index.
  37509. */
  37510. getVertexIndex() {
  37511. return 'uint( gl_VertexID )';
  37512. }
  37513. /**
  37514. * Returns the instance index builtin.
  37515. *
  37516. * @return {String} The instance index.
  37517. */
  37518. getInstanceIndex() {
  37519. return 'uint( gl_InstanceID )';
  37520. }
  37521. /**
  37522. * Returns the invocation local index builtin.
  37523. *
  37524. * @return {String} The invocation local index.
  37525. */
  37526. getInvocationLocalIndex() {
  37527. const workgroupSize = this.object.workgroupSize;
  37528. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  37529. return `uint( gl_InstanceID ) % ${size}u`;
  37530. }
  37531. /**
  37532. * Returns the draw index builtin.
  37533. *
  37534. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  37535. */
  37536. getDrawIndex() {
  37537. const extensions = this.renderer.backend.extensions;
  37538. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37539. return 'uint( gl_DrawID )';
  37540. }
  37541. return null;
  37542. }
  37543. /**
  37544. * Returns the front facing builtin.
  37545. *
  37546. * @return {String} The front facing builtin.
  37547. */
  37548. getFrontFacing() {
  37549. return 'gl_FrontFacing';
  37550. }
  37551. /**
  37552. * Returns the frag coord builtin.
  37553. *
  37554. * @return {String} The frag coord builtin.
  37555. */
  37556. getFragCoord() {
  37557. return 'gl_FragCoord.xy';
  37558. }
  37559. /**
  37560. * Returns the frag depth builtin.
  37561. *
  37562. * @return {String} The frag depth builtin.
  37563. */
  37564. getFragDepth() {
  37565. return 'gl_FragDepth';
  37566. }
  37567. /**
  37568. * Enables the given extension.
  37569. *
  37570. * @param {String} name - The extension name.
  37571. * @param {String} behavior - The extension behavior.
  37572. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  37573. */
  37574. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  37575. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  37576. if ( map.has( name ) === false ) {
  37577. map.set( name, {
  37578. name,
  37579. behavior
  37580. } );
  37581. }
  37582. }
  37583. /**
  37584. * Returns the enabled extensions of the given shader stage as a GLSL string.
  37585. *
  37586. * @param {String} shaderStage - The shader stage.
  37587. * @return {String} The GLSL snippet that defines the enabled extensions.
  37588. */
  37589. getExtensions( shaderStage ) {
  37590. const snippets = [];
  37591. if ( shaderStage === 'vertex' ) {
  37592. const ext = this.renderer.backend.extensions;
  37593. const isBatchedMesh = this.object.isBatchedMesh;
  37594. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37595. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  37596. }
  37597. }
  37598. const extensions = this.extensions[ shaderStage ];
  37599. if ( extensions !== undefined ) {
  37600. for ( const { name, behavior } of extensions.values() ) {
  37601. snippets.push( `#extension ${name} : ${behavior}` );
  37602. }
  37603. }
  37604. return snippets.join( '\n' );
  37605. }
  37606. /**
  37607. * Returns the clip distances builtin.
  37608. *
  37609. * @return {String} The clip distances builtin.
  37610. */
  37611. getClipDistance() {
  37612. return 'gl_ClipDistance';
  37613. }
  37614. /**
  37615. * Whether the requested feature is available or not.
  37616. *
  37617. * @param {String} name - The requested feature.
  37618. * @return {Boolean} Whether the requested feature is supported or not.
  37619. */
  37620. isAvailable( name ) {
  37621. let result = supports$1[ name ];
  37622. if ( result === undefined ) {
  37623. let extensionName;
  37624. result = false;
  37625. switch ( name ) {
  37626. case 'float32Filterable':
  37627. extensionName = 'OES_texture_float_linear';
  37628. break;
  37629. case 'clipDistance':
  37630. extensionName = 'WEBGL_clip_cull_distance';
  37631. break;
  37632. }
  37633. if ( extensionName !== undefined ) {
  37634. const extensions = this.renderer.backend.extensions;
  37635. if ( extensions.has( extensionName ) ) {
  37636. extensions.get( extensionName );
  37637. result = true;
  37638. }
  37639. }
  37640. supports$1[ name ] = result;
  37641. }
  37642. return result;
  37643. }
  37644. /**
  37645. * Whether to flip texture data along its vertical axis or not.
  37646. *
  37647. * @return {Boolean} Returns always `true` in context of GLSL.
  37648. */
  37649. isFlipY() {
  37650. return true;
  37651. }
  37652. /**
  37653. * Enables hardware clipping.
  37654. *
  37655. * @param {String} planeCount - The clipping plane count.
  37656. */
  37657. enableHardwareClipping( planeCount ) {
  37658. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  37659. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  37660. }
  37661. /**
  37662. * Registers a transform in context of Transform Feedback.
  37663. *
  37664. * @param {String} varyingName - The varying name.
  37665. * @param {AttributeNode} attributeNode - The attribute node.
  37666. */
  37667. registerTransform( varyingName, attributeNode ) {
  37668. this.transforms.push( { varyingName, attributeNode } );
  37669. }
  37670. /**
  37671. * Returns the transforms of the given shader stage as a GLSL string.
  37672. *
  37673. * @param {String} shaderStage - The shader stage.
  37674. * @return {String} The GLSL snippet that defines the transforms.
  37675. */
  37676. getTransforms( /* shaderStage */ ) {
  37677. const transforms = this.transforms;
  37678. let snippet = '';
  37679. for ( let i = 0; i < transforms.length; i ++ ) {
  37680. const transform = transforms[ i ];
  37681. const attributeName = this.getPropertyName( transform.attributeNode );
  37682. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37683. }
  37684. return snippet;
  37685. }
  37686. /**
  37687. * Returns a GLSL struct based on the given name and variables.
  37688. *
  37689. * @private
  37690. * @param {String} name - The struct name.
  37691. * @param {String} vars - The struct variables.
  37692. * @return {String} The GLSL snippet representing a struct.
  37693. */
  37694. _getGLSLUniformStruct( name, vars ) {
  37695. return `
  37696. layout( std140 ) uniform ${name} {
  37697. ${vars}
  37698. };`;
  37699. }
  37700. /**
  37701. * Returns a GLSL vertex shader based on the given shader data.
  37702. *
  37703. * @private
  37704. * @param {Object} shaderData - The shader data.
  37705. * @return {String} The vertex shader.
  37706. */
  37707. _getGLSLVertexCode( shaderData ) {
  37708. return `#version 300 es
  37709. ${ this.getSignature() }
  37710. // extensions
  37711. ${shaderData.extensions}
  37712. // precision
  37713. ${ defaultPrecisions }
  37714. // uniforms
  37715. ${shaderData.uniforms}
  37716. // varyings
  37717. ${shaderData.varyings}
  37718. // attributes
  37719. ${shaderData.attributes}
  37720. // codes
  37721. ${shaderData.codes}
  37722. void main() {
  37723. // vars
  37724. ${shaderData.vars}
  37725. // transforms
  37726. ${shaderData.transforms}
  37727. // flow
  37728. ${shaderData.flow}
  37729. gl_PointSize = 1.0;
  37730. }
  37731. `;
  37732. }
  37733. /**
  37734. * Returns a GLSL fragment shader based on the given shader data.
  37735. *
  37736. * @private
  37737. * @param {Object} shaderData - The shader data.
  37738. * @return {String} The vertex shader.
  37739. */
  37740. _getGLSLFragmentCode( shaderData ) {
  37741. return `#version 300 es
  37742. ${ this.getSignature() }
  37743. // precision
  37744. ${ defaultPrecisions }
  37745. // uniforms
  37746. ${shaderData.uniforms}
  37747. // varyings
  37748. ${shaderData.varyings}
  37749. // codes
  37750. ${shaderData.codes}
  37751. ${shaderData.structs}
  37752. void main() {
  37753. // vars
  37754. ${shaderData.vars}
  37755. // flow
  37756. ${shaderData.flow}
  37757. }
  37758. `;
  37759. }
  37760. /**
  37761. * Controls the code build of the shader stages.
  37762. */
  37763. buildCode() {
  37764. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37765. this.sortBindingGroups();
  37766. for ( const shaderStage in shadersData ) {
  37767. let flow = '// code\n\n';
  37768. flow += this.flowCode[ shaderStage ];
  37769. const flowNodes = this.flowNodes[ shaderStage ];
  37770. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37771. for ( const node of flowNodes ) {
  37772. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37773. const slotName = node.name;
  37774. if ( slotName ) {
  37775. if ( flow.length > 0 ) flow += '\n';
  37776. flow += `\t// flow -> ${ slotName }\n\t`;
  37777. }
  37778. flow += `${ flowSlotData.code }\n\t`;
  37779. if ( node === mainNode && shaderStage !== 'compute' ) {
  37780. flow += '// result\n\t';
  37781. if ( shaderStage === 'vertex' ) {
  37782. flow += 'gl_Position = ';
  37783. flow += `${ flowSlotData.result };`;
  37784. } else if ( shaderStage === 'fragment' ) {
  37785. if ( ! node.outputNode.isOutputStructNode ) {
  37786. flow += 'fragColor = ';
  37787. flow += `${ flowSlotData.result };`;
  37788. }
  37789. }
  37790. }
  37791. }
  37792. const stageData = shadersData[ shaderStage ];
  37793. stageData.extensions = this.getExtensions( shaderStage );
  37794. stageData.uniforms = this.getUniforms( shaderStage );
  37795. stageData.attributes = this.getAttributes( shaderStage );
  37796. stageData.varyings = this.getVaryings( shaderStage );
  37797. stageData.vars = this.getVars( shaderStage );
  37798. stageData.structs = this.getStructs( shaderStage );
  37799. stageData.codes = this.getCodes( shaderStage );
  37800. stageData.transforms = this.getTransforms( shaderStage );
  37801. stageData.flow = flow;
  37802. }
  37803. if ( this.material !== null ) {
  37804. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37805. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37806. } else {
  37807. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37808. }
  37809. }
  37810. /**
  37811. * This method is one of the more important ones since it's responsible
  37812. * for generating a matching binding instance for the given uniform node.
  37813. *
  37814. * These bindings are later used in the renderer to create bind groups
  37815. * and layouts.
  37816. *
  37817. * @param {UniformNode} node - The uniform node.
  37818. * @param {String} type - The node data type.
  37819. * @param {String} shaderStage - The shader stage.
  37820. * @param {String?} [name=null] - An optional uniform name.
  37821. * @return {NodeUniform} The node uniform object.
  37822. */
  37823. getUniformFromNode( node, type, shaderStage, name = null ) {
  37824. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37825. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37826. let uniformGPU = nodeData.uniformGPU;
  37827. if ( uniformGPU === undefined ) {
  37828. const group = node.groupNode;
  37829. const groupName = group.name;
  37830. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37831. if ( type === 'texture' ) {
  37832. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37833. bindings.push( uniformGPU );
  37834. } else if ( type === 'cubeTexture' ) {
  37835. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37836. bindings.push( uniformGPU );
  37837. } else if ( type === 'texture3D' ) {
  37838. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37839. bindings.push( uniformGPU );
  37840. } else if ( type === 'buffer' ) {
  37841. node.name = `NodeBuffer_${ node.id }`;
  37842. uniformNode.name = `buffer${ node.id }`;
  37843. const buffer = new NodeUniformBuffer( node, group );
  37844. buffer.name = node.name;
  37845. bindings.push( buffer );
  37846. uniformGPU = buffer;
  37847. } else {
  37848. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37849. let uniformsGroup = uniformsStage[ groupName ];
  37850. if ( uniformsGroup === undefined ) {
  37851. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37852. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37853. uniformsStage[ groupName ] = uniformsGroup;
  37854. bindings.push( uniformsGroup );
  37855. }
  37856. uniformGPU = this.getNodeUniform( uniformNode, type );
  37857. uniformsGroup.addUniform( uniformGPU );
  37858. }
  37859. nodeData.uniformGPU = uniformGPU;
  37860. }
  37861. return uniformNode;
  37862. }
  37863. }
  37864. let _vector2 = null;
  37865. let _color4 = null;
  37866. /**
  37867. * Most of the rendering related logic is implemented in the
  37868. * {@link module:Renderer} module and related management components.
  37869. * Sometimes it is required though to execute commands which are
  37870. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  37871. * This abstract base class defines an interface that encapsulates
  37872. * all backend-related logic. Derived classes for each backend must
  37873. * implement the interface.
  37874. *
  37875. * @abstract
  37876. * @private
  37877. */
  37878. class Backend {
  37879. /**
  37880. * Constructs a new backend.
  37881. *
  37882. * @param {Object} parameters - An object holding parameters for the backend.
  37883. */
  37884. constructor( parameters = {} ) {
  37885. /**
  37886. * The parameters of the backend.
  37887. *
  37888. * @type {Object}
  37889. */
  37890. this.parameters = Object.assign( {}, parameters );
  37891. /**
  37892. * This weak map holds backend-specific data of objects
  37893. * like textures, attributes or render targets.
  37894. *
  37895. * @type {WeakMap}
  37896. */
  37897. this.data = new WeakMap();
  37898. /**
  37899. * A reference to the renderer.
  37900. *
  37901. * @type {Renderer?}
  37902. * @default null
  37903. */
  37904. this.renderer = null;
  37905. /**
  37906. * A reference to the canvas element the renderer is drawing to.
  37907. *
  37908. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  37909. * @default null
  37910. */
  37911. this.domElement = null;
  37912. /**
  37913. * A reference to the timestamp query pool.
  37914. *
  37915. * @type {{render: TimestampQueryPool?, compute: TimestampQueryPool?}}
  37916. */
  37917. this.timestampQueryPool = {
  37918. 'render': null,
  37919. 'compute': null
  37920. };
  37921. }
  37922. /**
  37923. * Initializes the backend so it is ready for usage. Concrete backends
  37924. * are supposed to implement their rendering context creation and related
  37925. * operations in this method.
  37926. *
  37927. * @async
  37928. * @param {Renderer} renderer - The renderer.
  37929. * @return {Promise} A Promise that resolves when the backend has been initialized.
  37930. */
  37931. async init( renderer ) {
  37932. this.renderer = renderer;
  37933. }
  37934. /**
  37935. * The coordinate system of the backend.
  37936. *
  37937. * @abstract
  37938. * @type {Number}
  37939. * @readonly
  37940. */
  37941. get coordinateSystem() {}
  37942. // render context
  37943. /**
  37944. * This method is executed at the beginning of a render call and
  37945. * can be used by the backend to prepare the state for upcoming
  37946. * draw calls.
  37947. *
  37948. * @abstract
  37949. * @param {RenderContext} renderContext - The render context.
  37950. */
  37951. beginRender( /*renderContext*/ ) {}
  37952. /**
  37953. * This method is executed at the end of a render call and
  37954. * can be used by the backend to finalize work after draw
  37955. * calls.
  37956. *
  37957. * @abstract
  37958. * @param {RenderContext} renderContext - The render context.
  37959. */
  37960. finishRender( /*renderContext*/ ) {}
  37961. /**
  37962. * This method is executed at the beginning of a compute call and
  37963. * can be used by the backend to prepare the state for upcoming
  37964. * compute tasks.
  37965. *
  37966. * @abstract
  37967. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37968. */
  37969. beginCompute( /*computeGroup*/ ) {}
  37970. /**
  37971. * This method is executed at the end of a compute call and
  37972. * can be used by the backend to finalize work after compute
  37973. * tasks.
  37974. *
  37975. * @abstract
  37976. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37977. */
  37978. finishCompute( /*computeGroup*/ ) {}
  37979. // render object
  37980. /**
  37981. * Executes a draw command for the given render object.
  37982. *
  37983. * @abstract
  37984. * @param {RenderObject} renderObject - The render object to draw.
  37985. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  37986. */
  37987. draw( /*renderObject, info*/ ) { }
  37988. // compute node
  37989. /**
  37990. * Executes a compute command for the given compute node.
  37991. *
  37992. * @abstract
  37993. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  37994. * @param {Node} computeNode - The compute node.
  37995. * @param {Array<BindGroup>} bindings - The bindings.
  37996. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37997. */
  37998. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  37999. // program
  38000. /**
  38001. * Creates a shader program from the given programmable stage.
  38002. *
  38003. * @abstract
  38004. * @param {ProgrammableStage} program - The programmable stage.
  38005. */
  38006. createProgram( /*program*/ ) { }
  38007. /**
  38008. * Destroys the shader program of the given programmable stage.
  38009. *
  38010. * @abstract
  38011. * @param {ProgrammableStage} program - The programmable stage.
  38012. */
  38013. destroyProgram( /*program*/ ) { }
  38014. // bindings
  38015. /**
  38016. * Creates bindings from the given bind group definition.
  38017. *
  38018. * @abstract
  38019. * @param {BindGroup} bindGroup - The bind group.
  38020. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38021. * @param {Number} cacheIndex - The cache index.
  38022. * @param {Number} version - The version.
  38023. */
  38024. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38025. /**
  38026. * Updates the given bind group definition.
  38027. *
  38028. * @abstract
  38029. * @param {BindGroup} bindGroup - The bind group.
  38030. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38031. * @param {Number} cacheIndex - The cache index.
  38032. * @param {Number} version - The version.
  38033. */
  38034. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38035. /**
  38036. * Updates a buffer binding.
  38037. *
  38038. * @abstract
  38039. * @param {Buffer} binding - The buffer binding to update.
  38040. */
  38041. updateBinding( /*binding*/ ) { }
  38042. // pipeline
  38043. /**
  38044. * Creates a render pipeline for the given render object.
  38045. *
  38046. * @abstract
  38047. * @param {RenderObject} renderObject - The render object.
  38048. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  38049. */
  38050. createRenderPipeline( /*renderObject, promises*/ ) { }
  38051. /**
  38052. * Creates a compute pipeline for the given compute node.
  38053. *
  38054. * @abstract
  38055. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38056. * @param {Array<BindGroup>} bindings - The bindings.
  38057. */
  38058. createComputePipeline( /*computePipeline, bindings*/ ) { }
  38059. // cache key
  38060. /**
  38061. * Returns `true` if the render pipeline requires an update.
  38062. *
  38063. * @abstract
  38064. * @param {RenderObject} renderObject - The render object.
  38065. * @return {Boolean} Whether the render pipeline requires an update or not.
  38066. */
  38067. needsRenderUpdate( /*renderObject*/ ) { }
  38068. /**
  38069. * Returns a cache key that is used to identify render pipelines.
  38070. *
  38071. * @abstract
  38072. * @param {RenderObject} renderObject - The render object.
  38073. * @return {String} The cache key.
  38074. */
  38075. getRenderCacheKey( /*renderObject*/ ) { }
  38076. // node builder
  38077. /**
  38078. * Returns a node builder for the given render object.
  38079. *
  38080. * @abstract
  38081. * @param {RenderObject} renderObject - The render object.
  38082. * @param {Renderer} renderer - The renderer.
  38083. * @return {NodeBuilder} The node builder.
  38084. */
  38085. createNodeBuilder( /*renderObject, renderer*/ ) { }
  38086. // textures
  38087. /**
  38088. * Creates a GPU sampler for the given texture.
  38089. *
  38090. * @abstract
  38091. * @param {Texture} texture - The texture to create the sampler for.
  38092. */
  38093. createSampler( /*texture*/ ) { }
  38094. /**
  38095. * Destroys the GPU sampler for the given texture.
  38096. *
  38097. * @abstract
  38098. * @param {Texture} texture - The texture to destroy the sampler for.
  38099. */
  38100. destroySampler( /*texture*/ ) {}
  38101. /**
  38102. * Creates a default texture for the given texture that can be used
  38103. * as a placeholder until the actual texture is ready for usage.
  38104. *
  38105. * @abstract
  38106. * @param {Texture} texture - The texture to create a default texture for.
  38107. */
  38108. createDefaultTexture( /*texture*/ ) { }
  38109. /**
  38110. * Defines a texture on the GPU for the given texture object.
  38111. *
  38112. * @abstract
  38113. * @param {Texture} texture - The texture.
  38114. * @param {Object} [options={}] - Optional configuration parameter.
  38115. */
  38116. createTexture( /*texture, options={}*/ ) { }
  38117. /**
  38118. * Uploads the updated texture data to the GPU.
  38119. *
  38120. * @abstract
  38121. * @param {Texture} texture - The texture.
  38122. * @param {Object} [options={}] - Optional configuration parameter.
  38123. */
  38124. updateTexture( /*texture, options = {}*/ ) { }
  38125. /**
  38126. * Generates mipmaps for the given texture.
  38127. *
  38128. * @abstract
  38129. * @param {Texture} texture - The texture.
  38130. */
  38131. generateMipmaps( /*texture*/ ) { }
  38132. /**
  38133. * Destroys the GPU data for the given texture object.
  38134. *
  38135. * @abstract
  38136. * @param {Texture} texture - The texture.
  38137. */
  38138. destroyTexture( /*texture*/ ) { }
  38139. /**
  38140. * Returns texture data as a typed array.
  38141. *
  38142. * @abstract
  38143. * @async
  38144. * @param {Texture} texture - The texture to copy.
  38145. * @param {Number} x - The x coordinate of the copy origin.
  38146. * @param {Number} y - The y coordinate of the copy origin.
  38147. * @param {Number} width - The width of the copy.
  38148. * @param {Number} height - The height of the copy.
  38149. * @param {Number} faceIndex - The face index.
  38150. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  38151. */
  38152. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  38153. /**
  38154. * Copies data of the given source texture to the given destination texture.
  38155. *
  38156. * @abstract
  38157. * @param {Texture} srcTexture - The source texture.
  38158. * @param {Texture} dstTexture - The destination texture.
  38159. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  38160. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  38161. * @param {Number} [level=0] - The mip level to copy.
  38162. */
  38163. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  38164. /**
  38165. * Copies the current bound framebuffer to the given texture.
  38166. *
  38167. * @abstract
  38168. * @param {Texture} texture - The destination texture.
  38169. * @param {RenderContext} renderContext - The render context.
  38170. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  38171. */
  38172. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  38173. // attributes
  38174. /**
  38175. * Creates the GPU buffer of a shader attribute.
  38176. *
  38177. * @abstract
  38178. * @param {BufferAttribute} attribute - The buffer attribute.
  38179. */
  38180. createAttribute( /*attribute*/ ) { }
  38181. /**
  38182. * Creates the GPU buffer of an indexed shader attribute.
  38183. *
  38184. * @abstract
  38185. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  38186. */
  38187. createIndexAttribute( /*attribute*/ ) { }
  38188. /**
  38189. * Creates the GPU buffer of a storage attribute.
  38190. *
  38191. * @abstract
  38192. * @param {BufferAttribute} attribute - The buffer attribute.
  38193. */
  38194. createStorageAttribute( /*attribute*/ ) { }
  38195. /**
  38196. * Updates the GPU buffer of a shader attribute.
  38197. *
  38198. * @abstract
  38199. * @param {BufferAttribute} attribute - The buffer attribute to update.
  38200. */
  38201. updateAttribute( /*attribute*/ ) { }
  38202. /**
  38203. * Destroys the GPU buffer of a shader attribute.
  38204. *
  38205. * @abstract
  38206. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  38207. */
  38208. destroyAttribute( /*attribute*/ ) { }
  38209. // canvas
  38210. /**
  38211. * Returns the backend's rendering context.
  38212. *
  38213. * @abstract
  38214. * @return {Object} The rendering context.
  38215. */
  38216. getContext() { }
  38217. /**
  38218. * Backends can use this method if they have to run
  38219. * logic when the renderer gets resized.
  38220. *
  38221. * @abstract
  38222. */
  38223. updateSize() { }
  38224. /**
  38225. * Updates the viewport with the values from the given render context.
  38226. *
  38227. * @abstract
  38228. * @param {RenderContext} renderContext - The render context.
  38229. */
  38230. updateViewport( /*renderContext*/ ) {}
  38231. // utils
  38232. /**
  38233. * Returns `true` if the given 3D object is fully occluded by other
  38234. * 3D objects in the scene. Backends must implement this method by using
  38235. * a Occlusion Query API.
  38236. *
  38237. * @abstract
  38238. * @param {RenderContext} renderContext - The render context.
  38239. * @param {Object3D} object - The 3D object to test.
  38240. * @return {Boolean} Whether the 3D object is fully occluded or not.
  38241. */
  38242. isOccluded( /*renderContext, object*/ ) {}
  38243. /**
  38244. * Resolves the time stamp for the given render context and type.
  38245. *
  38246. * @async
  38247. * @abstract
  38248. * @param {String} [type='render'] - The type of the time stamp.
  38249. * @return {Promise<Number>} A Promise that resolves with the time stamp.
  38250. */
  38251. async resolveTimestampsAsync( type = 'render' ) {
  38252. if ( ! this.trackTimestamp ) {
  38253. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  38254. return;
  38255. }
  38256. const queryPool = this.timestampQueryPool[ type ];
  38257. if ( ! queryPool ) {
  38258. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  38259. return;
  38260. }
  38261. const duration = await queryPool.resolveQueriesAsync();
  38262. this.renderer.info[ type ].timestamp = duration;
  38263. return duration;
  38264. }
  38265. /**
  38266. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38267. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38268. *
  38269. * @async
  38270. * @abstract
  38271. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38272. */
  38273. async waitForGPU() {}
  38274. /**
  38275. * This method performs a readback operation by moving buffer data from
  38276. * a storage buffer attribute from the GPU to the CPU.
  38277. *
  38278. * @async
  38279. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38280. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38281. */
  38282. async getArrayBufferAsync( /* attribute */ ) {}
  38283. /**
  38284. * Checks if the given feature is supported by the backend.
  38285. *
  38286. * @async
  38287. * @abstract
  38288. * @param {String} name - The feature's name.
  38289. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38290. */
  38291. async hasFeatureAsync( /*name*/ ) { }
  38292. /**
  38293. * Checks if the given feature is supported by the backend.
  38294. *
  38295. * @abstract
  38296. * @param {String} name - The feature's name.
  38297. * @return {Boolean} Whether the feature is supported or not.
  38298. */
  38299. hasFeature( /*name*/ ) {}
  38300. /**
  38301. * Returns the maximum anisotropy texture filtering value.
  38302. *
  38303. * @abstract
  38304. * @return {Number} The maximum anisotropy texture filtering value.
  38305. */
  38306. getMaxAnisotropy() {}
  38307. /**
  38308. * Returns the drawing buffer size.
  38309. *
  38310. * @return {Vector2} The drawing buffer size.
  38311. */
  38312. getDrawingBufferSize() {
  38313. _vector2 = _vector2 || new Vector2();
  38314. return this.renderer.getDrawingBufferSize( _vector2 );
  38315. }
  38316. /**
  38317. * Defines the scissor test.
  38318. *
  38319. * @abstract
  38320. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38321. */
  38322. setScissorTest( /*boolean*/ ) { }
  38323. /**
  38324. * Returns the clear color and alpha into a single
  38325. * color object.
  38326. *
  38327. * @return {Color4} The clear color.
  38328. */
  38329. getClearColor() {
  38330. const renderer = this.renderer;
  38331. _color4 = _color4 || new Color4();
  38332. renderer.getClearColor( _color4 );
  38333. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  38334. return _color4;
  38335. }
  38336. /**
  38337. * Returns the DOM element. If no DOM element exists, the backend
  38338. * creates a new one.
  38339. *
  38340. * @return {HTMLCanvasElement} The DOM element.
  38341. */
  38342. getDomElement() {
  38343. let domElement = this.domElement;
  38344. if ( domElement === null ) {
  38345. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  38346. // OffscreenCanvas does not have setAttribute, see #22811
  38347. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  38348. this.domElement = domElement;
  38349. }
  38350. return domElement;
  38351. }
  38352. /**
  38353. * Sets a dictionary for the given object into the
  38354. * internal data structure.
  38355. *
  38356. * @param {Object} object - The object.
  38357. * @param {Object} value - The dictionary to set.
  38358. */
  38359. set( object, value ) {
  38360. this.data.set( object, value );
  38361. }
  38362. /**
  38363. * Returns the dictionary for the given object.
  38364. *
  38365. * @param {Object} object - The object.
  38366. * @return {Object} The object's dictionary.
  38367. */
  38368. get( object ) {
  38369. let map = this.data.get( object );
  38370. if ( map === undefined ) {
  38371. map = {};
  38372. this.data.set( object, map );
  38373. }
  38374. return map;
  38375. }
  38376. /**
  38377. * Checks if the given object has a dictionary
  38378. * with data defined.
  38379. *
  38380. * @param {Object} object - The object.
  38381. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  38382. */
  38383. has( object ) {
  38384. return this.data.has( object );
  38385. }
  38386. /**
  38387. * Deletes an object from the internal data structure.
  38388. *
  38389. * @param {Object} object - The object to delete.
  38390. */
  38391. delete( object ) {
  38392. this.data.delete( object );
  38393. }
  38394. /**
  38395. * Frees internal resources.
  38396. *
  38397. * @abstract
  38398. */
  38399. dispose() { }
  38400. }
  38401. let _id$1 = 0;
  38402. /**
  38403. * This module is internally used in context of compute shaders.
  38404. * This type of shader is not natively supported in WebGL 2 and
  38405. * thus implemented via Transform Feedback. `DualAttributeData`
  38406. * manages the related data.
  38407. *
  38408. * @private
  38409. */
  38410. class DualAttributeData {
  38411. constructor( attributeData, dualBuffer ) {
  38412. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38413. this.type = attributeData.type;
  38414. this.bufferType = attributeData.bufferType;
  38415. this.pbo = attributeData.pbo;
  38416. this.byteLength = attributeData.byteLength;
  38417. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38418. this.version = attributeData.version;
  38419. this.isInteger = attributeData.isInteger;
  38420. this.activeBufferIndex = 0;
  38421. this.baseId = attributeData.id;
  38422. }
  38423. get id() {
  38424. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38425. }
  38426. get bufferGPU() {
  38427. return this.buffers[ this.activeBufferIndex ];
  38428. }
  38429. get transformBuffer() {
  38430. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38431. }
  38432. switchBuffers() {
  38433. this.activeBufferIndex ^= 1;
  38434. }
  38435. }
  38436. /**
  38437. * A WebGL 2 backend utility module for managing shader attributes.
  38438. *
  38439. * @private
  38440. */
  38441. class WebGLAttributeUtils {
  38442. /**
  38443. * Constructs a new utility object.
  38444. *
  38445. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38446. */
  38447. constructor( backend ) {
  38448. /**
  38449. * A reference to the WebGL 2 backend.
  38450. *
  38451. * @type {WebGLBackend}
  38452. */
  38453. this.backend = backend;
  38454. }
  38455. /**
  38456. * Creates the GPU buffer for the given buffer attribute.
  38457. *
  38458. * @param {BufferAttribute} attribute - The buffer attribute.
  38459. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38460. */
  38461. createAttribute( attribute, bufferType ) {
  38462. const backend = this.backend;
  38463. const { gl } = backend;
  38464. const array = attribute.array;
  38465. const usage = attribute.usage || gl.STATIC_DRAW;
  38466. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38467. const bufferData = backend.get( bufferAttribute );
  38468. let bufferGPU = bufferData.bufferGPU;
  38469. if ( bufferGPU === undefined ) {
  38470. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38471. bufferData.bufferGPU = bufferGPU;
  38472. bufferData.bufferType = bufferType;
  38473. bufferData.version = bufferAttribute.version;
  38474. }
  38475. //attribute.onUploadCallback();
  38476. let type;
  38477. if ( array instanceof Float32Array ) {
  38478. type = gl.FLOAT;
  38479. } else if ( array instanceof Uint16Array ) {
  38480. if ( attribute.isFloat16BufferAttribute ) {
  38481. type = gl.HALF_FLOAT;
  38482. } else {
  38483. type = gl.UNSIGNED_SHORT;
  38484. }
  38485. } else if ( array instanceof Int16Array ) {
  38486. type = gl.SHORT;
  38487. } else if ( array instanceof Uint32Array ) {
  38488. type = gl.UNSIGNED_INT;
  38489. } else if ( array instanceof Int32Array ) {
  38490. type = gl.INT;
  38491. } else if ( array instanceof Int8Array ) {
  38492. type = gl.BYTE;
  38493. } else if ( array instanceof Uint8Array ) {
  38494. type = gl.UNSIGNED_BYTE;
  38495. } else if ( array instanceof Uint8ClampedArray ) {
  38496. type = gl.UNSIGNED_BYTE;
  38497. } else {
  38498. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38499. }
  38500. let attributeData = {
  38501. bufferGPU,
  38502. bufferType,
  38503. type,
  38504. byteLength: array.byteLength,
  38505. bytesPerElement: array.BYTES_PER_ELEMENT,
  38506. version: attribute.version,
  38507. pbo: attribute.pbo,
  38508. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38509. id: _id$1 ++
  38510. };
  38511. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38512. // create buffer for transform feedback use
  38513. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38514. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38515. }
  38516. backend.set( attribute, attributeData );
  38517. }
  38518. /**
  38519. * Updates the GPU buffer of the given buffer attribute.
  38520. *
  38521. * @param {BufferAttribute} attribute - The buffer attribute.
  38522. */
  38523. updateAttribute( attribute ) {
  38524. const backend = this.backend;
  38525. const { gl } = backend;
  38526. const array = attribute.array;
  38527. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38528. const bufferData = backend.get( bufferAttribute );
  38529. const bufferType = bufferData.bufferType;
  38530. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38531. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38532. if ( updateRanges.length === 0 ) {
  38533. // Not using update ranges
  38534. gl.bufferSubData( bufferType, 0, array );
  38535. } else {
  38536. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38537. const range = updateRanges[ i ];
  38538. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38539. array, range.start, range.count );
  38540. }
  38541. bufferAttribute.clearUpdateRanges();
  38542. }
  38543. gl.bindBuffer( bufferType, null );
  38544. bufferData.version = bufferAttribute.version;
  38545. }
  38546. /**
  38547. * Destroys the GPU buffer of the given buffer attribute.
  38548. *
  38549. * @param {BufferAttribute} attribute - The buffer attribute.
  38550. */
  38551. destroyAttribute( attribute ) {
  38552. const backend = this.backend;
  38553. const { gl } = backend;
  38554. if ( attribute.isInterleavedBufferAttribute ) {
  38555. backend.delete( attribute.data );
  38556. }
  38557. const attributeData = backend.get( attribute );
  38558. gl.deleteBuffer( attributeData.bufferGPU );
  38559. backend.delete( attribute );
  38560. }
  38561. /**
  38562. * This method performs a readback operation by moving buffer data from
  38563. * a storage buffer attribute from the GPU to the CPU.
  38564. *
  38565. * @async
  38566. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38567. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38568. */
  38569. async getArrayBufferAsync( attribute ) {
  38570. const backend = this.backend;
  38571. const { gl } = backend;
  38572. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38573. const { bufferGPU } = backend.get( bufferAttribute );
  38574. const array = attribute.array;
  38575. const byteLength = array.byteLength;
  38576. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38577. const writeBuffer = gl.createBuffer();
  38578. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38579. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38580. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38581. await backend.utils._clientWaitAsync();
  38582. const dstBuffer = new attribute.array.constructor( array.length );
  38583. // Ensure the buffer is bound before reading
  38584. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38585. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38586. gl.deleteBuffer( writeBuffer );
  38587. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  38588. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  38589. return dstBuffer.buffer;
  38590. }
  38591. /**
  38592. * Creates a WebGL buffer with the given data.
  38593. *
  38594. * @private
  38595. * @param {WebGL2RenderingContext} gl - The rendering context.
  38596. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38597. * @param {TypedArray} array - The array of the buffer attribute.
  38598. * @param {GLenum} usage - The usage.
  38599. * @return {WebGLBuffer} The WebGL buffer.
  38600. */
  38601. _createBuffer( gl, bufferType, array, usage ) {
  38602. const bufferGPU = gl.createBuffer();
  38603. gl.bindBuffer( bufferType, bufferGPU );
  38604. gl.bufferData( bufferType, array, usage );
  38605. gl.bindBuffer( bufferType, null );
  38606. return bufferGPU;
  38607. }
  38608. }
  38609. let equationToGL, factorToGL;
  38610. /**
  38611. * A WebGL 2 backend utility module for managing the WebGL state.
  38612. *
  38613. * The major goal of this module is to reduce the number of state changes
  38614. * by caching the WEbGL state with a series of variables. In this way, the
  38615. * renderer only executes state change commands when necessary which
  38616. * improves the overall performance.
  38617. *
  38618. * @private
  38619. */
  38620. class WebGLState {
  38621. /**
  38622. * Constructs a new utility object.
  38623. *
  38624. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38625. */
  38626. constructor( backend ) {
  38627. /**
  38628. * A reference to the WebGL 2 backend.
  38629. *
  38630. * @type {WebGLBackend}
  38631. */
  38632. this.backend = backend;
  38633. /**
  38634. * A reference to the rendering context.
  38635. *
  38636. * @type {WebGL2RenderingContext}
  38637. */
  38638. this.gl = this.backend.gl;
  38639. // Below properties are intended to cache
  38640. // the WebGL state and are not explicitly
  38641. // documented for convenience reasons.
  38642. this.enabled = {};
  38643. this.currentFlipSided = null;
  38644. this.currentCullFace = null;
  38645. this.currentProgram = null;
  38646. this.currentBlendingEnabled = false;
  38647. this.currentBlending = null;
  38648. this.currentBlendSrc = null;
  38649. this.currentBlendDst = null;
  38650. this.currentBlendSrcAlpha = null;
  38651. this.currentBlendDstAlpha = null;
  38652. this.currentPremultipledAlpha = null;
  38653. this.currentPolygonOffsetFactor = null;
  38654. this.currentPolygonOffsetUnits = null;
  38655. this.currentColorMask = null;
  38656. this.currentDepthFunc = null;
  38657. this.currentDepthMask = null;
  38658. this.currentStencilFunc = null;
  38659. this.currentStencilRef = null;
  38660. this.currentStencilFuncMask = null;
  38661. this.currentStencilFail = null;
  38662. this.currentStencilZFail = null;
  38663. this.currentStencilZPass = null;
  38664. this.currentStencilMask = null;
  38665. this.currentLineWidth = null;
  38666. this.currentClippingPlanes = 0;
  38667. this.currentBoundFramebuffers = {};
  38668. this.currentDrawbuffers = new WeakMap();
  38669. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38670. this.currentTextureSlot = null;
  38671. this.currentBoundTextures = {};
  38672. this.currentBoundBufferBases = {};
  38673. this._init();
  38674. }
  38675. /**
  38676. * Inits the state of the utility.
  38677. *
  38678. * @private
  38679. */
  38680. _init() {
  38681. const gl = this.gl;
  38682. // Store only WebGL constants here.
  38683. equationToGL = {
  38684. [ AddEquation ]: gl.FUNC_ADD,
  38685. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38686. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38687. };
  38688. factorToGL = {
  38689. [ ZeroFactor ]: gl.ZERO,
  38690. [ OneFactor ]: gl.ONE,
  38691. [ SrcColorFactor ]: gl.SRC_COLOR,
  38692. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38693. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38694. [ DstColorFactor ]: gl.DST_COLOR,
  38695. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38696. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38697. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38698. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38699. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38700. };
  38701. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  38702. const viewportParam = gl.getParameter( gl.VIEWPORT );
  38703. this.currentScissor = new Vector4().fromArray( scissorParam );
  38704. this.currentViewport = new Vector4().fromArray( viewportParam );
  38705. this._tempVec4 = new Vector4();
  38706. }
  38707. /**
  38708. * Enables the given WebGL capability.
  38709. *
  38710. * This method caches the capability state so
  38711. * `gl.enable()` is only called when necessary.
  38712. *
  38713. * @param {GLenum} id - The capability to enable.
  38714. */
  38715. enable( id ) {
  38716. const { enabled } = this;
  38717. if ( enabled[ id ] !== true ) {
  38718. this.gl.enable( id );
  38719. enabled[ id ] = true;
  38720. }
  38721. }
  38722. /**
  38723. * Disables the given WebGL capability.
  38724. *
  38725. * This method caches the capability state so
  38726. * `gl.disable()` is only called when necessary.
  38727. *
  38728. * @param {GLenum} id - The capability to enable.
  38729. */
  38730. disable( id ) {
  38731. const { enabled } = this;
  38732. if ( enabled[ id ] !== false ) {
  38733. this.gl.disable( id );
  38734. enabled[ id ] = false;
  38735. }
  38736. }
  38737. /**
  38738. * Specifies whether polygons are front- or back-facing
  38739. * by setting the winding orientation.
  38740. *
  38741. * This method caches the state so `gl.frontFace()` is only
  38742. * called when necessary.
  38743. *
  38744. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  38745. */
  38746. setFlipSided( flipSided ) {
  38747. if ( this.currentFlipSided !== flipSided ) {
  38748. const { gl } = this;
  38749. if ( flipSided ) {
  38750. gl.frontFace( gl.CW );
  38751. } else {
  38752. gl.frontFace( gl.CCW );
  38753. }
  38754. this.currentFlipSided = flipSided;
  38755. }
  38756. }
  38757. /**
  38758. * Specifies whether or not front- and/or back-facing
  38759. * polygons can be culled.
  38760. *
  38761. * This method caches the state so `gl.cullFace()` is only
  38762. * called when necessary.
  38763. *
  38764. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  38765. */
  38766. setCullFace( cullFace ) {
  38767. const { gl } = this;
  38768. if ( cullFace !== CullFaceNone ) {
  38769. this.enable( gl.CULL_FACE );
  38770. if ( cullFace !== this.currentCullFace ) {
  38771. if ( cullFace === CullFaceBack ) {
  38772. gl.cullFace( gl.BACK );
  38773. } else if ( cullFace === CullFaceFront ) {
  38774. gl.cullFace( gl.FRONT );
  38775. } else {
  38776. gl.cullFace( gl.FRONT_AND_BACK );
  38777. }
  38778. }
  38779. } else {
  38780. this.disable( gl.CULL_FACE );
  38781. }
  38782. this.currentCullFace = cullFace;
  38783. }
  38784. /**
  38785. * Specifies the width of line primitives.
  38786. *
  38787. * This method caches the state so `gl.lineWidth()` is only
  38788. * called when necessary.
  38789. *
  38790. * @param {Number} width - The line width.
  38791. */
  38792. setLineWidth( width ) {
  38793. const { currentLineWidth, gl } = this;
  38794. if ( width !== currentLineWidth ) {
  38795. gl.lineWidth( width );
  38796. this.currentLineWidth = width;
  38797. }
  38798. }
  38799. /**
  38800. * Defines the blending.
  38801. *
  38802. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  38803. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  38804. *
  38805. * @param {Number} blending - The blending type.
  38806. * @param {Number} blendEquation - The blending equation.
  38807. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  38808. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  38809. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  38810. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  38811. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  38812. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  38813. */
  38814. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  38815. const { gl } = this;
  38816. if ( blending === NoBlending ) {
  38817. if ( this.currentBlendingEnabled === true ) {
  38818. this.disable( gl.BLEND );
  38819. this.currentBlendingEnabled = false;
  38820. }
  38821. return;
  38822. }
  38823. if ( this.currentBlendingEnabled === false ) {
  38824. this.enable( gl.BLEND );
  38825. this.currentBlendingEnabled = true;
  38826. }
  38827. if ( blending !== CustomBlending ) {
  38828. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  38829. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  38830. gl.blendEquation( gl.FUNC_ADD );
  38831. this.currentBlendEquation = AddEquation;
  38832. this.currentBlendEquationAlpha = AddEquation;
  38833. }
  38834. if ( premultipliedAlpha ) {
  38835. switch ( blending ) {
  38836. case NormalBlending:
  38837. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38838. break;
  38839. case AdditiveBlending:
  38840. gl.blendFunc( gl.ONE, gl.ONE );
  38841. break;
  38842. case SubtractiveBlending:
  38843. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38844. break;
  38845. case MultiplyBlending:
  38846. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  38847. break;
  38848. default:
  38849. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38850. break;
  38851. }
  38852. } else {
  38853. switch ( blending ) {
  38854. case NormalBlending:
  38855. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38856. break;
  38857. case AdditiveBlending:
  38858. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  38859. break;
  38860. case SubtractiveBlending:
  38861. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38862. break;
  38863. case MultiplyBlending:
  38864. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  38865. break;
  38866. default:
  38867. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38868. break;
  38869. }
  38870. }
  38871. this.currentBlendSrc = null;
  38872. this.currentBlendDst = null;
  38873. this.currentBlendSrcAlpha = null;
  38874. this.currentBlendDstAlpha = null;
  38875. this.currentBlending = blending;
  38876. this.currentPremultipledAlpha = premultipliedAlpha;
  38877. }
  38878. return;
  38879. }
  38880. // custom blending
  38881. blendEquationAlpha = blendEquationAlpha || blendEquation;
  38882. blendSrcAlpha = blendSrcAlpha || blendSrc;
  38883. blendDstAlpha = blendDstAlpha || blendDst;
  38884. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  38885. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  38886. this.currentBlendEquation = blendEquation;
  38887. this.currentBlendEquationAlpha = blendEquationAlpha;
  38888. }
  38889. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  38890. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  38891. this.currentBlendSrc = blendSrc;
  38892. this.currentBlendDst = blendDst;
  38893. this.currentBlendSrcAlpha = blendSrcAlpha;
  38894. this.currentBlendDstAlpha = blendDstAlpha;
  38895. }
  38896. this.currentBlending = blending;
  38897. this.currentPremultipledAlpha = false;
  38898. }
  38899. /**
  38900. * Specifies whether colors can be written when rendering
  38901. * into a framebuffer or not.
  38902. *
  38903. * This method caches the state so `gl.colorMask()` is only
  38904. * called when necessary.
  38905. *
  38906. * @param {Boolean} colorMask - The color mask.
  38907. */
  38908. setColorMask( colorMask ) {
  38909. if ( this.currentColorMask !== colorMask ) {
  38910. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38911. this.currentColorMask = colorMask;
  38912. }
  38913. }
  38914. /**
  38915. * Specifies whether the depth test is enabled or not.
  38916. *
  38917. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  38918. */
  38919. setDepthTest( depthTest ) {
  38920. const { gl } = this;
  38921. if ( depthTest ) {
  38922. this.enable( gl.DEPTH_TEST );
  38923. } else {
  38924. this.disable( gl.DEPTH_TEST );
  38925. }
  38926. }
  38927. /**
  38928. * Specifies whether depth values can be written when rendering
  38929. * into a framebuffer or not.
  38930. *
  38931. * This method caches the state so `gl.depthMask()` is only
  38932. * called when necessary.
  38933. *
  38934. * @param {Boolean} depthMask - The depth mask.
  38935. */
  38936. setDepthMask( depthMask ) {
  38937. if ( this.currentDepthMask !== depthMask ) {
  38938. this.gl.depthMask( depthMask );
  38939. this.currentDepthMask = depthMask;
  38940. }
  38941. }
  38942. /**
  38943. * Specifies the depth compare function.
  38944. *
  38945. * This method caches the state so `gl.depthFunc()` is only
  38946. * called when necessary.
  38947. *
  38948. * @param {Number} depthFunc - The depth compare function.
  38949. */
  38950. setDepthFunc( depthFunc ) {
  38951. if ( this.currentDepthFunc !== depthFunc ) {
  38952. const { gl } = this;
  38953. switch ( depthFunc ) {
  38954. case NeverDepth:
  38955. gl.depthFunc( gl.NEVER );
  38956. break;
  38957. case AlwaysDepth:
  38958. gl.depthFunc( gl.ALWAYS );
  38959. break;
  38960. case LessDepth:
  38961. gl.depthFunc( gl.LESS );
  38962. break;
  38963. case LessEqualDepth:
  38964. gl.depthFunc( gl.LEQUAL );
  38965. break;
  38966. case EqualDepth:
  38967. gl.depthFunc( gl.EQUAL );
  38968. break;
  38969. case GreaterEqualDepth:
  38970. gl.depthFunc( gl.GEQUAL );
  38971. break;
  38972. case GreaterDepth:
  38973. gl.depthFunc( gl.GREATER );
  38974. break;
  38975. case NotEqualDepth:
  38976. gl.depthFunc( gl.NOTEQUAL );
  38977. break;
  38978. default:
  38979. gl.depthFunc( gl.LEQUAL );
  38980. }
  38981. this.currentDepthFunc = depthFunc;
  38982. }
  38983. }
  38984. /**
  38985. * Specifies the viewport.
  38986. *
  38987. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38988. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38989. * @param {Number} width - The width of the viewport.
  38990. * @param {Number} height - The height of the viewport.
  38991. *
  38992. */
  38993. scissor( x, y, width, height ) {
  38994. const scissor = this._tempVec4.set( x, y, width, height );
  38995. if ( this.currentScissor.equals( scissor ) === false ) {
  38996. const { gl } = this;
  38997. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  38998. this.currentScissor.copy( scissor );
  38999. }
  39000. }
  39001. /**
  39002. * Specifies the viewport.
  39003. *
  39004. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  39005. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  39006. * @param {Number} width - The width of the viewport.
  39007. * @param {Number} height - The height of the viewport.
  39008. *
  39009. */
  39010. viewport( x, y, width, height ) {
  39011. const viewport = this._tempVec4.set( x, y, width, height );
  39012. if ( this.currentViewport.equals( viewport ) === false ) {
  39013. const { gl } = this;
  39014. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  39015. this.currentViewport.copy( viewport );
  39016. }
  39017. }
  39018. /**
  39019. * Defines the scissor test.
  39020. *
  39021. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  39022. */
  39023. setScissorTest( boolean ) {
  39024. const gl = this.gl;
  39025. if ( boolean ) {
  39026. gl.enable( gl.SCISSOR_TEST );
  39027. } else {
  39028. gl.disable( gl.SCISSOR_TEST );
  39029. }
  39030. }
  39031. /**
  39032. * Specifies whether the stencil test is enabled or not.
  39033. *
  39034. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  39035. */
  39036. setStencilTest( stencilTest ) {
  39037. const { gl } = this;
  39038. if ( stencilTest ) {
  39039. this.enable( gl.STENCIL_TEST );
  39040. } else {
  39041. this.disable( gl.STENCIL_TEST );
  39042. }
  39043. }
  39044. /**
  39045. * Specifies whether stencil values can be written when rendering
  39046. * into a framebuffer or not.
  39047. *
  39048. * This method caches the state so `gl.stencilMask()` is only
  39049. * called when necessary.
  39050. *
  39051. * @param {Boolean} stencilMask - The stencil mask.
  39052. */
  39053. setStencilMask( stencilMask ) {
  39054. if ( this.currentStencilMask !== stencilMask ) {
  39055. this.gl.stencilMask( stencilMask );
  39056. this.currentStencilMask = stencilMask;
  39057. }
  39058. }
  39059. /**
  39060. * Specifies whether the stencil test functions.
  39061. *
  39062. * This method caches the state so `gl.stencilFunc()` is only
  39063. * called when necessary.
  39064. *
  39065. * @param {Number} stencilFunc - The stencil compare function.
  39066. * @param {Number} stencilRef - The reference value for the stencil test.
  39067. * @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.
  39068. */
  39069. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39070. if ( this.currentStencilFunc !== stencilFunc ||
  39071. this.currentStencilRef !== stencilRef ||
  39072. this.currentStencilFuncMask !== stencilMask ) {
  39073. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39074. this.currentStencilFunc = stencilFunc;
  39075. this.currentStencilRef = stencilRef;
  39076. this.currentStencilFuncMask = stencilMask;
  39077. }
  39078. }
  39079. /**
  39080. * Specifies whether the stencil test operation.
  39081. *
  39082. * This method caches the state so `gl.stencilOp()` is only
  39083. * called when necessary.
  39084. *
  39085. * @param {Number} stencilFail - The function to use when the stencil test fails.
  39086. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  39087. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  39088. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  39089. */
  39090. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39091. if ( this.currentStencilFail !== stencilFail ||
  39092. this.currentStencilZFail !== stencilZFail ||
  39093. this.currentStencilZPass !== stencilZPass ) {
  39094. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39095. this.currentStencilFail = stencilFail;
  39096. this.currentStencilZFail = stencilZFail;
  39097. this.currentStencilZPass = stencilZPass;
  39098. }
  39099. }
  39100. /**
  39101. * Configures the WebGL state for the given material.
  39102. *
  39103. * @param {Material} material - The material to configure the state for.
  39104. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  39105. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  39106. */
  39107. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  39108. const { gl } = this;
  39109. material.side === DoubleSide
  39110. ? this.disable( gl.CULL_FACE )
  39111. : this.enable( gl.CULL_FACE );
  39112. let flipSided = ( material.side === BackSide );
  39113. if ( frontFaceCW ) flipSided = ! flipSided;
  39114. this.setFlipSided( flipSided );
  39115. ( material.blending === NormalBlending && material.transparent === false )
  39116. ? this.setBlending( NoBlending )
  39117. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39118. this.setDepthFunc( material.depthFunc );
  39119. this.setDepthTest( material.depthTest );
  39120. this.setDepthMask( material.depthWrite );
  39121. this.setColorMask( material.colorWrite );
  39122. const stencilWrite = material.stencilWrite;
  39123. this.setStencilTest( stencilWrite );
  39124. if ( stencilWrite ) {
  39125. this.setStencilMask( material.stencilWriteMask );
  39126. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39127. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39128. }
  39129. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39130. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39131. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39132. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39133. if ( hardwareClippingPlanes > 0 ) {
  39134. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  39135. const CLIP_DISTANCE0_WEBGL = 0x3000;
  39136. for ( let i = 0; i < 8; i ++ ) {
  39137. if ( i < hardwareClippingPlanes ) {
  39138. this.enable( CLIP_DISTANCE0_WEBGL + i );
  39139. } else {
  39140. this.disable( CLIP_DISTANCE0_WEBGL + i );
  39141. }
  39142. }
  39143. }
  39144. }
  39145. }
  39146. /**
  39147. * Specifies the polygon offset.
  39148. *
  39149. * This method caches the state so `gl.polygonOffset()` is only
  39150. * called when necessary.
  39151. *
  39152. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  39153. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  39154. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  39155. */
  39156. setPolygonOffset( polygonOffset, factor, units ) {
  39157. const { gl } = this;
  39158. if ( polygonOffset ) {
  39159. this.enable( gl.POLYGON_OFFSET_FILL );
  39160. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39161. gl.polygonOffset( factor, units );
  39162. this.currentPolygonOffsetFactor = factor;
  39163. this.currentPolygonOffsetUnits = units;
  39164. }
  39165. } else {
  39166. this.disable( gl.POLYGON_OFFSET_FILL );
  39167. }
  39168. }
  39169. /**
  39170. * Defines the usage of the given WebGL program.
  39171. *
  39172. * This method caches the state so `gl.useProgram()` is only
  39173. * called when necessary.
  39174. *
  39175. * @param {WebGLProgram} program - The WebGL program to use.
  39176. * @return {Boolean} Whether a program change has been executed or not.
  39177. */
  39178. useProgram( program ) {
  39179. if ( this.currentProgram !== program ) {
  39180. this.gl.useProgram( program );
  39181. this.currentProgram = program;
  39182. return true;
  39183. }
  39184. return false;
  39185. }
  39186. // framebuffer
  39187. /**
  39188. * Binds the given framebuffer.
  39189. *
  39190. * This method caches the state so `gl.bindFramebuffer()` is only
  39191. * called when necessary.
  39192. *
  39193. * @param {Number} target - The binding point (target).
  39194. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  39195. * @return {Boolean} Whether a bind has been executed or not.
  39196. */
  39197. bindFramebuffer( target, framebuffer ) {
  39198. const { gl, currentBoundFramebuffers } = this;
  39199. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39200. gl.bindFramebuffer( target, framebuffer );
  39201. currentBoundFramebuffers[ target ] = framebuffer;
  39202. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39203. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39204. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39205. }
  39206. if ( target === gl.FRAMEBUFFER ) {
  39207. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39208. }
  39209. return true;
  39210. }
  39211. return false;
  39212. }
  39213. /**
  39214. * Defines draw buffers to which fragment colors are written into.
  39215. * Configures the MRT setup of custom framebuffers.
  39216. *
  39217. * This method caches the state so `gl.drawBuffers()` is only
  39218. * called when necessary.
  39219. *
  39220. * @param {RenderContext} renderContext - The render context.
  39221. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  39222. */
  39223. drawBuffers( renderContext, framebuffer ) {
  39224. const { gl } = this;
  39225. let drawBuffers = [];
  39226. let needsUpdate = false;
  39227. if ( renderContext.textures !== null ) {
  39228. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39229. if ( drawBuffers === undefined ) {
  39230. drawBuffers = [];
  39231. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39232. }
  39233. const textures = renderContext.textures;
  39234. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39235. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39236. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39237. }
  39238. drawBuffers.length = textures.length;
  39239. needsUpdate = true;
  39240. }
  39241. } else {
  39242. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39243. drawBuffers[ 0 ] = gl.BACK;
  39244. needsUpdate = true;
  39245. }
  39246. }
  39247. if ( needsUpdate ) {
  39248. gl.drawBuffers( drawBuffers );
  39249. }
  39250. }
  39251. // texture
  39252. /**
  39253. * Makes the given texture unit active.
  39254. *
  39255. * This method caches the state so `gl.activeTexture()` is only
  39256. * called when necessary.
  39257. *
  39258. * @param {Number} webglSlot - The texture unit to make active.
  39259. */
  39260. activeTexture( webglSlot ) {
  39261. const { gl, currentTextureSlot, maxTextures } = this;
  39262. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39263. if ( currentTextureSlot !== webglSlot ) {
  39264. gl.activeTexture( webglSlot );
  39265. this.currentTextureSlot = webglSlot;
  39266. }
  39267. }
  39268. /**
  39269. * Binds the given WebGL texture to a target.
  39270. *
  39271. * This method caches the state so `gl.bindTexture()` is only
  39272. * called when necessary.
  39273. *
  39274. * @param {Number} webglType - The binding point (target).
  39275. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  39276. * @param {Number} webglSlot - The texture.
  39277. */
  39278. bindTexture( webglType, webglTexture, webglSlot ) {
  39279. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39280. if ( webglSlot === undefined ) {
  39281. if ( currentTextureSlot === null ) {
  39282. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39283. } else {
  39284. webglSlot = currentTextureSlot;
  39285. }
  39286. }
  39287. let boundTexture = currentBoundTextures[ webglSlot ];
  39288. if ( boundTexture === undefined ) {
  39289. boundTexture = { type: undefined, texture: undefined };
  39290. currentBoundTextures[ webglSlot ] = boundTexture;
  39291. }
  39292. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39293. if ( currentTextureSlot !== webglSlot ) {
  39294. gl.activeTexture( webglSlot );
  39295. this.currentTextureSlot = webglSlot;
  39296. }
  39297. gl.bindTexture( webglType, webglTexture );
  39298. boundTexture.type = webglType;
  39299. boundTexture.texture = webglTexture;
  39300. }
  39301. }
  39302. /**
  39303. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  39304. *
  39305. * This method caches the state so `gl.bindBufferBase()` is only
  39306. * called when necessary.
  39307. *
  39308. * @param {Number} target - The target for the bind operation.
  39309. * @param {Number} index - The index of the target.
  39310. * @param {WebGLBuffer} buffer - The WebGL buffer.
  39311. * @return {Boolean} Whether a bind has been executed or not.
  39312. */
  39313. bindBufferBase( target, index, buffer ) {
  39314. const { gl } = this;
  39315. const key = `${target}-${index}`;
  39316. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39317. gl.bindBufferBase( target, index, buffer );
  39318. this.currentBoundBufferBases[ key ] = buffer;
  39319. return true;
  39320. }
  39321. return false;
  39322. }
  39323. /**
  39324. * Unbinds the current bound texture.
  39325. *
  39326. * This method caches the state so `gl.bindTexture()` is only
  39327. * called when necessary.
  39328. */
  39329. unbindTexture() {
  39330. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39331. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39332. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39333. gl.bindTexture( boundTexture.type, null );
  39334. boundTexture.type = undefined;
  39335. boundTexture.texture = undefined;
  39336. }
  39337. }
  39338. }
  39339. /**
  39340. * A WebGL 2 backend utility module with common helpers.
  39341. *
  39342. * @private
  39343. */
  39344. class WebGLUtils {
  39345. /**
  39346. * Constructs a new utility object.
  39347. *
  39348. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39349. */
  39350. constructor( backend ) {
  39351. /**
  39352. * A reference to the WebGL 2 backend.
  39353. *
  39354. * @type {WebGLBackend}
  39355. */
  39356. this.backend = backend;
  39357. /**
  39358. * A reference to the rendering context.
  39359. *
  39360. * @type {WebGL2RenderingContext}
  39361. */
  39362. this.gl = this.backend.gl;
  39363. /**
  39364. * A reference to a backend module holding extension-related
  39365. * utility functions.
  39366. *
  39367. * @type {WebGLExtensions}
  39368. */
  39369. this.extensions = backend.extensions;
  39370. }
  39371. /**
  39372. * Converts the given three.js constant into a WebGL constant.
  39373. * The method currently supports the conversion of texture formats
  39374. * and types.
  39375. *
  39376. * @param {Number} p - The three.js constant.
  39377. * @param {String} [colorSpace=NoColorSpace] - The color space.
  39378. * @return {Number} The corresponding WebGL constant.
  39379. */
  39380. convert( p, colorSpace = NoColorSpace ) {
  39381. const { gl, extensions } = this;
  39382. let extension;
  39383. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39384. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39385. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39386. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39387. if ( p === ByteType ) return gl.BYTE;
  39388. if ( p === ShortType ) return gl.SHORT;
  39389. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39390. if ( p === IntType ) return gl.INT;
  39391. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39392. if ( p === FloatType ) return gl.FLOAT;
  39393. if ( p === HalfFloatType ) {
  39394. return gl.HALF_FLOAT;
  39395. }
  39396. if ( p === AlphaFormat ) return gl.ALPHA;
  39397. if ( p === RGBFormat ) return gl.RGB;
  39398. if ( p === RGBAFormat ) return gl.RGBA;
  39399. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39400. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39401. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39402. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39403. // WebGL2 formats.
  39404. if ( p === RedFormat ) return gl.RED;
  39405. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39406. if ( p === RGFormat ) return gl.RG;
  39407. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39408. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39409. // S3TC
  39410. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39411. if ( colorSpace === SRGBColorSpace ) {
  39412. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39413. if ( extension !== null ) {
  39414. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39415. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39416. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39417. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39418. } else {
  39419. return null;
  39420. }
  39421. } else {
  39422. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39423. if ( extension !== null ) {
  39424. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39425. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39426. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39427. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39428. } else {
  39429. return null;
  39430. }
  39431. }
  39432. }
  39433. // PVRTC
  39434. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39435. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39436. if ( extension !== null ) {
  39437. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39438. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39439. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39440. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39441. } else {
  39442. return null;
  39443. }
  39444. }
  39445. // ETC
  39446. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39447. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39448. if ( extension !== null ) {
  39449. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39450. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39451. } else {
  39452. return null;
  39453. }
  39454. }
  39455. // ASTC
  39456. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39457. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39458. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39459. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39460. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39461. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39462. if ( extension !== null ) {
  39463. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39464. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39465. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39466. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39467. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39468. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39469. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39470. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39471. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39472. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39473. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39474. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39475. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39476. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39477. } else {
  39478. return null;
  39479. }
  39480. }
  39481. // BPTC
  39482. if ( p === RGBA_BPTC_Format ) {
  39483. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39484. if ( extension !== null ) {
  39485. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39486. } else {
  39487. return null;
  39488. }
  39489. }
  39490. // RGTC
  39491. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39492. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39493. if ( extension !== null ) {
  39494. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39495. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39496. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39497. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39498. } else {
  39499. return null;
  39500. }
  39501. }
  39502. //
  39503. if ( p === UnsignedInt248Type ) {
  39504. return gl.UNSIGNED_INT_24_8;
  39505. }
  39506. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39507. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39508. }
  39509. /**
  39510. * This method can be used to synchronize the CPU with the GPU by waiting until
  39511. * ongoing GPU commands have been completed.
  39512. *
  39513. * @private
  39514. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  39515. */
  39516. _clientWaitAsync() {
  39517. const { gl } = this;
  39518. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39519. gl.flush();
  39520. return new Promise( ( resolve, reject ) => {
  39521. function test() {
  39522. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39523. if ( res === gl.WAIT_FAILED ) {
  39524. gl.deleteSync( sync );
  39525. reject();
  39526. return;
  39527. }
  39528. if ( res === gl.TIMEOUT_EXPIRED ) {
  39529. requestAnimationFrame( test );
  39530. return;
  39531. }
  39532. gl.deleteSync( sync );
  39533. resolve();
  39534. }
  39535. test();
  39536. } );
  39537. }
  39538. }
  39539. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39540. /**
  39541. * A WebGL 2 backend utility module for managing textures.
  39542. *
  39543. * @private
  39544. */
  39545. class WebGLTextureUtils {
  39546. /**
  39547. * Constructs a new utility object.
  39548. *
  39549. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39550. */
  39551. constructor( backend ) {
  39552. /**
  39553. * A reference to the WebGL 2 backend.
  39554. *
  39555. * @type {WebGLBackend}
  39556. */
  39557. this.backend = backend;
  39558. /**
  39559. * A reference to the rendering context.
  39560. *
  39561. * @type {WebGL2RenderingContext}
  39562. */
  39563. this.gl = backend.gl;
  39564. /**
  39565. * A reference to a backend module holding extension-related
  39566. * utility functions.
  39567. *
  39568. * @type {WebGLExtensions}
  39569. */
  39570. this.extensions = backend.extensions;
  39571. /**
  39572. * A dictionary for managing default textures. The key
  39573. * is the binding point (target), the value the WEbGL texture object.
  39574. *
  39575. * @type {Object<GLenum,WebGLTexture>}
  39576. */
  39577. this.defaultTextures = {};
  39578. if ( initialized === false ) {
  39579. this._init();
  39580. initialized = true;
  39581. }
  39582. }
  39583. /**
  39584. * Inits the state of the utility.
  39585. *
  39586. * @private
  39587. */
  39588. _init() {
  39589. const gl = this.gl;
  39590. // Store only WebGL constants here.
  39591. wrappingToGL = {
  39592. [ RepeatWrapping ]: gl.REPEAT,
  39593. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39594. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39595. };
  39596. filterToGL = {
  39597. [ NearestFilter ]: gl.NEAREST,
  39598. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39599. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39600. [ LinearFilter ]: gl.LINEAR,
  39601. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39602. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39603. };
  39604. compareToGL = {
  39605. [ NeverCompare ]: gl.NEVER,
  39606. [ AlwaysCompare ]: gl.ALWAYS,
  39607. [ LessCompare ]: gl.LESS,
  39608. [ LessEqualCompare ]: gl.LEQUAL,
  39609. [ EqualCompare ]: gl.EQUAL,
  39610. [ GreaterEqualCompare ]: gl.GEQUAL,
  39611. [ GreaterCompare ]: gl.GREATER,
  39612. [ NotEqualCompare ]: gl.NOTEQUAL
  39613. };
  39614. }
  39615. /**
  39616. * Returns the native texture type for the given texture.
  39617. *
  39618. * @param {Texture} texture - The texture.
  39619. * @return {GLenum} The native texture type.
  39620. */
  39621. getGLTextureType( texture ) {
  39622. const { gl } = this;
  39623. let glTextureType;
  39624. if ( texture.isCubeTexture === true ) {
  39625. glTextureType = gl.TEXTURE_CUBE_MAP;
  39626. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39627. glTextureType = gl.TEXTURE_2D_ARRAY;
  39628. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39629. glTextureType = gl.TEXTURE_3D;
  39630. } else {
  39631. glTextureType = gl.TEXTURE_2D;
  39632. }
  39633. return glTextureType;
  39634. }
  39635. /**
  39636. * Returns the native texture type for the given texture.
  39637. *
  39638. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  39639. * @param {GLenum} glFormat - The WebGL format.
  39640. * @param {GLenum} glType - The WebGL type.
  39641. * @param {String} colorSpace - The texture's color space.
  39642. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  39643. * @return {GLenum} The internal format.
  39644. */
  39645. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39646. const { gl, extensions } = this;
  39647. if ( internalFormatName !== null ) {
  39648. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39649. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39650. }
  39651. let internalFormat = glFormat;
  39652. if ( glFormat === gl.RED ) {
  39653. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39654. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39655. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39656. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39657. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39658. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39659. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39660. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39661. }
  39662. if ( glFormat === gl.RED_INTEGER ) {
  39663. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39664. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39665. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39666. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39667. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39668. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39669. }
  39670. if ( glFormat === gl.RG ) {
  39671. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39672. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39673. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39674. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39675. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39676. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39677. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39678. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39679. }
  39680. if ( glFormat === gl.RG_INTEGER ) {
  39681. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39682. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39683. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39684. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39685. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39686. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39687. }
  39688. if ( glFormat === gl.RGB ) {
  39689. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39690. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39691. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39692. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39693. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39694. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39695. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39696. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39697. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39698. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39699. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39700. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39701. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39702. }
  39703. if ( glFormat === gl.RGB_INTEGER ) {
  39704. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39705. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39706. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39707. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39708. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39709. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39710. }
  39711. if ( glFormat === gl.RGBA ) {
  39712. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39713. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39714. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39715. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39716. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39717. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39718. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39719. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39720. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39721. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39722. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39723. }
  39724. if ( glFormat === gl.RGBA_INTEGER ) {
  39725. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39726. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39727. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39728. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39729. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39730. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39731. }
  39732. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39733. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39734. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39735. }
  39736. if ( glFormat === gl.DEPTH_STENCIL ) {
  39737. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39738. }
  39739. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39740. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39741. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39742. extensions.get( 'EXT_color_buffer_float' );
  39743. }
  39744. return internalFormat;
  39745. }
  39746. /**
  39747. * Sets the texture parameters for the given texture.
  39748. *
  39749. * @param {GLenum} textureType - The texture type.
  39750. * @param {Texture} texture - The texture.
  39751. */
  39752. setTextureParameters( textureType, texture ) {
  39753. const { gl, extensions, backend } = this;
  39754. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39755. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39756. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39757. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39758. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39759. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39760. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39761. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39762. }
  39763. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39764. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  39765. // follow WebGPU backend mapping for texture filtering
  39766. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  39767. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39768. if ( texture.compareFunction ) {
  39769. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39770. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39771. }
  39772. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39773. if ( texture.magFilter === NearestFilter ) return;
  39774. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39775. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39776. if ( texture.anisotropy > 1 ) {
  39777. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39778. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39779. }
  39780. }
  39781. }
  39782. /**
  39783. * Creates a default texture for the given texture that can be used
  39784. * as a placeholder until the actual texture is ready for usage.
  39785. *
  39786. * @param {Texture} texture - The texture to create a default texture for.
  39787. */
  39788. createDefaultTexture( texture ) {
  39789. const { gl, backend, defaultTextures } = this;
  39790. const glTextureType = this.getGLTextureType( texture );
  39791. let textureGPU = defaultTextures[ glTextureType ];
  39792. if ( textureGPU === undefined ) {
  39793. textureGPU = gl.createTexture();
  39794. backend.state.bindTexture( glTextureType, textureGPU );
  39795. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39796. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39797. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39798. defaultTextures[ glTextureType ] = textureGPU;
  39799. }
  39800. backend.set( texture, {
  39801. textureGPU,
  39802. glTextureType,
  39803. isDefault: true
  39804. } );
  39805. }
  39806. /**
  39807. * Defines a texture on the GPU for the given texture object.
  39808. *
  39809. * @param {Texture} texture - The texture.
  39810. * @param {Object} [options={}] - Optional configuration parameter.
  39811. * @return {undefined}
  39812. */
  39813. createTexture( texture, options ) {
  39814. const { gl, backend } = this;
  39815. const { levels, width, height, depth } = options;
  39816. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39817. const glType = backend.utils.convert( texture.type );
  39818. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39819. const textureGPU = gl.createTexture();
  39820. const glTextureType = this.getGLTextureType( texture );
  39821. backend.state.bindTexture( glTextureType, textureGPU );
  39822. this.setTextureParameters( glTextureType, texture );
  39823. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  39824. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39825. } else if ( texture.isData3DTexture ) {
  39826. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39827. } else if ( ! texture.isVideoTexture ) {
  39828. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39829. }
  39830. backend.set( texture, {
  39831. textureGPU,
  39832. glTextureType,
  39833. glFormat,
  39834. glType,
  39835. glInternalFormat
  39836. } );
  39837. }
  39838. /**
  39839. * Uploads texture buffer data to the GPU memory.
  39840. *
  39841. * @param {WebGLBuffer} buffer - The buffer data.
  39842. * @param {Texture} texture - The texture,
  39843. */
  39844. copyBufferToTexture( buffer, texture ) {
  39845. const { gl, backend } = this;
  39846. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39847. const { width, height } = texture.source.data;
  39848. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39849. backend.state.bindTexture( glTextureType, textureGPU );
  39850. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39851. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39852. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39853. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39854. backend.state.unbindTexture();
  39855. // debug
  39856. // const framebuffer = gl.createFramebuffer();
  39857. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39858. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39859. // const readout = new Float32Array( width * height * 4 );
  39860. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39861. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39862. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39863. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39864. // console.log( readout );
  39865. }
  39866. /**
  39867. * Uploads the updated texture data to the GPU.
  39868. *
  39869. * @param {Texture} texture - The texture.
  39870. * @param {Object} [options={}] - Optional configuration parameter.
  39871. */
  39872. updateTexture( texture, options ) {
  39873. const { gl } = this;
  39874. const { width, height } = options;
  39875. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39876. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39877. return;
  39878. const getImage = ( source ) => {
  39879. if ( source.isDataTexture ) {
  39880. return source.image.data;
  39881. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  39882. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  39883. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  39884. source instanceof OffscreenCanvas ) {
  39885. return source;
  39886. }
  39887. return source.data;
  39888. };
  39889. this.backend.state.bindTexture( glTextureType, textureGPU );
  39890. this.setTextureParameters( glTextureType, texture );
  39891. if ( texture.isCompressedTexture ) {
  39892. const mipmaps = texture.mipmaps;
  39893. const image = options.image;
  39894. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39895. const mipmap = mipmaps[ i ];
  39896. if ( texture.isCompressedArrayTexture ) {
  39897. if ( texture.format !== gl.RGBA ) {
  39898. if ( glFormat !== null ) {
  39899. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  39900. } else {
  39901. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39902. }
  39903. } else {
  39904. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39905. }
  39906. } else {
  39907. if ( glFormat !== null ) {
  39908. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39909. } else {
  39910. console.warn( 'Unsupported compressed texture format' );
  39911. }
  39912. }
  39913. }
  39914. } else if ( texture.isCubeTexture ) {
  39915. const images = options.images;
  39916. for ( let i = 0; i < 6; i ++ ) {
  39917. const image = getImage( images[ i ] );
  39918. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39919. }
  39920. } else if ( texture.isDataArrayTexture ) {
  39921. const image = options.image;
  39922. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39923. } else if ( texture.isData3DTexture ) {
  39924. const image = options.image;
  39925. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39926. } else if ( texture.isVideoTexture ) {
  39927. texture.update();
  39928. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39929. } else {
  39930. const image = getImage( options.image );
  39931. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39932. }
  39933. }
  39934. /**
  39935. * Generates mipmaps for the given texture.
  39936. *
  39937. * @param {Texture} texture - The texture.
  39938. */
  39939. generateMipmaps( texture ) {
  39940. const { gl, backend } = this;
  39941. const { textureGPU, glTextureType } = backend.get( texture );
  39942. backend.state.bindTexture( glTextureType, textureGPU );
  39943. gl.generateMipmap( glTextureType );
  39944. }
  39945. /**
  39946. * Deallocates the render buffers of the given render target.
  39947. *
  39948. * @param {RenderTarget} renderTarget - The render target.
  39949. */
  39950. deallocateRenderBuffers( renderTarget ) {
  39951. const { gl, backend } = this;
  39952. // remove framebuffer reference
  39953. if ( renderTarget ) {
  39954. const renderContextData = backend.get( renderTarget );
  39955. renderContextData.renderBufferStorageSetup = undefined;
  39956. if ( renderContextData.framebuffers ) {
  39957. for ( const cacheKey in renderContextData.framebuffers ) {
  39958. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  39959. }
  39960. delete renderContextData.framebuffers;
  39961. }
  39962. if ( renderContextData.depthRenderbuffer ) {
  39963. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39964. delete renderContextData.depthRenderbuffer;
  39965. }
  39966. if ( renderContextData.stencilRenderbuffer ) {
  39967. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39968. delete renderContextData.stencilRenderbuffer;
  39969. }
  39970. if ( renderContextData.msaaFrameBuffer ) {
  39971. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39972. delete renderContextData.msaaFrameBuffer;
  39973. }
  39974. if ( renderContextData.msaaRenderbuffers ) {
  39975. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39976. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39977. }
  39978. delete renderContextData.msaaRenderbuffers;
  39979. }
  39980. }
  39981. }
  39982. /**
  39983. * Destroys the GPU data for the given texture object.
  39984. *
  39985. * @param {Texture} texture - The texture.
  39986. */
  39987. destroyTexture( texture ) {
  39988. const { gl, backend } = this;
  39989. const { textureGPU, renderTarget } = backend.get( texture );
  39990. this.deallocateRenderBuffers( renderTarget );
  39991. gl.deleteTexture( textureGPU );
  39992. backend.delete( texture );
  39993. }
  39994. /**
  39995. * Copies data of the given source texture to the given destination texture.
  39996. *
  39997. * @param {Texture} srcTexture - The source texture.
  39998. * @param {Texture} dstTexture - The destination texture.
  39999. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  40000. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  40001. * @param {Number} [level=0] - The mip level to copy.
  40002. */
  40003. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40004. const { gl, backend } = this;
  40005. const { state } = this.backend;
  40006. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40007. let width, height, minX, minY;
  40008. let dstX, dstY;
  40009. if ( srcRegion !== null ) {
  40010. width = srcRegion.max.x - srcRegion.min.x;
  40011. height = srcRegion.max.y - srcRegion.min.y;
  40012. minX = srcRegion.min.x;
  40013. minY = srcRegion.min.y;
  40014. } else {
  40015. width = srcTexture.image.width;
  40016. height = srcTexture.image.height;
  40017. minX = 0;
  40018. minY = 0;
  40019. }
  40020. if ( dstPosition !== null ) {
  40021. dstX = dstPosition.x;
  40022. dstY = dstPosition.y;
  40023. } else {
  40024. dstX = 0;
  40025. dstY = 0;
  40026. }
  40027. state.bindTexture( glTextureType, dstTextureGPU );
  40028. // As another texture upload may have changed pixelStorei
  40029. // parameters, make sure they are correct for the dstTexture
  40030. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40031. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40032. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40033. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40034. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40035. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40036. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40037. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40038. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40039. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40040. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40041. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40042. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40043. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40044. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40045. const srcTextureData = backend.get( srcTexture );
  40046. const dstTextureData = backend.get( dstTexture );
  40047. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40048. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40049. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40050. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40051. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40052. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40053. let mask = gl.COLOR_BUFFER_BIT;
  40054. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40055. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40056. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40057. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40058. } else {
  40059. if ( srcTexture.isDataTexture ) {
  40060. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40061. } else {
  40062. if ( srcTexture.isCompressedTexture ) {
  40063. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40064. } else {
  40065. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40066. }
  40067. }
  40068. }
  40069. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40070. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40071. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40072. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40073. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40074. // Generate mipmaps only when copying level 0
  40075. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40076. state.unbindTexture();
  40077. }
  40078. /**
  40079. * Copies the current bound framebuffer to the given texture.
  40080. *
  40081. * @param {Texture} texture - The destination texture.
  40082. * @param {RenderContext} renderContext - The render context.
  40083. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40084. */
  40085. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40086. const { gl } = this;
  40087. const { state } = this.backend;
  40088. const { textureGPU } = this.backend.get( texture );
  40089. const { x, y, z: width, w: height } = rectangle;
  40090. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40091. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  40092. if ( requireDrawFrameBuffer ) {
  40093. const partial = ( x !== 0 || y !== 0 );
  40094. let mask;
  40095. let attachment;
  40096. if ( texture.isDepthTexture === true ) {
  40097. mask = gl.DEPTH_BUFFER_BIT;
  40098. attachment = gl.DEPTH_ATTACHMENT;
  40099. if ( renderContext.stencil ) {
  40100. mask |= gl.STENCIL_BUFFER_BIT;
  40101. }
  40102. } else {
  40103. mask = gl.COLOR_BUFFER_BIT;
  40104. attachment = gl.COLOR_ATTACHMENT0;
  40105. }
  40106. if ( partial ) {
  40107. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40108. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40109. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40110. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40111. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40112. const flippedY = srcHeight - y - height;
  40113. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40114. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40115. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40116. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40117. state.unbindTexture();
  40118. } else {
  40119. const fb = gl.createFramebuffer();
  40120. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40121. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40122. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40123. gl.deleteFramebuffer( fb );
  40124. }
  40125. } else {
  40126. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40127. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40128. state.unbindTexture();
  40129. }
  40130. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40131. this.backend._setFramebuffer( renderContext );
  40132. }
  40133. /**
  40134. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  40135. *
  40136. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  40137. * @param {RenderContext} renderContext - The render context.
  40138. */
  40139. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40140. const { gl } = this;
  40141. const renderTarget = renderContext.renderTarget;
  40142. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40143. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40144. if ( depthBuffer && ! stencilBuffer ) {
  40145. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40146. if ( samples > 0 ) {
  40147. if ( depthTexture && depthTexture.isDepthTexture ) {
  40148. if ( depthTexture.type === gl.FLOAT ) {
  40149. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40150. }
  40151. }
  40152. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40153. } else {
  40154. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40155. }
  40156. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40157. } else if ( depthBuffer && stencilBuffer ) {
  40158. if ( samples > 0 ) {
  40159. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40160. } else {
  40161. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40162. }
  40163. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40164. }
  40165. }
  40166. /**
  40167. * Returns texture data as a typed array.
  40168. *
  40169. * @async
  40170. * @param {Texture} texture - The texture to copy.
  40171. * @param {Number} x - The x coordinate of the copy origin.
  40172. * @param {Number} y - The y coordinate of the copy origin.
  40173. * @param {Number} width - The width of the copy.
  40174. * @param {Number} height - The height of the copy.
  40175. * @param {Number} faceIndex - The face index.
  40176. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40177. */
  40178. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40179. const { backend, gl } = this;
  40180. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40181. const fb = gl.createFramebuffer();
  40182. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40183. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40184. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40185. const typedArrayType = this._getTypedArrayType( glType );
  40186. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40187. const elementCount = width * height;
  40188. const byteLength = elementCount * bytesPerTexel;
  40189. const buffer = gl.createBuffer();
  40190. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40191. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40192. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40193. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40194. await backend.utils._clientWaitAsync();
  40195. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40196. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40197. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40198. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40199. gl.deleteFramebuffer( fb );
  40200. return dstBuffer;
  40201. }
  40202. /**
  40203. * Returns the corresponding typed array type for the given WebGL data type.
  40204. *
  40205. * @private
  40206. * @param {GLenum} glType - The WebGL data type.
  40207. * @return {TypedArray.constructor} The typed array type.
  40208. */
  40209. _getTypedArrayType( glType ) {
  40210. const { gl } = this;
  40211. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40212. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40213. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40214. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40215. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40216. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40217. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40218. if ( glType === gl.FLOAT ) return Float32Array;
  40219. throw new Error( `Unsupported WebGL type: ${glType}` );
  40220. }
  40221. /**
  40222. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  40223. *
  40224. * @private
  40225. * @param {GLenum} glType - The WebGL data type.
  40226. * @param {GLenum} glFormat - The WebGL texture format.
  40227. * @return {Number} The bytes-per-texel.
  40228. */
  40229. _getBytesPerTexel( glType, glFormat ) {
  40230. const { gl } = this;
  40231. let bytesPerComponent = 0;
  40232. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40233. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40234. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40235. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40236. glType === gl.UNSIGNED_SHORT ||
  40237. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40238. if ( glType === gl.UNSIGNED_INT ||
  40239. glType === gl.FLOAT ) bytesPerComponent = 4;
  40240. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40241. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40242. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40243. }
  40244. }
  40245. /**
  40246. * A WebGL 2 backend utility module for managing extensions.
  40247. *
  40248. * @private
  40249. */
  40250. class WebGLExtensions {
  40251. /**
  40252. * Constructs a new utility object.
  40253. *
  40254. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40255. */
  40256. constructor( backend ) {
  40257. /**
  40258. * A reference to the WebGL 2 backend.
  40259. *
  40260. * @type {WebGLBackend}
  40261. */
  40262. this.backend = backend;
  40263. /**
  40264. * A reference to the rendering context.
  40265. *
  40266. * @type {WebGL2RenderingContext}
  40267. */
  40268. this.gl = this.backend.gl;
  40269. /**
  40270. * A list with all the supported WebGL extensions.
  40271. *
  40272. * @type {Array<String>}
  40273. */
  40274. this.availableExtensions = this.gl.getSupportedExtensions();
  40275. /**
  40276. * A dictionary with requested WebGL extensions.
  40277. * The key is the name of the extension, the value
  40278. * the requested extension object.
  40279. *
  40280. * @type {Object<String,Object>}
  40281. */
  40282. this.extensions = {};
  40283. }
  40284. /**
  40285. * Returns the extension object for the given extension name.
  40286. *
  40287. * @param {String} name - The extension name.
  40288. * @return {Object} The extension object.
  40289. */
  40290. get( name ) {
  40291. let extension = this.extensions[ name ];
  40292. if ( extension === undefined ) {
  40293. extension = this.gl.getExtension( name );
  40294. this.extensions[ name ] = extension;
  40295. }
  40296. return extension;
  40297. }
  40298. /**
  40299. * Returns `true` if the requested extension is available.
  40300. *
  40301. * @param {String} name - The extension name.
  40302. * @return {Boolean} Whether the given extension is available or not.
  40303. */
  40304. has( name ) {
  40305. return this.availableExtensions.includes( name );
  40306. }
  40307. }
  40308. /**
  40309. * A WebGL 2 backend utility module for managing the device's capabilities.
  40310. *
  40311. * @private
  40312. */
  40313. class WebGLCapabilities {
  40314. /**
  40315. * Constructs a new utility object.
  40316. *
  40317. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40318. */
  40319. constructor( backend ) {
  40320. /**
  40321. * A reference to the WebGL 2 backend.
  40322. *
  40323. * @type {WebGLBackend}
  40324. */
  40325. this.backend = backend;
  40326. /**
  40327. * This value holds the cached max anisotropy value.
  40328. *
  40329. * @type {Number?}
  40330. * @default null
  40331. */
  40332. this.maxAnisotropy = null;
  40333. }
  40334. /**
  40335. * Returns the maximum anisotropy texture filtering value. This value
  40336. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  40337. * WebGL extension.
  40338. *
  40339. * @return {Number} The maximum anisotropy texture filtering value.
  40340. */
  40341. getMaxAnisotropy() {
  40342. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40343. const gl = this.backend.gl;
  40344. const extensions = this.backend.extensions;
  40345. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40346. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40347. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40348. } else {
  40349. this.maxAnisotropy = 0;
  40350. }
  40351. return this.maxAnisotropy;
  40352. }
  40353. }
  40354. const GLFeatureName = {
  40355. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40356. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40357. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40358. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40359. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40360. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40361. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40362. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40363. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40364. };
  40365. class WebGLBufferRenderer {
  40366. constructor( backend ) {
  40367. this.gl = backend.gl;
  40368. this.extensions = backend.extensions;
  40369. this.info = backend.renderer.info;
  40370. this.mode = null;
  40371. this.index = 0;
  40372. this.type = null;
  40373. this.object = null;
  40374. }
  40375. render( start, count ) {
  40376. const { gl, mode, object, type, info, index } = this;
  40377. if ( index !== 0 ) {
  40378. gl.drawElements( mode, count, type, start );
  40379. } else {
  40380. gl.drawArrays( mode, start, count );
  40381. }
  40382. info.update( object, count, mode, 1 );
  40383. }
  40384. renderInstances( start, count, primcount ) {
  40385. const { gl, mode, type, index, object, info } = this;
  40386. if ( primcount === 0 ) return;
  40387. if ( index !== 0 ) {
  40388. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40389. } else {
  40390. gl.drawArraysInstanced( mode, start, count, primcount );
  40391. }
  40392. info.update( object, count, mode, primcount );
  40393. }
  40394. renderMultiDraw( starts, counts, drawCount ) {
  40395. const { extensions, mode, object, info } = this;
  40396. if ( drawCount === 0 ) return;
  40397. const extension = extensions.get( 'WEBGL_multi_draw' );
  40398. if ( extension === null ) {
  40399. for ( let i = 0; i < drawCount; i ++ ) {
  40400. this.render( starts[ i ], counts[ i ] );
  40401. }
  40402. } else {
  40403. if ( this.index !== 0 ) {
  40404. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40405. } else {
  40406. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40407. }
  40408. let elementCount = 0;
  40409. for ( let i = 0; i < drawCount; i ++ ) {
  40410. elementCount += counts[ i ];
  40411. }
  40412. info.update( object, elementCount, mode, 1 );
  40413. }
  40414. }
  40415. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40416. const { extensions, mode, object, info } = this;
  40417. if ( drawCount === 0 ) return;
  40418. const extension = extensions.get( 'WEBGL_multi_draw' );
  40419. if ( extension === null ) {
  40420. for ( let i = 0; i < drawCount; i ++ ) {
  40421. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40422. }
  40423. } else {
  40424. if ( this.index !== 0 ) {
  40425. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40426. } else {
  40427. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40428. }
  40429. let elementCount = 0;
  40430. for ( let i = 0; i < drawCount; i ++ ) {
  40431. elementCount += counts[ i ] * primcount[ i ];
  40432. }
  40433. info.update( object, elementCount, mode, 1 );
  40434. }
  40435. }
  40436. //
  40437. }
  40438. class TimestampQueryPool {
  40439. constructor( maxQueries = 256 ) {
  40440. this.trackTimestamp = true;
  40441. this.maxQueries = maxQueries;
  40442. this.currentQueryIndex = 0; // how many queries allocated so far
  40443. this.queryOffsets = new Map(); // track offsets for different contexts
  40444. this.isDisposed = false;
  40445. this.lastValue = 0;
  40446. this.pendingResolve = false;
  40447. }
  40448. /**
  40449. * Allocate queries for a specific renderContext.
  40450. *
  40451. * @abstract
  40452. */
  40453. allocateQueriesForContext( /* renderContext */ ) {}
  40454. /**
  40455. * Resolve all timestamps and return data (or process them).
  40456. *
  40457. * @abstract
  40458. * @returns {Promise<Number>|Number} The resolved timestamp value.
  40459. */
  40460. async resolveQueriesAsync() {}
  40461. /**
  40462. * Dispose of the query pool.
  40463. *
  40464. * @abstract
  40465. */
  40466. dispose() {}
  40467. }
  40468. /**
  40469. * Manages a pool of WebGL timestamp queries for performance measurement.
  40470. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  40471. * @extends TimestampQueryPool
  40472. */
  40473. class WebGLTimestampQueryPool extends TimestampQueryPool {
  40474. /**
  40475. * Creates a new WebGL timestamp query pool.
  40476. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  40477. * @param {string} type - The type identifier for this query pool.
  40478. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  40479. */
  40480. constructor( gl, type, maxQueries = 2048 ) {
  40481. super( maxQueries );
  40482. this.gl = gl;
  40483. this.type = type;
  40484. // Check for timer query extensions
  40485. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  40486. gl.getExtension( 'EXT_disjoint_timer_query' );
  40487. if ( ! this.ext ) {
  40488. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  40489. this.trackTimestamp = false;
  40490. return;
  40491. }
  40492. // Create query objects
  40493. this.queries = [];
  40494. for ( let i = 0; i < this.maxQueries; i ++ ) {
  40495. this.queries.push( gl.createQuery() );
  40496. }
  40497. this.activeQuery = null;
  40498. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  40499. }
  40500. /**
  40501. * Allocates a pair of queries for a given render context.
  40502. * @param {Object} renderContext - The render context to allocate queries for.
  40503. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  40504. */
  40505. allocateQueriesForContext( renderContext ) {
  40506. if ( ! this.trackTimestamp ) return null;
  40507. // Check if we have enough space for a new query pair
  40508. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  40509. return null;
  40510. }
  40511. const baseOffset = this.currentQueryIndex;
  40512. this.currentQueryIndex += 2;
  40513. // Initialize query states
  40514. this.queryStates.set( baseOffset, 'inactive' );
  40515. this.queryOffsets.set( renderContext.id, baseOffset );
  40516. return baseOffset;
  40517. }
  40518. /**
  40519. * Begins a timestamp query for the specified render context.
  40520. * @param {Object} renderContext - The render context to begin timing for.
  40521. */
  40522. beginQuery( renderContext ) {
  40523. if ( ! this.trackTimestamp || this.isDisposed ) {
  40524. return;
  40525. }
  40526. const baseOffset = this.queryOffsets.get( renderContext.id );
  40527. if ( baseOffset == null ) {
  40528. return;
  40529. }
  40530. // Don't start a new query if there's an active one
  40531. if ( this.activeQuery !== null ) {
  40532. return;
  40533. }
  40534. const query = this.queries[ baseOffset ];
  40535. if ( ! query ) {
  40536. return;
  40537. }
  40538. try {
  40539. // Only begin if query is inactive
  40540. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  40541. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  40542. this.activeQuery = baseOffset;
  40543. this.queryStates.set( baseOffset, 'started' );
  40544. }
  40545. } catch ( error ) {
  40546. console.error( 'Error in beginQuery:', error );
  40547. this.activeQuery = null;
  40548. this.queryStates.set( baseOffset, 'inactive' );
  40549. }
  40550. }
  40551. /**
  40552. * Ends the active timestamp query for the specified render context.
  40553. * @param {Object} renderContext - The render context to end timing for.
  40554. * @param {string} renderContext.id - Unique identifier for the render context.
  40555. */
  40556. endQuery( renderContext ) {
  40557. if ( ! this.trackTimestamp || this.isDisposed ) {
  40558. return;
  40559. }
  40560. const baseOffset = this.queryOffsets.get( renderContext.id );
  40561. if ( baseOffset == null ) {
  40562. return;
  40563. }
  40564. // Only end if this is the active query
  40565. if ( this.activeQuery !== baseOffset ) {
  40566. return;
  40567. }
  40568. try {
  40569. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  40570. this.queryStates.set( baseOffset, 'ended' );
  40571. this.activeQuery = null;
  40572. } catch ( error ) {
  40573. console.error( 'Error in endQuery:', error );
  40574. // Reset state on error
  40575. this.queryStates.set( baseOffset, 'inactive' );
  40576. this.activeQuery = null;
  40577. }
  40578. }
  40579. /**
  40580. * Asynchronously resolves all completed queries and returns the total duration.
  40581. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  40582. */
  40583. async resolveQueriesAsync() {
  40584. if ( ! this.trackTimestamp || this.pendingResolve ) {
  40585. return this.lastValue;
  40586. }
  40587. this.pendingResolve = true;
  40588. try {
  40589. // Wait for all ended queries to complete
  40590. const resolvePromises = [];
  40591. for ( const [ baseOffset, state ] of this.queryStates ) {
  40592. if ( state === 'ended' ) {
  40593. const query = this.queries[ baseOffset ];
  40594. resolvePromises.push( this.resolveQuery( query ) );
  40595. }
  40596. }
  40597. if ( resolvePromises.length === 0 ) {
  40598. return this.lastValue;
  40599. }
  40600. const results = await Promise.all( resolvePromises );
  40601. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  40602. // Store the last valid result
  40603. this.lastValue = totalDuration;
  40604. // Reset states
  40605. this.currentQueryIndex = 0;
  40606. this.queryOffsets.clear();
  40607. this.queryStates.clear();
  40608. this.activeQuery = null;
  40609. return totalDuration;
  40610. } catch ( error ) {
  40611. console.error( 'Error resolving queries:', error );
  40612. return this.lastValue;
  40613. } finally {
  40614. this.pendingResolve = false;
  40615. }
  40616. }
  40617. /**
  40618. * Resolves a single query, checking for completion and disjoint operation.
  40619. * @private
  40620. * @param {WebGLQuery} query - The query object to resolve.
  40621. * @returns {Promise<number>} The elapsed time in milliseconds.
  40622. */
  40623. async resolveQuery( query ) {
  40624. return new Promise( ( resolve ) => {
  40625. if ( this.isDisposed ) {
  40626. resolve( this.lastValue );
  40627. return;
  40628. }
  40629. let timeoutId;
  40630. let isResolved = false;
  40631. const cleanup = () => {
  40632. if ( timeoutId ) {
  40633. clearTimeout( timeoutId );
  40634. timeoutId = null;
  40635. }
  40636. };
  40637. const finalizeResolution = ( value ) => {
  40638. if ( ! isResolved ) {
  40639. isResolved = true;
  40640. cleanup();
  40641. resolve( value );
  40642. }
  40643. };
  40644. const checkQuery = () => {
  40645. if ( this.isDisposed ) {
  40646. finalizeResolution( this.lastValue );
  40647. return;
  40648. }
  40649. try {
  40650. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  40651. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  40652. if ( disjoint ) {
  40653. finalizeResolution( this.lastValue );
  40654. return;
  40655. }
  40656. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  40657. if ( ! available ) {
  40658. timeoutId = setTimeout( checkQuery, 1 );
  40659. return;
  40660. }
  40661. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  40662. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  40663. } catch ( error ) {
  40664. console.error( 'Error checking query:', error );
  40665. resolve( this.lastValue );
  40666. }
  40667. };
  40668. checkQuery();
  40669. } );
  40670. }
  40671. /**
  40672. * Releases all resources held by this query pool.
  40673. * This includes deleting all query objects and clearing internal state.
  40674. */
  40675. dispose() {
  40676. if ( this.isDisposed ) {
  40677. return;
  40678. }
  40679. this.isDisposed = true;
  40680. if ( ! this.trackTimestamp ) return;
  40681. for ( const query of this.queries ) {
  40682. this.gl.deleteQuery( query );
  40683. }
  40684. this.queries = [];
  40685. this.queryStates.clear();
  40686. this.queryOffsets.clear();
  40687. this.lastValue = 0;
  40688. this.activeQuery = null;
  40689. }
  40690. }
  40691. /**
  40692. * A backend implementation targeting WebGL 2.
  40693. *
  40694. * @private
  40695. * @augments Backend
  40696. */
  40697. class WebGLBackend extends Backend {
  40698. /**
  40699. * Constructs a new WebGPU backend.
  40700. *
  40701. * @param {Object} parameters - The configuration parameter.
  40702. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40703. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40704. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40705. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40706. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40707. * @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.
  40708. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  40709. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  40710. */
  40711. constructor( parameters = {} ) {
  40712. super( parameters );
  40713. /**
  40714. * This flag can be used for type testing.
  40715. *
  40716. * @type {Boolean}
  40717. * @readonly
  40718. * @default true
  40719. */
  40720. this.isWebGLBackend = true;
  40721. /**
  40722. * A reference to a backend module holding shader attribute-related
  40723. * utility functions.
  40724. *
  40725. * @type {WebGLAttributeUtils?}
  40726. * @default null
  40727. */
  40728. this.attributeUtils = null;
  40729. /**
  40730. * A reference to a backend module holding extension-related
  40731. * utility functions.
  40732. *
  40733. * @type {WebGLExtensions?}
  40734. * @default null
  40735. */
  40736. this.extensions = null;
  40737. /**
  40738. * A reference to a backend module holding capability-related
  40739. * utility functions.
  40740. *
  40741. * @type {WebGLCapabilities?}
  40742. * @default null
  40743. */
  40744. this.capabilities = null;
  40745. /**
  40746. * A reference to a backend module holding texture-related
  40747. * utility functions.
  40748. *
  40749. * @type {WebGLTextureUtils?}
  40750. * @default null
  40751. */
  40752. this.textureUtils = null;
  40753. /**
  40754. * A reference to a backend module holding renderer-related
  40755. * utility functions.
  40756. *
  40757. * @type {WebGLBufferRenderer?}
  40758. * @default null
  40759. */
  40760. this.bufferRenderer = null;
  40761. /**
  40762. * A reference to the rendering context.
  40763. *
  40764. * @type {WebGL2RenderingContext?}
  40765. * @default null
  40766. */
  40767. this.gl = null;
  40768. /**
  40769. * A reference to a backend module holding state-related
  40770. * utility functions.
  40771. *
  40772. * @type {WebGLState?}
  40773. * @default null
  40774. */
  40775. this.state = null;
  40776. /**
  40777. * A reference to a backend module holding common
  40778. * utility functions.
  40779. *
  40780. * @type {WebGLUtils?}
  40781. * @default null
  40782. */
  40783. this.utils = null;
  40784. /**
  40785. * Dictionary for caching VAOs.
  40786. *
  40787. * @type {Object<String,WebGLVertexArrayObject>}
  40788. */
  40789. this.vaoCache = {};
  40790. /**
  40791. * Dictionary for caching transform feedback objects.
  40792. *
  40793. * @type {Object<String,WebGLTransformFeedback>}
  40794. */
  40795. this.transformFeedbackCache = {};
  40796. /**
  40797. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  40798. * Only relevant when using compute shaders.
  40799. *
  40800. * @type {Boolean}
  40801. * @default false
  40802. */
  40803. this.discard = false;
  40804. /**
  40805. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  40806. * device does not support the extension.
  40807. *
  40808. * @type {EXTDisjointTimerQueryWebGL2?}
  40809. * @default null
  40810. */
  40811. this.disjoint = null;
  40812. /**
  40813. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  40814. * device does not support the extension.
  40815. *
  40816. * @type {KHRParallelShaderCompile?}
  40817. * @default null
  40818. */
  40819. this.parallel = null;
  40820. /**
  40821. * Whether to track timestamps with a Timestamp Query API or not.
  40822. *
  40823. * @type {Boolean}
  40824. * @default false
  40825. */
  40826. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40827. /**
  40828. * A reference to the current render context.
  40829. *
  40830. * @private
  40831. * @type {RenderContext}
  40832. * @default null
  40833. */
  40834. this._currentContext = null;
  40835. /**
  40836. * A unique collection of bindings.
  40837. *
  40838. * @private
  40839. * @type {WeakSet}
  40840. */
  40841. this._knownBindings = new WeakSet();
  40842. /**
  40843. * The target framebuffer when rendering with
  40844. * the WebXR device API.
  40845. *
  40846. * @private
  40847. * @type {WebGLFramebuffer}
  40848. * @default null
  40849. */
  40850. this._xrFamebuffer = null;
  40851. }
  40852. /**
  40853. * Initializes the backend so it is ready for usage.
  40854. *
  40855. * @param {Renderer} renderer - The renderer.
  40856. */
  40857. init( renderer ) {
  40858. super.init( renderer );
  40859. //
  40860. const parameters = this.parameters;
  40861. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40862. function onContextLost( event ) {
  40863. event.preventDefault();
  40864. const contextLossInfo = {
  40865. api: 'WebGL',
  40866. message: event.statusMessage || 'Unknown reason',
  40867. reason: null,
  40868. originalEvent: event
  40869. };
  40870. renderer.onDeviceLost( contextLossInfo );
  40871. }
  40872. this._onContextLost = onContextLost;
  40873. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40874. this.gl = glContext;
  40875. this.extensions = new WebGLExtensions( this );
  40876. this.capabilities = new WebGLCapabilities( this );
  40877. this.attributeUtils = new WebGLAttributeUtils( this );
  40878. this.textureUtils = new WebGLTextureUtils( this );
  40879. this.bufferRenderer = new WebGLBufferRenderer( this );
  40880. this.state = new WebGLState( this );
  40881. this.utils = new WebGLUtils( this );
  40882. this.extensions.get( 'EXT_color_buffer_float' );
  40883. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40884. this.extensions.get( 'OES_texture_float_linear' );
  40885. this.extensions.get( 'EXT_color_buffer_half_float' );
  40886. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40887. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40888. this.extensions.get( 'WEBGL_multi_draw' );
  40889. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40890. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40891. }
  40892. /**
  40893. * The coordinate system of the backend.
  40894. *
  40895. * @type {Number}
  40896. * @readonly
  40897. */
  40898. get coordinateSystem() {
  40899. return WebGLCoordinateSystem;
  40900. }
  40901. /**
  40902. * This method performs a readback operation by moving buffer data from
  40903. * a storage buffer attribute from the GPU to the CPU.
  40904. *
  40905. * @async
  40906. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40907. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40908. */
  40909. async getArrayBufferAsync( attribute ) {
  40910. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40911. }
  40912. /**
  40913. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40914. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40915. *
  40916. * @async
  40917. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40918. */
  40919. async waitForGPU() {
  40920. await this.utils._clientWaitAsync();
  40921. }
  40922. /**
  40923. * Ensures the backend is XR compatible.
  40924. *
  40925. * @async
  40926. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  40927. */
  40928. async makeXRCompatible() {
  40929. const attributes = this.gl.getContextAttributes();
  40930. if ( attributes.xrCompatible !== true ) {
  40931. await this.gl.makeXRCompatible();
  40932. }
  40933. }
  40934. /**
  40935. * Sets the XR rendering destination.
  40936. *
  40937. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  40938. */
  40939. setXRTarget( xrFamebuffer ) {
  40940. this._xrFamebuffer = xrFamebuffer;
  40941. }
  40942. /**
  40943. * Configures the given XR render target with external textures.
  40944. *
  40945. * This method is only relevant when using the WebXR Layers API.
  40946. *
  40947. * @param {XRRenderTarget} renderTarget - The XR render target.
  40948. * @param {WebGLTexture} colorTexture - A native color texture.
  40949. * @param {WebGLTexture?} [depthTexture=null] - A native depth texture.
  40950. */
  40951. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  40952. const gl = this.gl;
  40953. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  40954. if ( depthTexture !== null ) {
  40955. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40956. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  40957. renderTarget.autoAllocateDepthBuffer = false;
  40958. }
  40959. }
  40960. /**
  40961. * Inits a time stamp query for the given render context.
  40962. *
  40963. * @param {RenderContext} renderContext - The render context.
  40964. */
  40965. initTimestampQuery( renderContext ) {
  40966. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40967. const type = renderContext.isComputeNode ? 'compute' : 'render';
  40968. if ( ! this.timestampQueryPool[ type ] ) {
  40969. // TODO: Variable maxQueries?
  40970. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  40971. }
  40972. const timestampQueryPool = this.timestampQueryPool[ type ];
  40973. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  40974. if ( baseOffset !== null ) {
  40975. timestampQueryPool.beginQuery( renderContext );
  40976. }
  40977. }
  40978. // timestamp utils
  40979. /**
  40980. * Prepares the timestamp buffer.
  40981. *
  40982. * @param {RenderContext} renderContext - The render context.
  40983. */
  40984. prepareTimestampBuffer( renderContext ) {
  40985. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40986. const type = renderContext.isComputeNode ? 'compute' : 'render';
  40987. const timestampQueryPool = this.timestampQueryPool[ type ];
  40988. timestampQueryPool.endQuery( renderContext );
  40989. }
  40990. /**
  40991. * Returns the backend's rendering context.
  40992. *
  40993. * @return {WebGL2RenderingContext} The rendering context.
  40994. */
  40995. getContext() {
  40996. return this.gl;
  40997. }
  40998. /**
  40999. * This method is executed at the beginning of a render call and prepares
  41000. * the WebGL state for upcoming render calls
  41001. *
  41002. * @param {RenderContext} renderContext - The render context.
  41003. */
  41004. beginRender( renderContext ) {
  41005. const { state, gl } = this;
  41006. const renderContextData = this.get( renderContext );
  41007. //
  41008. //
  41009. this.initTimestampQuery( renderContext );
  41010. renderContextData.previousContext = this._currentContext;
  41011. this._currentContext = renderContext;
  41012. this._setFramebuffer( renderContext );
  41013. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41014. //
  41015. if ( renderContext.viewport ) {
  41016. this.updateViewport( renderContext );
  41017. } else {
  41018. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41019. }
  41020. if ( renderContext.scissor ) {
  41021. const { x, y, width, height } = renderContext.scissorValue;
  41022. state.scissor( x, renderContext.height - height - y, width, height );
  41023. }
  41024. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41025. if ( occlusionQueryCount > 0 ) {
  41026. // Get a reference to the array of objects with queries. The renderContextData property
  41027. // can be changed by another render pass before the async reading of all previous queries complete
  41028. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41029. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41030. renderContextData.lastOcclusionObject = null;
  41031. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41032. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41033. renderContextData.occlusionQueryIndex = 0;
  41034. }
  41035. }
  41036. /**
  41037. * This method is executed at the end of a render call and finalizes work
  41038. * after draw calls.
  41039. *
  41040. * @param {RenderContext} renderContext - The render context.
  41041. */
  41042. finishRender( renderContext ) {
  41043. const { gl, state } = this;
  41044. const renderContextData = this.get( renderContext );
  41045. const previousContext = renderContextData.previousContext;
  41046. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41047. if ( occlusionQueryCount > 0 ) {
  41048. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41049. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41050. }
  41051. this.resolveOccludedAsync( renderContext );
  41052. }
  41053. const textures = renderContext.textures;
  41054. if ( textures !== null ) {
  41055. for ( let i = 0; i < textures.length; i ++ ) {
  41056. const texture = textures[ i ];
  41057. if ( texture.generateMipmaps ) {
  41058. this.generateMipmaps( texture );
  41059. }
  41060. }
  41061. }
  41062. this._currentContext = previousContext;
  41063. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41064. const renderTargetContextData = this.get( renderContext.renderTarget );
  41065. const { samples } = renderContext.renderTarget;
  41066. if ( samples > 0 ) {
  41067. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41068. const mask = gl.COLOR_BUFFER_BIT;
  41069. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41070. const textures = renderContext.textures;
  41071. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41072. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41073. for ( let i = 0; i < textures.length; i ++ ) {
  41074. // TODO Add support for MRT
  41075. if ( renderContext.scissor ) {
  41076. const { x, y, width, height } = renderContext.scissorValue;
  41077. const viewY = renderContext.height - height - y;
  41078. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41079. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41080. } else {
  41081. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41082. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41083. }
  41084. }
  41085. }
  41086. }
  41087. if ( previousContext !== null ) {
  41088. this._setFramebuffer( previousContext );
  41089. if ( previousContext.viewport ) {
  41090. this.updateViewport( previousContext );
  41091. } else {
  41092. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41093. }
  41094. }
  41095. this.prepareTimestampBuffer( renderContext );
  41096. }
  41097. /**
  41098. * This method processes the result of occlusion queries and writes it
  41099. * into render context data.
  41100. *
  41101. * @async
  41102. * @param {RenderContext} renderContext - The render context.
  41103. */
  41104. resolveOccludedAsync( renderContext ) {
  41105. const renderContextData = this.get( renderContext );
  41106. // handle occlusion query results
  41107. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41108. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41109. const occluded = new WeakSet();
  41110. const { gl } = this;
  41111. renderContextData.currentOcclusionQueryObjects = null;
  41112. renderContextData.currentOcclusionQueries = null;
  41113. const check = () => {
  41114. let completed = 0;
  41115. // check all queries and requeue as appropriate
  41116. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41117. const query = currentOcclusionQueries[ i ];
  41118. if ( query === null ) continue;
  41119. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41120. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41121. currentOcclusionQueries[ i ] = null;
  41122. gl.deleteQuery( query );
  41123. completed ++;
  41124. }
  41125. }
  41126. if ( completed < currentOcclusionQueries.length ) {
  41127. requestAnimationFrame( check );
  41128. } else {
  41129. renderContextData.occluded = occluded;
  41130. }
  41131. };
  41132. check();
  41133. }
  41134. }
  41135. /**
  41136. * Returns `true` if the given 3D object is fully occluded by other
  41137. * 3D objects in the scene.
  41138. *
  41139. * @param {RenderContext} renderContext - The render context.
  41140. * @param {Object3D} object - The 3D object to test.
  41141. * @return {Boolean} Whether the 3D object is fully occluded or not.
  41142. */
  41143. isOccluded( renderContext, object ) {
  41144. const renderContextData = this.get( renderContext );
  41145. return renderContextData.occluded && renderContextData.occluded.has( object );
  41146. }
  41147. /**
  41148. * Updates the viewport with the values from the given render context.
  41149. *
  41150. * @param {RenderContext} renderContext - The render context.
  41151. */
  41152. updateViewport( renderContext ) {
  41153. const { state } = this;
  41154. const { x, y, width, height } = renderContext.viewportValue;
  41155. state.viewport( x, renderContext.height - height - y, width, height );
  41156. }
  41157. /**
  41158. * Defines the scissor test.
  41159. *
  41160. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  41161. */
  41162. setScissorTest( boolean ) {
  41163. const state = this.state;
  41164. state.setScissorTest( boolean );
  41165. }
  41166. /**
  41167. * Performs a clear operation.
  41168. *
  41169. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  41170. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  41171. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  41172. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  41173. * @param {Boolean} [setFrameBuffer=true] - TODO.
  41174. */
  41175. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41176. const { gl } = this;
  41177. if ( descriptor === null ) {
  41178. const clearColor = this.getClearColor();
  41179. // premultiply alpha
  41180. clearColor.r *= clearColor.a;
  41181. clearColor.g *= clearColor.a;
  41182. clearColor.b *= clearColor.a;
  41183. descriptor = {
  41184. textures: null,
  41185. clearColorValue: clearColor
  41186. };
  41187. }
  41188. //
  41189. let clear = 0;
  41190. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41191. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41192. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41193. if ( clear !== 0 ) {
  41194. let clearColor;
  41195. if ( descriptor.clearColorValue ) {
  41196. clearColor = descriptor.clearColorValue;
  41197. } else {
  41198. clearColor = this.getClearColor();
  41199. // premultiply alpha
  41200. clearColor.r *= clearColor.a;
  41201. clearColor.g *= clearColor.a;
  41202. clearColor.b *= clearColor.a;
  41203. }
  41204. if ( depth ) this.state.setDepthMask( true );
  41205. if ( descriptor.textures === null ) {
  41206. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41207. gl.clear( clear );
  41208. } else {
  41209. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41210. if ( color ) {
  41211. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41212. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41213. }
  41214. }
  41215. if ( depth && stencil ) {
  41216. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41217. } else if ( depth ) {
  41218. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41219. } else if ( stencil ) {
  41220. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41221. }
  41222. }
  41223. }
  41224. }
  41225. /**
  41226. * This method is executed at the beginning of a compute call and
  41227. * prepares the state for upcoming compute tasks.
  41228. *
  41229. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41230. */
  41231. beginCompute( computeGroup ) {
  41232. const { state, gl } = this;
  41233. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41234. this.initTimestampQuery( computeGroup );
  41235. }
  41236. /**
  41237. * Executes a compute command for the given compute node.
  41238. *
  41239. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  41240. * @param {Node} computeNode - The compute node.
  41241. * @param {Array<BindGroup>} bindings - The bindings.
  41242. * @param {ComputePipeline} pipeline - The compute pipeline.
  41243. */
  41244. compute( computeGroup, computeNode, bindings, pipeline ) {
  41245. const { state, gl } = this;
  41246. if ( this.discard === false ) {
  41247. // required here to handle async behaviour of render.compute()
  41248. gl.enable( gl.RASTERIZER_DISCARD );
  41249. this.discard = true;
  41250. }
  41251. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41252. const vaoKey = this._getVaoKey( null, attributes );
  41253. const vaoGPU = this.vaoCache[ vaoKey ];
  41254. if ( vaoGPU === undefined ) {
  41255. this._createVao( null, attributes );
  41256. } else {
  41257. gl.bindVertexArray( vaoGPU );
  41258. }
  41259. state.useProgram( programGPU );
  41260. this._bindUniforms( bindings );
  41261. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41262. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41263. gl.beginTransformFeedback( gl.POINTS );
  41264. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41265. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41266. } else {
  41267. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41268. }
  41269. gl.endTransformFeedback();
  41270. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41271. // switch active buffers
  41272. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41273. const dualAttributeData = transformBuffers[ i ];
  41274. if ( dualAttributeData.pbo ) {
  41275. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41276. }
  41277. dualAttributeData.switchBuffers();
  41278. }
  41279. }
  41280. /**
  41281. * This method is executed at the end of a compute call and
  41282. * finalizes work after compute tasks.
  41283. *
  41284. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41285. */
  41286. finishCompute( computeGroup ) {
  41287. const gl = this.gl;
  41288. this.discard = false;
  41289. gl.disable( gl.RASTERIZER_DISCARD );
  41290. this.prepareTimestampBuffer( computeGroup );
  41291. if ( this._currentContext ) {
  41292. this._setFramebuffer( this._currentContext );
  41293. }
  41294. }
  41295. /**
  41296. * Executes a draw command for the given render object.
  41297. *
  41298. * @param {RenderObject} renderObject - The render object to draw.
  41299. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  41300. */
  41301. draw( renderObject/*, info*/ ) {
  41302. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  41303. const { programGPU } = this.get( pipeline );
  41304. const { gl, state } = this;
  41305. const contextData = this.get( context );
  41306. const drawParams = renderObject.getDrawParameters();
  41307. if ( drawParams === null ) return;
  41308. //
  41309. this._bindUniforms( renderObject.getBindings() );
  41310. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  41311. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  41312. state.useProgram( programGPU );
  41313. //
  41314. const renderObjectData = this.get( renderObject );
  41315. let vaoGPU = renderObjectData.staticVao;
  41316. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  41317. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  41318. vaoGPU = this.vaoCache[ vaoKey ];
  41319. if ( vaoGPU === undefined ) {
  41320. let staticVao;
  41321. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41322. if ( staticVao ) {
  41323. renderObjectData.staticVao = vaoGPU;
  41324. renderObjectData.geometryId = renderObject.geometry.id;
  41325. }
  41326. }
  41327. }
  41328. gl.bindVertexArray( vaoGPU );
  41329. //
  41330. const index = renderObject.getIndex();
  41331. //
  41332. const lastObject = contextData.lastOcclusionObject;
  41333. if ( lastObject !== object && lastObject !== undefined ) {
  41334. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41335. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41336. contextData.occlusionQueryIndex ++;
  41337. }
  41338. if ( object.occlusionTest === true ) {
  41339. const query = gl.createQuery();
  41340. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41341. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41342. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41343. }
  41344. contextData.lastOcclusionObject = object;
  41345. }
  41346. //
  41347. const renderer = this.bufferRenderer;
  41348. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41349. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41350. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41351. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41352. else {
  41353. if ( material.wireframe === true ) {
  41354. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41355. renderer.mode = gl.LINES;
  41356. } else {
  41357. renderer.mode = gl.TRIANGLES;
  41358. }
  41359. }
  41360. //
  41361. const { vertexCount, instanceCount } = drawParams;
  41362. let { firstVertex } = drawParams;
  41363. renderer.object = object;
  41364. if ( index !== null ) {
  41365. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41366. const indexData = this.get( index );
  41367. renderer.index = index.count;
  41368. renderer.type = indexData.type;
  41369. } else {
  41370. renderer.index = 0;
  41371. }
  41372. const draw = () => {
  41373. if ( object.isBatchedMesh ) {
  41374. if ( object._multiDrawInstances !== null ) {
  41375. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41376. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41377. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41378. } else {
  41379. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41380. }
  41381. } else if ( instanceCount > 1 ) {
  41382. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41383. } else {
  41384. renderer.render( firstVertex, vertexCount );
  41385. }
  41386. };
  41387. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  41388. const cameraData = this.get( renderObject.camera );
  41389. const cameras = renderObject.camera.cameras;
  41390. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  41391. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  41392. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  41393. const indexesGPU = [];
  41394. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  41395. const bufferGPU = gl.createBuffer();
  41396. data[ 0 ] = i;
  41397. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41398. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  41399. indexesGPU.push( bufferGPU );
  41400. }
  41401. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  41402. }
  41403. const cameraIndexData = this.get( cameraIndex );
  41404. const pixelRatio = this.renderer.getPixelRatio();
  41405. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  41406. const subCamera = cameras[ i ];
  41407. if ( object.layers.test( subCamera.layers ) ) {
  41408. const vp = subCamera.viewport;
  41409. const x = vp.x * pixelRatio;
  41410. const y = vp.y * pixelRatio;
  41411. const width = vp.width * pixelRatio;
  41412. const height = vp.height * pixelRatio;
  41413. state.viewport(
  41414. Math.floor( x ),
  41415. Math.floor( renderObject.context.height - height - y ),
  41416. Math.floor( width ),
  41417. Math.floor( height )
  41418. );
  41419. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  41420. draw();
  41421. }
  41422. }
  41423. } else {
  41424. draw();
  41425. }
  41426. //
  41427. gl.bindVertexArray( null );
  41428. }
  41429. /**
  41430. * Explain why always null is returned.
  41431. *
  41432. * @param {RenderObject} renderObject - The render object.
  41433. * @return {Boolean} Whether the render pipeline requires an update or not.
  41434. */
  41435. needsRenderUpdate( /*renderObject*/ ) {
  41436. return false;
  41437. }
  41438. /**
  41439. * Explain why no cache key is computed.
  41440. *
  41441. * @param {RenderObject} renderObject - The render object.
  41442. * @return {String} The cache key.
  41443. */
  41444. getRenderCacheKey( /*renderObject*/ ) {
  41445. return '';
  41446. }
  41447. // textures
  41448. /**
  41449. * Creates a default texture for the given texture that can be used
  41450. * as a placeholder until the actual texture is ready for usage.
  41451. *
  41452. * @param {Texture} texture - The texture to create a default texture for.
  41453. */
  41454. createDefaultTexture( texture ) {
  41455. this.textureUtils.createDefaultTexture( texture );
  41456. }
  41457. /**
  41458. * Defines a texture on the GPU for the given texture object.
  41459. *
  41460. * @param {Texture} texture - The texture.
  41461. * @param {Object} [options={}] - Optional configuration parameter.
  41462. */
  41463. createTexture( texture, options ) {
  41464. this.textureUtils.createTexture( texture, options );
  41465. }
  41466. /**
  41467. * Uploads the updated texture data to the GPU.
  41468. *
  41469. * @param {Texture} texture - The texture.
  41470. * @param {Object} [options={}] - Optional configuration parameter.
  41471. */
  41472. updateTexture( texture, options ) {
  41473. this.textureUtils.updateTexture( texture, options );
  41474. }
  41475. /**
  41476. * Generates mipmaps for the given texture.
  41477. *
  41478. * @param {Texture} texture - The texture.
  41479. */
  41480. generateMipmaps( texture ) {
  41481. this.textureUtils.generateMipmaps( texture );
  41482. }
  41483. /**
  41484. * Destroys the GPU data for the given texture object.
  41485. *
  41486. * @param {Texture} texture - The texture.
  41487. */
  41488. destroyTexture( texture ) {
  41489. this.textureUtils.destroyTexture( texture );
  41490. }
  41491. /**
  41492. * Returns texture data as a typed array.
  41493. *
  41494. * @async
  41495. * @param {Texture} texture - The texture to copy.
  41496. * @param {Number} x - The x coordinate of the copy origin.
  41497. * @param {Number} y - The y coordinate of the copy origin.
  41498. * @param {Number} width - The width of the copy.
  41499. * @param {Number} height - The height of the copy.
  41500. * @param {Number} faceIndex - The face index.
  41501. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41502. */
  41503. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41504. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41505. }
  41506. /**
  41507. * This method does nothing since WebGL 2 has no concept of samplers.
  41508. *
  41509. * @param {Texture} texture - The texture to create the sampler for.
  41510. */
  41511. createSampler( /*texture*/ ) {
  41512. //console.warn( 'Abstract class.' );
  41513. }
  41514. /**
  41515. * This method does nothing since WebGL 2 has no concept of samplers.
  41516. *
  41517. * @param {Texture} texture - The texture to destroy the sampler for.
  41518. */
  41519. destroySampler( /*texture*/ ) {}
  41520. // node builder
  41521. /**
  41522. * Returns a node builder for the given render object.
  41523. *
  41524. * @param {RenderObject} object - The render object.
  41525. * @param {Renderer} renderer - The renderer.
  41526. * @return {GLSLNodeBuilder} The node builder.
  41527. */
  41528. createNodeBuilder( object, renderer ) {
  41529. return new GLSLNodeBuilder( object, renderer );
  41530. }
  41531. // program
  41532. /**
  41533. * Creates a shader program from the given programmable stage.
  41534. *
  41535. * @param {ProgrammableStage} program - The programmable stage.
  41536. */
  41537. createProgram( program ) {
  41538. const gl = this.gl;
  41539. const { stage, code } = program;
  41540. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41541. gl.shaderSource( shader, code );
  41542. gl.compileShader( shader );
  41543. this.set( program, {
  41544. shaderGPU: shader
  41545. } );
  41546. }
  41547. /**
  41548. * Destroys the shader program of the given programmable stage.
  41549. *
  41550. * @param {ProgrammableStage} program - The programmable stage.
  41551. */
  41552. destroyProgram( program ) {
  41553. this.delete( program );
  41554. }
  41555. /**
  41556. * Creates a render pipeline for the given render object.
  41557. *
  41558. * @param {RenderObject} renderObject - The render object.
  41559. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  41560. */
  41561. createRenderPipeline( renderObject, promises ) {
  41562. const gl = this.gl;
  41563. const pipeline = renderObject.pipeline;
  41564. // Program
  41565. const { fragmentProgram, vertexProgram } = pipeline;
  41566. const programGPU = gl.createProgram();
  41567. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41568. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41569. gl.attachShader( programGPU, fragmentShader );
  41570. gl.attachShader( programGPU, vertexShader );
  41571. gl.linkProgram( programGPU );
  41572. this.set( pipeline, {
  41573. programGPU,
  41574. fragmentShader,
  41575. vertexShader
  41576. } );
  41577. if ( promises !== null && this.parallel ) {
  41578. const p = new Promise( ( resolve /*, reject*/ ) => {
  41579. const parallel = this.parallel;
  41580. const checkStatus = () => {
  41581. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41582. this._completeCompile( renderObject, pipeline );
  41583. resolve();
  41584. } else {
  41585. requestAnimationFrame( checkStatus );
  41586. }
  41587. };
  41588. checkStatus();
  41589. } );
  41590. promises.push( p );
  41591. return;
  41592. }
  41593. this._completeCompile( renderObject, pipeline );
  41594. }
  41595. /**
  41596. * Formats the source code of error messages.
  41597. *
  41598. * @private
  41599. * @param {String} string - The code.
  41600. * @param {Number} errorLine - The error line.
  41601. * @return {String} The formatted code.
  41602. */
  41603. _handleSource( string, errorLine ) {
  41604. const lines = string.split( '\n' );
  41605. const lines2 = [];
  41606. const from = Math.max( errorLine - 6, 0 );
  41607. const to = Math.min( errorLine + 6, lines.length );
  41608. for ( let i = from; i < to; i ++ ) {
  41609. const line = i + 1;
  41610. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41611. }
  41612. return lines2.join( '\n' );
  41613. }
  41614. /**
  41615. * Gets the shader compilation errors from the info log.
  41616. *
  41617. * @private
  41618. * @param {WebGL2RenderingContext} gl - The rendering context.
  41619. * @param {WebGLShader} shader - The WebGL shader object.
  41620. * @param {String} type - The shader type.
  41621. * @return {String} The shader errors.
  41622. */
  41623. _getShaderErrors( gl, shader, type ) {
  41624. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41625. const errors = gl.getShaderInfoLog( shader ).trim();
  41626. if ( status && errors === '' ) return '';
  41627. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41628. if ( errorMatches ) {
  41629. const errorLine = parseInt( errorMatches[ 1 ] );
  41630. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41631. } else {
  41632. return errors;
  41633. }
  41634. }
  41635. /**
  41636. * Logs shader compilation errors.
  41637. *
  41638. * @private
  41639. * @param {WebGLProgram} programGPU - The WebGL program.
  41640. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  41641. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  41642. */
  41643. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41644. if ( this.renderer.debug.checkShaderErrors ) {
  41645. const gl = this.gl;
  41646. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41647. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41648. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41649. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41650. } else {
  41651. // default error reporting
  41652. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41653. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41654. console.error(
  41655. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41656. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41657. 'Program Info Log: ' + programLog + '\n' +
  41658. vertexErrors + '\n' +
  41659. fragmentErrors
  41660. );
  41661. }
  41662. } else if ( programLog !== '' ) {
  41663. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41664. }
  41665. }
  41666. }
  41667. /**
  41668. * Completes the shader program setup for the given render object.
  41669. *
  41670. * @private
  41671. * @param {RenderObject} renderObject - The render object.
  41672. * @param {RenderPipeline} pipeline - The render pipeline.
  41673. */
  41674. _completeCompile( renderObject, pipeline ) {
  41675. const { state, gl } = this;
  41676. const pipelineData = this.get( pipeline );
  41677. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41678. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41679. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41680. }
  41681. state.useProgram( programGPU );
  41682. // Bindings
  41683. const bindings = renderObject.getBindings();
  41684. this._setupBindings( bindings, programGPU );
  41685. //
  41686. this.set( pipeline, {
  41687. programGPU
  41688. } );
  41689. }
  41690. /**
  41691. * Creates a compute pipeline for the given compute node.
  41692. *
  41693. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41694. * @param {Array<BindGroup>} bindings - The bindings.
  41695. */
  41696. createComputePipeline( computePipeline, bindings ) {
  41697. const { state, gl } = this;
  41698. // Program
  41699. const fragmentProgram = {
  41700. stage: 'fragment',
  41701. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41702. };
  41703. this.createProgram( fragmentProgram );
  41704. const { computeProgram } = computePipeline;
  41705. const programGPU = gl.createProgram();
  41706. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41707. const vertexShader = this.get( computeProgram ).shaderGPU;
  41708. const transforms = computeProgram.transforms;
  41709. const transformVaryingNames = [];
  41710. const transformAttributeNodes = [];
  41711. for ( let i = 0; i < transforms.length; i ++ ) {
  41712. const transform = transforms[ i ];
  41713. transformVaryingNames.push( transform.varyingName );
  41714. transformAttributeNodes.push( transform.attributeNode );
  41715. }
  41716. gl.attachShader( programGPU, fragmentShader );
  41717. gl.attachShader( programGPU, vertexShader );
  41718. gl.transformFeedbackVaryings(
  41719. programGPU,
  41720. transformVaryingNames,
  41721. gl.SEPARATE_ATTRIBS
  41722. );
  41723. gl.linkProgram( programGPU );
  41724. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41725. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41726. }
  41727. state.useProgram( programGPU );
  41728. // Bindings
  41729. this._setupBindings( bindings, programGPU );
  41730. const attributeNodes = computeProgram.attributes;
  41731. const attributes = [];
  41732. const transformBuffers = [];
  41733. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41734. const attribute = attributeNodes[ i ].node.attribute;
  41735. attributes.push( attribute );
  41736. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41737. }
  41738. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41739. const attribute = transformAttributeNodes[ i ].attribute;
  41740. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41741. const attributeData = this.get( attribute );
  41742. transformBuffers.push( attributeData );
  41743. }
  41744. //
  41745. this.set( computePipeline, {
  41746. programGPU,
  41747. transformBuffers,
  41748. attributes
  41749. } );
  41750. }
  41751. /**
  41752. * Creates bindings from the given bind group definition.
  41753. *
  41754. * @param {BindGroup} bindGroup - The bind group.
  41755. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41756. * @param {Number} cacheIndex - The cache index.
  41757. * @param {Number} version - The version.
  41758. */
  41759. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  41760. if ( this._knownBindings.has( bindings ) === false ) {
  41761. this._knownBindings.add( bindings );
  41762. let uniformBuffers = 0;
  41763. let textures = 0;
  41764. for ( const bindGroup of bindings ) {
  41765. this.set( bindGroup, {
  41766. textures: textures,
  41767. uniformBuffers: uniformBuffers
  41768. } );
  41769. for ( const binding of bindGroup.bindings ) {
  41770. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41771. if ( binding.isSampledTexture ) textures ++;
  41772. }
  41773. }
  41774. }
  41775. this.updateBindings( bindGroup, bindings );
  41776. }
  41777. /**
  41778. * Updates the given bind group definition.
  41779. *
  41780. * @param {BindGroup} bindGroup - The bind group.
  41781. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41782. * @param {Number} cacheIndex - The cache index.
  41783. * @param {Number} version - The version.
  41784. */
  41785. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  41786. const { gl } = this;
  41787. const bindGroupData = this.get( bindGroup );
  41788. let i = bindGroupData.uniformBuffers;
  41789. let t = bindGroupData.textures;
  41790. for ( const binding of bindGroup.bindings ) {
  41791. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41792. const data = binding.buffer;
  41793. const bufferGPU = gl.createBuffer();
  41794. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41795. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41796. this.set( binding, {
  41797. index: i ++,
  41798. bufferGPU
  41799. } );
  41800. } else if ( binding.isSampledTexture ) {
  41801. const { textureGPU, glTextureType } = this.get( binding.texture );
  41802. this.set( binding, {
  41803. index: t ++,
  41804. textureGPU,
  41805. glTextureType
  41806. } );
  41807. }
  41808. }
  41809. }
  41810. /**
  41811. * Updates a buffer binding.
  41812. *
  41813. * @param {Buffer} binding - The buffer binding to update.
  41814. */
  41815. updateBinding( binding ) {
  41816. const gl = this.gl;
  41817. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41818. const bindingData = this.get( binding );
  41819. const bufferGPU = bindingData.bufferGPU;
  41820. const data = binding.buffer;
  41821. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41822. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41823. }
  41824. }
  41825. // attributes
  41826. /**
  41827. * Creates the GPU buffer of an indexed shader attribute.
  41828. *
  41829. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41830. */
  41831. createIndexAttribute( attribute ) {
  41832. const gl = this.gl;
  41833. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41834. }
  41835. /**
  41836. * Creates the GPU buffer of a shader attribute.
  41837. *
  41838. * @param {BufferAttribute} attribute - The buffer attribute.
  41839. */
  41840. createAttribute( attribute ) {
  41841. if ( this.has( attribute ) ) return;
  41842. const gl = this.gl;
  41843. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41844. }
  41845. /**
  41846. * Creates the GPU buffer of a storage attribute.
  41847. *
  41848. * @param {BufferAttribute} attribute - The buffer attribute.
  41849. */
  41850. createStorageAttribute( attribute ) {
  41851. if ( this.has( attribute ) ) return;
  41852. const gl = this.gl;
  41853. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41854. }
  41855. /**
  41856. * Updates the GPU buffer of a shader attribute.
  41857. *
  41858. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41859. */
  41860. updateAttribute( attribute ) {
  41861. this.attributeUtils.updateAttribute( attribute );
  41862. }
  41863. /**
  41864. * Destroys the GPU buffer of a shader attribute.
  41865. *
  41866. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41867. */
  41868. destroyAttribute( attribute ) {
  41869. this.attributeUtils.destroyAttribute( attribute );
  41870. }
  41871. /**
  41872. * Checks if the given feature is supported by the backend.
  41873. *
  41874. * @param {String} name - The feature's name.
  41875. * @return {Boolean} Whether the feature is supported or not.
  41876. */
  41877. hasFeature( name ) {
  41878. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41879. const extensions = this.extensions;
  41880. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41881. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41882. }
  41883. return false;
  41884. }
  41885. /**
  41886. * Returns the maximum anisotropy texture filtering value.
  41887. *
  41888. * @return {Number} The maximum anisotropy texture filtering value.
  41889. */
  41890. getMaxAnisotropy() {
  41891. return this.capabilities.getMaxAnisotropy();
  41892. }
  41893. /**
  41894. * Copies data of the given source texture to the given destination texture.
  41895. *
  41896. * @param {Texture} srcTexture - The source texture.
  41897. * @param {Texture} dstTexture - The destination texture.
  41898. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  41899. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  41900. * @param {Number} [level=0] - The mip level to copy.
  41901. */
  41902. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  41903. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41904. }
  41905. /**
  41906. * Copies the current bound framebuffer to the given texture.
  41907. *
  41908. * @param {Texture} texture - The destination texture.
  41909. * @param {RenderContext} renderContext - The render context.
  41910. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41911. */
  41912. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41913. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41914. }
  41915. /**
  41916. * Configures the active framebuffer from the given render context.
  41917. *
  41918. * @private
  41919. * @param {RenderContext} descriptor - The render context.
  41920. */
  41921. _setFramebuffer( descriptor ) {
  41922. const { gl, state } = this;
  41923. let currentFrameBuffer = null;
  41924. if ( descriptor.textures !== null ) {
  41925. const renderTarget = descriptor.renderTarget;
  41926. const renderTargetContextData = this.get( renderTarget );
  41927. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41928. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41929. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  41930. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  41931. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  41932. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  41933. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41934. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41935. const cacheKey = getCacheKey( descriptor );
  41936. let fb;
  41937. if ( isCube ) {
  41938. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41939. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41940. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  41941. fb = this._xrFamebuffer;
  41942. } else {
  41943. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41944. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41945. }
  41946. if ( fb === undefined ) {
  41947. fb = gl.createFramebuffer();
  41948. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41949. const textures = descriptor.textures;
  41950. if ( isCube ) {
  41951. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41952. const { textureGPU } = this.get( textures[ 0 ] );
  41953. const cubeFace = this.renderer._activeCubeFace;
  41954. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41955. } else {
  41956. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41957. for ( let i = 0; i < textures.length; i ++ ) {
  41958. const texture = textures[ i ];
  41959. const textureData = this.get( texture );
  41960. textureData.renderTarget = descriptor.renderTarget;
  41961. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41962. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41963. if ( isRenderTarget3D || isRenderTargetArray ) {
  41964. const layer = this.renderer._activeCubeFace;
  41965. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  41966. } else {
  41967. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41968. }
  41969. }
  41970. state.drawBuffers( descriptor, fb );
  41971. }
  41972. if ( descriptor.depthTexture !== null ) {
  41973. const textureData = this.get( descriptor.depthTexture );
  41974. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41975. textureData.renderTarget = descriptor.renderTarget;
  41976. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41977. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41978. }
  41979. } else {
  41980. // rebind external XR textures
  41981. if ( isXRRenderTarget && hasExternalTextures ) {
  41982. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41983. // rebind color
  41984. const textureData = this.get( descriptor.textures[ 0 ] );
  41985. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41986. // rebind depth
  41987. if ( descriptor.depthTexture !== null ) {
  41988. const textureData = this.get( descriptor.depthTexture );
  41989. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41990. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41991. }
  41992. }
  41993. }
  41994. if ( samples > 0 ) {
  41995. if ( msaaFb === undefined ) {
  41996. const invalidationArray = [];
  41997. msaaFb = gl.createFramebuffer();
  41998. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41999. const msaaRenderbuffers = [];
  42000. const textures = descriptor.textures;
  42001. for ( let i = 0; i < textures.length; i ++ ) {
  42002. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  42003. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42004. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  42005. if ( depthBuffer ) {
  42006. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42007. invalidationArray.push( depthStyle );
  42008. }
  42009. const texture = descriptor.textures[ i ];
  42010. const textureData = this.get( texture );
  42011. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  42012. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42013. }
  42014. renderTargetContextData.msaaFrameBuffer = msaaFb;
  42015. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  42016. if ( depthRenderbuffer === undefined ) {
  42017. depthRenderbuffer = gl.createRenderbuffer();
  42018. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  42019. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  42020. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42021. invalidationArray.push( depthStyle );
  42022. }
  42023. renderTargetContextData.invalidationArray = invalidationArray;
  42024. }
  42025. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42026. } else {
  42027. currentFrameBuffer = fb;
  42028. }
  42029. }
  42030. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  42031. }
  42032. /**
  42033. * Computes the VAO key for the given index and attributes.
  42034. *
  42035. * @private
  42036. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  42037. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42038. * @return {String} The VAO key.
  42039. */
  42040. _getVaoKey( index, attributes ) {
  42041. let key = '';
  42042. if ( index !== null ) {
  42043. const indexData = this.get( index );
  42044. key += ':' + indexData.id;
  42045. }
  42046. for ( let i = 0; i < attributes.length; i ++ ) {
  42047. const attributeData = this.get( attributes[ i ] );
  42048. key += ':' + attributeData.id;
  42049. }
  42050. return key;
  42051. }
  42052. /**
  42053. * Creates a VAO from the index and attributes.
  42054. *
  42055. * @private
  42056. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  42057. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42058. * @return {Object} The VAO data.
  42059. */
  42060. _createVao( index, attributes ) {
  42061. const { gl } = this;
  42062. const vaoGPU = gl.createVertexArray();
  42063. let key = '';
  42064. let staticVao = true;
  42065. gl.bindVertexArray( vaoGPU );
  42066. if ( index !== null ) {
  42067. const indexData = this.get( index );
  42068. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  42069. key += ':' + indexData.id;
  42070. }
  42071. for ( let i = 0; i < attributes.length; i ++ ) {
  42072. const attribute = attributes[ i ];
  42073. const attributeData = this.get( attribute );
  42074. key += ':' + attributeData.id;
  42075. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  42076. gl.enableVertexAttribArray( i );
  42077. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  42078. let stride, offset;
  42079. if ( attribute.isInterleavedBufferAttribute === true ) {
  42080. stride = attribute.data.stride * attributeData.bytesPerElement;
  42081. offset = attribute.offset * attributeData.bytesPerElement;
  42082. } else {
  42083. stride = 0;
  42084. offset = 0;
  42085. }
  42086. if ( attributeData.isInteger ) {
  42087. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  42088. } else {
  42089. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  42090. }
  42091. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  42092. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  42093. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  42094. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  42095. }
  42096. }
  42097. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  42098. this.vaoCache[ key ] = vaoGPU;
  42099. return { vaoGPU, staticVao };
  42100. }
  42101. /**
  42102. * Creates a transform feedback from the given transform buffers.
  42103. *
  42104. * @private
  42105. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  42106. * @return {WebGLTransformFeedback} The transform feedback.
  42107. */
  42108. _getTransformFeedback( transformBuffers ) {
  42109. let key = '';
  42110. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42111. key += ':' + transformBuffers[ i ].id;
  42112. }
  42113. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  42114. if ( transformFeedbackGPU !== undefined ) {
  42115. return transformFeedbackGPU;
  42116. }
  42117. const { gl } = this;
  42118. transformFeedbackGPU = gl.createTransformFeedback();
  42119. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42120. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42121. const attributeData = transformBuffers[ i ];
  42122. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  42123. }
  42124. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42125. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  42126. return transformFeedbackGPU;
  42127. }
  42128. /**
  42129. * Setups the given bindings.
  42130. *
  42131. * @private
  42132. * @param {Array<BindGroup>} bindings - The bindings.
  42133. * @param {WebGLProgram} programGPU - The WebGL program.
  42134. */
  42135. _setupBindings( bindings, programGPU ) {
  42136. const gl = this.gl;
  42137. for ( const bindGroup of bindings ) {
  42138. for ( const binding of bindGroup.bindings ) {
  42139. const bindingData = this.get( binding );
  42140. const index = bindingData.index;
  42141. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42142. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  42143. gl.uniformBlockBinding( programGPU, location, index );
  42144. } else if ( binding.isSampledTexture ) {
  42145. const location = gl.getUniformLocation( programGPU, binding.name );
  42146. gl.uniform1i( location, index );
  42147. }
  42148. }
  42149. }
  42150. }
  42151. /**
  42152. * Binds the given uniforms.
  42153. *
  42154. * @private
  42155. * @param {Array<BindGroup>} bindings - The bindings.
  42156. */
  42157. _bindUniforms( bindings ) {
  42158. const { gl, state } = this;
  42159. for ( const bindGroup of bindings ) {
  42160. for ( const binding of bindGroup.bindings ) {
  42161. const bindingData = this.get( binding );
  42162. const index = bindingData.index;
  42163. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42164. // TODO USE bindBufferRange to group multiple uniform buffers
  42165. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  42166. } else if ( binding.isSampledTexture ) {
  42167. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  42168. }
  42169. }
  42170. }
  42171. }
  42172. /**
  42173. * Frees internal resources.
  42174. */
  42175. dispose() {
  42176. const extension = this.extensions.get( 'WEBGL_lose_context' );
  42177. if ( extension ) extension.loseContext();
  42178. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  42179. }
  42180. }
  42181. const GPUPrimitiveTopology = {
  42182. PointList: 'point-list',
  42183. LineList: 'line-list',
  42184. LineStrip: 'line-strip',
  42185. TriangleList: 'triangle-list',
  42186. TriangleStrip: 'triangle-strip',
  42187. };
  42188. const GPUCompareFunction = {
  42189. Never: 'never',
  42190. Less: 'less',
  42191. Equal: 'equal',
  42192. LessEqual: 'less-equal',
  42193. Greater: 'greater',
  42194. NotEqual: 'not-equal',
  42195. GreaterEqual: 'greater-equal',
  42196. Always: 'always'
  42197. };
  42198. const GPUStoreOp = {
  42199. Store: 'store',
  42200. Discard: 'discard'
  42201. };
  42202. const GPULoadOp = {
  42203. Load: 'load',
  42204. Clear: 'clear'
  42205. };
  42206. const GPUFrontFace = {
  42207. CCW: 'ccw',
  42208. CW: 'cw'
  42209. };
  42210. const GPUCullMode = {
  42211. None: 'none',
  42212. Front: 'front',
  42213. Back: 'back'
  42214. };
  42215. const GPUIndexFormat = {
  42216. Uint16: 'uint16',
  42217. Uint32: 'uint32'
  42218. };
  42219. const GPUTextureFormat = {
  42220. // 8-bit formats
  42221. R8Unorm: 'r8unorm',
  42222. R8Snorm: 'r8snorm',
  42223. R8Uint: 'r8uint',
  42224. R8Sint: 'r8sint',
  42225. // 16-bit formats
  42226. R16Uint: 'r16uint',
  42227. R16Sint: 'r16sint',
  42228. R16Float: 'r16float',
  42229. RG8Unorm: 'rg8unorm',
  42230. RG8Snorm: 'rg8snorm',
  42231. RG8Uint: 'rg8uint',
  42232. RG8Sint: 'rg8sint',
  42233. // 32-bit formats
  42234. R32Uint: 'r32uint',
  42235. R32Sint: 'r32sint',
  42236. R32Float: 'r32float',
  42237. RG16Uint: 'rg16uint',
  42238. RG16Sint: 'rg16sint',
  42239. RG16Float: 'rg16float',
  42240. RGBA8Unorm: 'rgba8unorm',
  42241. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  42242. RGBA8Snorm: 'rgba8snorm',
  42243. RGBA8Uint: 'rgba8uint',
  42244. RGBA8Sint: 'rgba8sint',
  42245. BGRA8Unorm: 'bgra8unorm',
  42246. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  42247. // Packed 32-bit formats
  42248. RGB9E5UFloat: 'rgb9e5ufloat',
  42249. RGB10A2Unorm: 'rgb10a2unorm',
  42250. RG11B10uFloat: 'rgb10a2unorm',
  42251. // 64-bit formats
  42252. RG32Uint: 'rg32uint',
  42253. RG32Sint: 'rg32sint',
  42254. RG32Float: 'rg32float',
  42255. RGBA16Uint: 'rgba16uint',
  42256. RGBA16Sint: 'rgba16sint',
  42257. RGBA16Float: 'rgba16float',
  42258. // 128-bit formats
  42259. RGBA32Uint: 'rgba32uint',
  42260. RGBA32Sint: 'rgba32sint',
  42261. RGBA32Float: 'rgba32float',
  42262. // Depth and stencil formats
  42263. Stencil8: 'stencil8',
  42264. Depth16Unorm: 'depth16unorm',
  42265. Depth24Plus: 'depth24plus',
  42266. Depth24PlusStencil8: 'depth24plus-stencil8',
  42267. Depth32Float: 'depth32float',
  42268. // 'depth32float-stencil8' extension
  42269. Depth32FloatStencil8: 'depth32float-stencil8',
  42270. // BC compressed formats usable if 'texture-compression-bc' is both
  42271. // supported by the device/user agent and enabled in requestDevice.
  42272. BC1RGBAUnorm: 'bc1-rgba-unorm',
  42273. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  42274. BC2RGBAUnorm: 'bc2-rgba-unorm',
  42275. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  42276. BC3RGBAUnorm: 'bc3-rgba-unorm',
  42277. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  42278. BC4RUnorm: 'bc4-r-unorm',
  42279. BC4RSnorm: 'bc4-r-snorm',
  42280. BC5RGUnorm: 'bc5-rg-unorm',
  42281. BC5RGSnorm: 'bc5-rg-snorm',
  42282. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  42283. BC6HRGBFloat: 'bc6h-rgb-float',
  42284. BC7RGBAUnorm: 'bc7-rgba-unorm',
  42285. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  42286. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  42287. // supported by the device/user agent and enabled in requestDevice.
  42288. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  42289. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  42290. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  42291. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  42292. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  42293. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  42294. EACR11Unorm: 'eac-r11unorm',
  42295. EACR11Snorm: 'eac-r11snorm',
  42296. EACRG11Unorm: 'eac-rg11unorm',
  42297. EACRG11Snorm: 'eac-rg11snorm',
  42298. // ASTC compressed formats usable if 'texture-compression-astc' is both
  42299. // supported by the device/user agent and enabled in requestDevice.
  42300. ASTC4x4Unorm: 'astc-4x4-unorm',
  42301. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  42302. ASTC5x4Unorm: 'astc-5x4-unorm',
  42303. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  42304. ASTC5x5Unorm: 'astc-5x5-unorm',
  42305. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  42306. ASTC6x5Unorm: 'astc-6x5-unorm',
  42307. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  42308. ASTC6x6Unorm: 'astc-6x6-unorm',
  42309. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  42310. ASTC8x5Unorm: 'astc-8x5-unorm',
  42311. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  42312. ASTC8x6Unorm: 'astc-8x6-unorm',
  42313. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  42314. ASTC8x8Unorm: 'astc-8x8-unorm',
  42315. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  42316. ASTC10x5Unorm: 'astc-10x5-unorm',
  42317. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  42318. ASTC10x6Unorm: 'astc-10x6-unorm',
  42319. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  42320. ASTC10x8Unorm: 'astc-10x8-unorm',
  42321. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  42322. ASTC10x10Unorm: 'astc-10x10-unorm',
  42323. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  42324. ASTC12x10Unorm: 'astc-12x10-unorm',
  42325. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  42326. ASTC12x12Unorm: 'astc-12x12-unorm',
  42327. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  42328. };
  42329. const GPUAddressMode = {
  42330. ClampToEdge: 'clamp-to-edge',
  42331. Repeat: 'repeat',
  42332. MirrorRepeat: 'mirror-repeat'
  42333. };
  42334. const GPUFilterMode = {
  42335. Linear: 'linear',
  42336. Nearest: 'nearest'
  42337. };
  42338. const GPUBlendFactor = {
  42339. Zero: 'zero',
  42340. One: 'one',
  42341. Src: 'src',
  42342. OneMinusSrc: 'one-minus-src',
  42343. SrcAlpha: 'src-alpha',
  42344. OneMinusSrcAlpha: 'one-minus-src-alpha',
  42345. Dst: 'dst',
  42346. OneMinusDstColor: 'one-minus-dst',
  42347. DstAlpha: 'dst-alpha',
  42348. OneMinusDstAlpha: 'one-minus-dst-alpha',
  42349. SrcAlphaSaturated: 'src-alpha-saturated',
  42350. Constant: 'constant',
  42351. OneMinusConstant: 'one-minus-constant'
  42352. };
  42353. const GPUBlendOperation = {
  42354. Add: 'add',
  42355. Subtract: 'subtract',
  42356. ReverseSubtract: 'reverse-subtract',
  42357. Min: 'min',
  42358. Max: 'max'
  42359. };
  42360. const GPUColorWriteFlags = {
  42361. None: 0,
  42362. Red: 0x1,
  42363. Green: 0x2,
  42364. Blue: 0x4,
  42365. Alpha: 0x8,
  42366. All: 0xF
  42367. };
  42368. const GPUStencilOperation = {
  42369. Keep: 'keep',
  42370. Zero: 'zero',
  42371. Replace: 'replace',
  42372. Invert: 'invert',
  42373. IncrementClamp: 'increment-clamp',
  42374. DecrementClamp: 'decrement-clamp',
  42375. IncrementWrap: 'increment-wrap',
  42376. DecrementWrap: 'decrement-wrap'
  42377. };
  42378. const GPUBufferBindingType = {
  42379. Uniform: 'uniform',
  42380. Storage: 'storage',
  42381. ReadOnlyStorage: 'read-only-storage'
  42382. };
  42383. const GPUStorageTextureAccess = {
  42384. WriteOnly: 'write-only',
  42385. ReadOnly: 'read-only',
  42386. ReadWrite: 'read-write',
  42387. };
  42388. const GPUTextureSampleType = {
  42389. Float: 'float',
  42390. UnfilterableFloat: 'unfilterable-float',
  42391. Depth: 'depth',
  42392. SInt: 'sint',
  42393. UInt: 'uint'
  42394. };
  42395. const GPUTextureDimension = {
  42396. OneD: '1d',
  42397. TwoD: '2d',
  42398. ThreeD: '3d'
  42399. };
  42400. const GPUTextureViewDimension = {
  42401. OneD: '1d',
  42402. TwoD: '2d',
  42403. TwoDArray: '2d-array',
  42404. Cube: 'cube',
  42405. CubeArray: 'cube-array',
  42406. ThreeD: '3d'
  42407. };
  42408. const GPUTextureAspect = {
  42409. All: 'all',
  42410. StencilOnly: 'stencil-only',
  42411. DepthOnly: 'depth-only'
  42412. };
  42413. const GPUInputStepMode = {
  42414. Vertex: 'vertex',
  42415. Instance: 'instance'
  42416. };
  42417. const GPUFeatureName = {
  42418. DepthClipControl: 'depth-clip-control',
  42419. Depth32FloatStencil8: 'depth32float-stencil8',
  42420. TextureCompressionBC: 'texture-compression-bc',
  42421. TextureCompressionETC2: 'texture-compression-etc2',
  42422. TextureCompressionASTC: 'texture-compression-astc',
  42423. TimestampQuery: 'timestamp-query',
  42424. IndirectFirstInstance: 'indirect-first-instance',
  42425. ShaderF16: 'shader-f16',
  42426. RG11B10UFloat: 'rg11b10ufloat-renderable',
  42427. BGRA8UNormStorage: 'bgra8unorm-storage',
  42428. Float32Filterable: 'float32-filterable',
  42429. ClipDistances: 'clip-distances',
  42430. DualSourceBlending: 'dual-source-blending',
  42431. Subgroups: 'subgroups'
  42432. };
  42433. /**
  42434. * Represents a sampler binding type.
  42435. *
  42436. * @private
  42437. * @augments Binding
  42438. */
  42439. class Sampler extends Binding {
  42440. /**
  42441. * Constructs a new sampler.
  42442. *
  42443. * @param {String} name - The samplers's name.
  42444. * @param {Texture?} texture - The texture this binding is referring to.
  42445. */
  42446. constructor( name, texture ) {
  42447. super( name );
  42448. /**
  42449. * The texture the sampler is referring to.
  42450. *
  42451. * @type {Texture?}
  42452. */
  42453. this.texture = texture;
  42454. /**
  42455. * The binding's version.
  42456. *
  42457. * @type {Number}
  42458. */
  42459. this.version = texture ? texture.version : 0;
  42460. /**
  42461. * This flag can be used for type testing.
  42462. *
  42463. * @type {Boolean}
  42464. * @readonly
  42465. * @default true
  42466. */
  42467. this.isSampler = true;
  42468. }
  42469. }
  42470. /**
  42471. * A special form of sampler binding type.
  42472. * It's texture value is managed by a node object.
  42473. *
  42474. * @private
  42475. * @augments Sampler
  42476. */
  42477. class NodeSampler extends Sampler {
  42478. /**
  42479. * Constructs a new node-based sampler.
  42480. *
  42481. * @param {String} name - The samplers's name.
  42482. * @param {TextureNode} textureNode - The texture node.
  42483. * @param {UniformGroupNode} groupNode - The uniform group node.
  42484. */
  42485. constructor( name, textureNode, groupNode ) {
  42486. super( name, textureNode ? textureNode.value : null );
  42487. /**
  42488. * The texture node.
  42489. *
  42490. * @type {TextureNode}
  42491. */
  42492. this.textureNode = textureNode;
  42493. /**
  42494. * The uniform group node.
  42495. *
  42496. * @type {UniformGroupNode}
  42497. */
  42498. this.groupNode = groupNode;
  42499. }
  42500. /**
  42501. * Updates the texture value of this sampler.
  42502. */
  42503. update() {
  42504. this.texture = this.textureNode.value;
  42505. }
  42506. }
  42507. /**
  42508. * Represents a storage buffer binding type.
  42509. *
  42510. * @private
  42511. * @augments Buffer
  42512. */
  42513. class StorageBuffer extends Buffer {
  42514. /**
  42515. * Constructs a new uniform buffer.
  42516. *
  42517. * @param {String} name - The buffer's name.
  42518. * @param {BufferAttribute} attribute - The buffer attribute.
  42519. */
  42520. constructor( name, attribute ) {
  42521. super( name, attribute ? attribute.array : null );
  42522. /**
  42523. * This flag can be used for type testing.
  42524. *
  42525. * @type {BufferAttribute}
  42526. */
  42527. this.attribute = attribute;
  42528. /**
  42529. * This flag can be used for type testing.
  42530. *
  42531. * @type {Boolean}
  42532. * @readonly
  42533. * @default true
  42534. */
  42535. this.isStorageBuffer = true;
  42536. }
  42537. }
  42538. let _id = 0;
  42539. /**
  42540. * A special form of storage buffer binding type.
  42541. * It's buffer value is managed by a node object.
  42542. *
  42543. * @private
  42544. * @augments StorageBuffer
  42545. */
  42546. class NodeStorageBuffer extends StorageBuffer {
  42547. /**
  42548. * Constructs a new node-based storage buffer.
  42549. *
  42550. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  42551. * @param {UniformGroupNode} groupNode - The uniform group node.
  42552. */
  42553. constructor( nodeUniform, groupNode ) {
  42554. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  42555. /**
  42556. * The node uniform.
  42557. *
  42558. * @type {StorageBufferNode}
  42559. */
  42560. this.nodeUniform = nodeUniform;
  42561. /**
  42562. * The access type.
  42563. *
  42564. * @type {String}
  42565. */
  42566. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  42567. /**
  42568. * The uniform group node.
  42569. *
  42570. * @type {UniformGroupNode}
  42571. */
  42572. this.groupNode = groupNode;
  42573. }
  42574. /**
  42575. * The storage buffer.
  42576. *
  42577. * @type {BufferAttribute}
  42578. */
  42579. get buffer() {
  42580. return this.nodeUniform.value;
  42581. }
  42582. }
  42583. /**
  42584. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  42585. *
  42586. * @private
  42587. */
  42588. class WebGPUTexturePassUtils extends DataMap {
  42589. /**
  42590. * Constructs a new utility object.
  42591. *
  42592. * @param {GPUDevice} device - The WebGPU device.
  42593. */
  42594. constructor( device ) {
  42595. super();
  42596. /**
  42597. * The WebGPU device.
  42598. *
  42599. * @type {GPUDevice}
  42600. */
  42601. this.device = device;
  42602. const mipmapVertexSource = `
  42603. struct VarysStruct {
  42604. @builtin( position ) Position: vec4<f32>,
  42605. @location( 0 ) vTex : vec2<f32>
  42606. };
  42607. @vertex
  42608. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  42609. var Varys : VarysStruct;
  42610. var pos = array< vec2<f32>, 4 >(
  42611. vec2<f32>( -1.0, 1.0 ),
  42612. vec2<f32>( 1.0, 1.0 ),
  42613. vec2<f32>( -1.0, -1.0 ),
  42614. vec2<f32>( 1.0, -1.0 )
  42615. );
  42616. var tex = array< vec2<f32>, 4 >(
  42617. vec2<f32>( 0.0, 0.0 ),
  42618. vec2<f32>( 1.0, 0.0 ),
  42619. vec2<f32>( 0.0, 1.0 ),
  42620. vec2<f32>( 1.0, 1.0 )
  42621. );
  42622. Varys.vTex = tex[ vertexIndex ];
  42623. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  42624. return Varys;
  42625. }
  42626. `;
  42627. const mipmapFragmentSource = `
  42628. @group( 0 ) @binding( 0 )
  42629. var imgSampler : sampler;
  42630. @group( 0 ) @binding( 1 )
  42631. var img : texture_2d<f32>;
  42632. @fragment
  42633. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42634. return textureSample( img, imgSampler, vTex );
  42635. }
  42636. `;
  42637. const flipYFragmentSource = `
  42638. @group( 0 ) @binding( 0 )
  42639. var imgSampler : sampler;
  42640. @group( 0 ) @binding( 1 )
  42641. var img : texture_2d<f32>;
  42642. @fragment
  42643. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42644. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  42645. }
  42646. `;
  42647. /**
  42648. * The mipmap GPU sampler.
  42649. *
  42650. * @type {GPUSampler}
  42651. */
  42652. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  42653. /**
  42654. * The flipY GPU sampler.
  42655. *
  42656. * @type {GPUSampler}
  42657. */
  42658. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42659. /**
  42660. * A cache for GPU render pipelines used for copy/transfer passes.
  42661. * Every texture format requires a unique pipeline.
  42662. *
  42663. * @type {Object<String,GPURenderPipeline>}
  42664. */
  42665. this.transferPipelines = {};
  42666. /**
  42667. * A cache for GPU render pipelines used for flipY passes.
  42668. * Every texture format requires a unique pipeline.
  42669. *
  42670. * @type {Object<String,GPURenderPipeline>}
  42671. */
  42672. this.flipYPipelines = {};
  42673. /**
  42674. * The mipmap vertex shader module.
  42675. *
  42676. * @type {GPUShaderModule}
  42677. */
  42678. this.mipmapVertexShaderModule = device.createShaderModule( {
  42679. label: 'mipmapVertex',
  42680. code: mipmapVertexSource
  42681. } );
  42682. /**
  42683. * The mipmap fragment shader module.
  42684. *
  42685. * @type {GPUShaderModule}
  42686. */
  42687. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42688. label: 'mipmapFragment',
  42689. code: mipmapFragmentSource
  42690. } );
  42691. /**
  42692. * The flipY fragment shader module.
  42693. *
  42694. * @type {GPUShaderModule}
  42695. */
  42696. this.flipYFragmentShaderModule = device.createShaderModule( {
  42697. label: 'flipYFragment',
  42698. code: flipYFragmentSource
  42699. } );
  42700. }
  42701. /**
  42702. * Returns a render pipeline for the internal copy render pass. The pass
  42703. * requires a unique render pipeline for each texture format.
  42704. *
  42705. * @param {String} format - The GPU texture format
  42706. * @return {GPURenderPipeline} The GPU render pipeline.
  42707. */
  42708. getTransferPipeline( format ) {
  42709. let pipeline = this.transferPipelines[ format ];
  42710. if ( pipeline === undefined ) {
  42711. pipeline = this.device.createRenderPipeline( {
  42712. label: `mipmap-${ format }`,
  42713. vertex: {
  42714. module: this.mipmapVertexShaderModule,
  42715. entryPoint: 'main'
  42716. },
  42717. fragment: {
  42718. module: this.mipmapFragmentShaderModule,
  42719. entryPoint: 'main',
  42720. targets: [ { format } ]
  42721. },
  42722. primitive: {
  42723. topology: GPUPrimitiveTopology.TriangleStrip,
  42724. stripIndexFormat: GPUIndexFormat.Uint32
  42725. },
  42726. layout: 'auto'
  42727. } );
  42728. this.transferPipelines[ format ] = pipeline;
  42729. }
  42730. return pipeline;
  42731. }
  42732. /**
  42733. * Returns a render pipeline for the flipY render pass. The pass
  42734. * requires a unique render pipeline for each texture format.
  42735. *
  42736. * @param {String} format - The GPU texture format
  42737. * @return {GPURenderPipeline} The GPU render pipeline.
  42738. */
  42739. getFlipYPipeline( format ) {
  42740. let pipeline = this.flipYPipelines[ format ];
  42741. if ( pipeline === undefined ) {
  42742. pipeline = this.device.createRenderPipeline( {
  42743. label: `flipY-${ format }`,
  42744. vertex: {
  42745. module: this.mipmapVertexShaderModule,
  42746. entryPoint: 'main'
  42747. },
  42748. fragment: {
  42749. module: this.flipYFragmentShaderModule,
  42750. entryPoint: 'main',
  42751. targets: [ { format } ]
  42752. },
  42753. primitive: {
  42754. topology: GPUPrimitiveTopology.TriangleStrip,
  42755. stripIndexFormat: GPUIndexFormat.Uint32
  42756. },
  42757. layout: 'auto'
  42758. } );
  42759. this.flipYPipelines[ format ] = pipeline;
  42760. }
  42761. return pipeline;
  42762. }
  42763. /**
  42764. * Flip the contents of the given GPU texture along its vertical axis.
  42765. *
  42766. * @param {GPUTexture} textureGPU - The GPU texture object.
  42767. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42768. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42769. */
  42770. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42771. const format = textureGPUDescriptor.format;
  42772. const { width, height } = textureGPUDescriptor.size;
  42773. const transferPipeline = this.getTransferPipeline( format );
  42774. const flipYPipeline = this.getFlipYPipeline( format );
  42775. const tempTexture = this.device.createTexture( {
  42776. size: { width, height, depthOrArrayLayers: 1 },
  42777. format,
  42778. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42779. } );
  42780. const srcView = textureGPU.createView( {
  42781. baseMipLevel: 0,
  42782. mipLevelCount: 1,
  42783. dimension: GPUTextureViewDimension.TwoD,
  42784. baseArrayLayer
  42785. } );
  42786. const dstView = tempTexture.createView( {
  42787. baseMipLevel: 0,
  42788. mipLevelCount: 1,
  42789. dimension: GPUTextureViewDimension.TwoD,
  42790. baseArrayLayer: 0
  42791. } );
  42792. const commandEncoder = this.device.createCommandEncoder( {} );
  42793. const pass = ( pipeline, sourceView, destinationView ) => {
  42794. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42795. const bindGroup = this.device.createBindGroup( {
  42796. layout: bindGroupLayout,
  42797. entries: [ {
  42798. binding: 0,
  42799. resource: this.flipYSampler
  42800. }, {
  42801. binding: 1,
  42802. resource: sourceView
  42803. } ]
  42804. } );
  42805. const passEncoder = commandEncoder.beginRenderPass( {
  42806. colorAttachments: [ {
  42807. view: destinationView,
  42808. loadOp: GPULoadOp.Clear,
  42809. storeOp: GPUStoreOp.Store,
  42810. clearValue: [ 0, 0, 0, 0 ]
  42811. } ]
  42812. } );
  42813. passEncoder.setPipeline( pipeline );
  42814. passEncoder.setBindGroup( 0, bindGroup );
  42815. passEncoder.draw( 4, 1, 0, 0 );
  42816. passEncoder.end();
  42817. };
  42818. pass( transferPipeline, srcView, dstView );
  42819. pass( flipYPipeline, dstView, srcView );
  42820. this.device.queue.submit( [ commandEncoder.finish() ] );
  42821. tempTexture.destroy();
  42822. }
  42823. /**
  42824. * Generates mipmaps for the given GPU texture.
  42825. *
  42826. * @param {GPUTexture} textureGPU - The GPU texture object.
  42827. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42828. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42829. */
  42830. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42831. const textureData = this.get( textureGPU );
  42832. if ( textureData.useCount === undefined ) {
  42833. textureData.useCount = 0;
  42834. textureData.layers = [];
  42835. }
  42836. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42837. const commandEncoder = this.device.createCommandEncoder( {} );
  42838. this._mipmapRunBundles( commandEncoder, passes );
  42839. this.device.queue.submit( [ commandEncoder.finish() ] );
  42840. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42841. textureData.useCount ++;
  42842. }
  42843. /**
  42844. * Since multiple copy render passes are required to generate mipmaps, the passes
  42845. * are managed as render bundles to improve performance.
  42846. *
  42847. * @param {GPUTexture} textureGPU - The GPU texture object.
  42848. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42849. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  42850. * @return {Array} An array of render bundles.
  42851. */
  42852. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42853. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42854. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42855. let srcView = textureGPU.createView( {
  42856. baseMipLevel: 0,
  42857. mipLevelCount: 1,
  42858. dimension: GPUTextureViewDimension.TwoD,
  42859. baseArrayLayer
  42860. } );
  42861. const passes = [];
  42862. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42863. const bindGroup = this.device.createBindGroup( {
  42864. layout: bindGroupLayout,
  42865. entries: [ {
  42866. binding: 0,
  42867. resource: this.mipmapSampler
  42868. }, {
  42869. binding: 1,
  42870. resource: srcView
  42871. } ]
  42872. } );
  42873. const dstView = textureGPU.createView( {
  42874. baseMipLevel: i,
  42875. mipLevelCount: 1,
  42876. dimension: GPUTextureViewDimension.TwoD,
  42877. baseArrayLayer
  42878. } );
  42879. const passDescriptor = {
  42880. colorAttachments: [ {
  42881. view: dstView,
  42882. loadOp: GPULoadOp.Clear,
  42883. storeOp: GPUStoreOp.Store,
  42884. clearValue: [ 0, 0, 0, 0 ]
  42885. } ]
  42886. };
  42887. const passEncoder = this.device.createRenderBundleEncoder( {
  42888. colorFormats: [ textureGPUDescriptor.format ]
  42889. } );
  42890. passEncoder.setPipeline( pipeline );
  42891. passEncoder.setBindGroup( 0, bindGroup );
  42892. passEncoder.draw( 4, 1, 0, 0 );
  42893. passes.push( {
  42894. renderBundles: [ passEncoder.finish() ],
  42895. passDescriptor
  42896. } );
  42897. srcView = dstView;
  42898. }
  42899. return passes;
  42900. }
  42901. /**
  42902. * Executes the render bundles.
  42903. *
  42904. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  42905. * @param {Array} passes - An array of render bundles.
  42906. */
  42907. _mipmapRunBundles( commandEncoder, passes ) {
  42908. const levels = passes.length;
  42909. for ( let i = 0; i < levels; i ++ ) {
  42910. const pass = passes[ i ];
  42911. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42912. passEncoder.executeBundles( pass.renderBundles );
  42913. passEncoder.end();
  42914. }
  42915. }
  42916. }
  42917. const _compareToWebGPU = {
  42918. [ NeverCompare ]: 'never',
  42919. [ LessCompare ]: 'less',
  42920. [ EqualCompare ]: 'equal',
  42921. [ LessEqualCompare ]: 'less-equal',
  42922. [ GreaterCompare ]: 'greater',
  42923. [ GreaterEqualCompare ]: 'greater-equal',
  42924. [ AlwaysCompare ]: 'always',
  42925. [ NotEqualCompare ]: 'not-equal'
  42926. };
  42927. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42928. /**
  42929. * A WebGPU backend utility module for managing textures.
  42930. *
  42931. * @private
  42932. */
  42933. class WebGPUTextureUtils {
  42934. /**
  42935. * Constructs a new utility object.
  42936. *
  42937. * @param {WebGPUBackend} backend - The WebGPU backend.
  42938. */
  42939. constructor( backend ) {
  42940. /**
  42941. * A reference to the WebGPU backend.
  42942. *
  42943. * @type {WebGPUBackend}
  42944. */
  42945. this.backend = backend;
  42946. /**
  42947. * A reference to the pass utils.
  42948. *
  42949. * @type {WebGPUTexturePassUtils?}
  42950. * @default null
  42951. */
  42952. this._passUtils = null;
  42953. /**
  42954. * A dictionary for managing default textures. The key
  42955. * is the texture format, the value the texture object.
  42956. *
  42957. * @type {Object<String,Texture>}
  42958. */
  42959. this.defaultTexture = {};
  42960. /**
  42961. * A dictionary for managing default cube textures. The key
  42962. * is the texture format, the value the texture object.
  42963. *
  42964. * @type {Object<String,CubeTexture>}
  42965. */
  42966. this.defaultCubeTexture = {};
  42967. /**
  42968. * A default video frame.
  42969. *
  42970. * @type {VideoFrame?}
  42971. * @default null
  42972. */
  42973. this.defaultVideoFrame = null;
  42974. /**
  42975. * Represents the color attachment of the default framebuffer.
  42976. *
  42977. * @type {GPUTexture?}
  42978. * @default null
  42979. */
  42980. this.colorBuffer = null;
  42981. /**
  42982. * Represents the depth attachment of the default framebuffer.
  42983. *
  42984. * @type {DepthTexture}
  42985. */
  42986. this.depthTexture = new DepthTexture();
  42987. this.depthTexture.name = 'depthBuffer';
  42988. }
  42989. /**
  42990. * Creates a GPU sampler for the given texture.
  42991. *
  42992. * @param {Texture} texture - The texture to create the sampler for.
  42993. */
  42994. createSampler( texture ) {
  42995. const backend = this.backend;
  42996. const device = backend.device;
  42997. const textureGPU = backend.get( texture );
  42998. const samplerDescriptorGPU = {
  42999. addressModeU: this._convertAddressMode( texture.wrapS ),
  43000. addressModeV: this._convertAddressMode( texture.wrapT ),
  43001. addressModeW: this._convertAddressMode( texture.wrapR ),
  43002. magFilter: this._convertFilterMode( texture.magFilter ),
  43003. minFilter: this._convertFilterMode( texture.minFilter ),
  43004. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  43005. maxAnisotropy: 1
  43006. };
  43007. // anisotropy can only be used when all filter modes are set to linear.
  43008. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  43009. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  43010. }
  43011. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  43012. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  43013. }
  43014. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  43015. }
  43016. /**
  43017. * Creates a default texture for the given texture that can be used
  43018. * as a placeholder until the actual texture is ready for usage.
  43019. *
  43020. * @param {Texture} texture - The texture to create a default texture for.
  43021. */
  43022. createDefaultTexture( texture ) {
  43023. let textureGPU;
  43024. const format = getFormat( texture );
  43025. if ( texture.isCubeTexture ) {
  43026. textureGPU = this._getDefaultCubeTextureGPU( format );
  43027. } else if ( texture.isVideoTexture ) {
  43028. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  43029. } else {
  43030. textureGPU = this._getDefaultTextureGPU( format );
  43031. }
  43032. this.backend.get( texture ).texture = textureGPU;
  43033. }
  43034. /**
  43035. * Defines a texture on the GPU for the given texture object.
  43036. *
  43037. * @param {Texture} texture - The texture.
  43038. * @param {Object} [options={}] - Optional configuration parameter.
  43039. * @return {undefined}
  43040. */
  43041. createTexture( texture, options = {} ) {
  43042. const backend = this.backend;
  43043. const textureData = backend.get( texture );
  43044. if ( textureData.initialized ) {
  43045. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  43046. }
  43047. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  43048. if ( options.levels === undefined ) options.levels = 1;
  43049. if ( options.depth === undefined ) options.depth = 1;
  43050. const { width, height, depth, levels } = options;
  43051. if ( texture.isFramebufferTexture ) {
  43052. if ( options.renderTarget ) {
  43053. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  43054. } else {
  43055. options.format = this.backend.utils.getPreferredCanvasFormat();
  43056. }
  43057. }
  43058. const dimension = this._getDimension( texture );
  43059. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  43060. textureData.format = format;
  43061. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  43062. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  43063. if ( texture.isStorageTexture === true ) {
  43064. usage |= GPUTextureUsage.STORAGE_BINDING;
  43065. }
  43066. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  43067. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  43068. }
  43069. const textureDescriptorGPU = {
  43070. label: texture.name,
  43071. size: {
  43072. width: width,
  43073. height: height,
  43074. depthOrArrayLayers: depth,
  43075. },
  43076. mipLevelCount: levels,
  43077. sampleCount: primarySamples,
  43078. dimension: dimension,
  43079. format: format,
  43080. usage: usage
  43081. };
  43082. // texture creation
  43083. if ( texture.isVideoTexture ) {
  43084. const video = texture.source.data;
  43085. const videoFrame = new VideoFrame( video );
  43086. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  43087. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  43088. videoFrame.close();
  43089. textureData.externalTexture = video;
  43090. } else {
  43091. if ( format === undefined ) {
  43092. console.warn( 'WebGPURenderer: Texture format not supported.' );
  43093. return this.createDefaultTexture( texture );
  43094. }
  43095. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  43096. }
  43097. if ( isMSAA ) {
  43098. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  43099. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  43100. msaaTextureDescriptorGPU.sampleCount = samples;
  43101. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  43102. }
  43103. textureData.initialized = true;
  43104. textureData.textureDescriptorGPU = textureDescriptorGPU;
  43105. }
  43106. /**
  43107. * Destroys the GPU data for the given texture object.
  43108. *
  43109. * @param {Texture} texture - The texture.
  43110. */
  43111. destroyTexture( texture ) {
  43112. const backend = this.backend;
  43113. const textureData = backend.get( texture );
  43114. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  43115. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  43116. backend.delete( texture );
  43117. }
  43118. /**
  43119. * Destroys the GPU sampler for the given texture.
  43120. *
  43121. * @param {Texture} texture - The texture to destroy the sampler for.
  43122. */
  43123. destroySampler( texture ) {
  43124. const backend = this.backend;
  43125. const textureData = backend.get( texture );
  43126. delete textureData.sampler;
  43127. }
  43128. /**
  43129. * Generates mipmaps for the given texture.
  43130. *
  43131. * @param {Texture} texture - The texture.
  43132. */
  43133. generateMipmaps( texture ) {
  43134. const textureData = this.backend.get( texture );
  43135. if ( texture.isCubeTexture ) {
  43136. for ( let i = 0; i < 6; i ++ ) {
  43137. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43138. }
  43139. } else {
  43140. const depth = texture.image.depth || 1;
  43141. for ( let i = 0; i < depth; i ++ ) {
  43142. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43143. }
  43144. }
  43145. }
  43146. /**
  43147. * Returns the color buffer representing the color
  43148. * attachment of the default framebuffer.
  43149. *
  43150. * @return {GPUTexture} The color buffer.
  43151. */
  43152. getColorBuffer() {
  43153. if ( this.colorBuffer ) this.colorBuffer.destroy();
  43154. const backend = this.backend;
  43155. const { width, height } = backend.getDrawingBufferSize();
  43156. this.colorBuffer = backend.device.createTexture( {
  43157. label: 'colorBuffer',
  43158. size: {
  43159. width: width,
  43160. height: height,
  43161. depthOrArrayLayers: 1
  43162. },
  43163. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  43164. format: backend.utils.getPreferredCanvasFormat(),
  43165. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  43166. } );
  43167. return this.colorBuffer;
  43168. }
  43169. /**
  43170. * Returns the depth buffer representing the depth
  43171. * attachment of the default framebuffer.
  43172. *
  43173. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  43174. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  43175. * @return {GPUTexture} The depth buffer.
  43176. */
  43177. getDepthBuffer( depth = true, stencil = false ) {
  43178. const backend = this.backend;
  43179. const { width, height } = backend.getDrawingBufferSize();
  43180. const depthTexture = this.depthTexture;
  43181. const depthTextureGPU = backend.get( depthTexture ).texture;
  43182. let format, type;
  43183. if ( stencil ) {
  43184. format = DepthStencilFormat;
  43185. type = UnsignedInt248Type;
  43186. } else if ( depth ) {
  43187. format = DepthFormat;
  43188. type = UnsignedIntType;
  43189. }
  43190. if ( depthTextureGPU !== undefined ) {
  43191. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  43192. return depthTextureGPU;
  43193. }
  43194. this.destroyTexture( depthTexture );
  43195. }
  43196. depthTexture.name = 'depthBuffer';
  43197. depthTexture.format = format;
  43198. depthTexture.type = type;
  43199. depthTexture.image.width = width;
  43200. depthTexture.image.height = height;
  43201. this.createTexture( depthTexture, { width, height } );
  43202. return backend.get( depthTexture ).texture;
  43203. }
  43204. /**
  43205. * Uploads the updated texture data to the GPU.
  43206. *
  43207. * @param {Texture} texture - The texture.
  43208. * @param {Object} [options={}] - Optional configuration parameter.
  43209. */
  43210. updateTexture( texture, options ) {
  43211. const textureData = this.backend.get( texture );
  43212. const { textureDescriptorGPU } = textureData;
  43213. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  43214. return;
  43215. // transfer texture data
  43216. if ( texture.isDataTexture ) {
  43217. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43218. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43219. for ( let i = 0; i < options.image.depth; i ++ ) {
  43220. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  43221. }
  43222. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  43223. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  43224. } else if ( texture.isCubeTexture ) {
  43225. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  43226. } else if ( texture.isVideoTexture ) {
  43227. const video = texture.source.data;
  43228. textureData.externalTexture = video;
  43229. } else {
  43230. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43231. }
  43232. //
  43233. textureData.version = texture.version;
  43234. if ( texture.onUpdate ) texture.onUpdate( texture );
  43235. }
  43236. /**
  43237. * Returns texture data as a typed array.
  43238. *
  43239. * @async
  43240. * @param {Texture} texture - The texture to copy.
  43241. * @param {Number} x - The x coordinate of the copy origin.
  43242. * @param {Number} y - The y coordinate of the copy origin.
  43243. * @param {Number} width - The width of the copy.
  43244. * @param {Number} height - The height of the copy.
  43245. * @param {Number} faceIndex - The face index.
  43246. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43247. */
  43248. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43249. const device = this.backend.device;
  43250. const textureData = this.backend.get( texture );
  43251. const textureGPU = textureData.texture;
  43252. const format = textureData.textureDescriptorGPU.format;
  43253. const bytesPerTexel = this._getBytesPerTexel( format );
  43254. let bytesPerRow = width * bytesPerTexel;
  43255. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  43256. const readBuffer = device.createBuffer(
  43257. {
  43258. size: width * height * bytesPerTexel,
  43259. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43260. }
  43261. );
  43262. const encoder = device.createCommandEncoder();
  43263. encoder.copyTextureToBuffer(
  43264. {
  43265. texture: textureGPU,
  43266. origin: { x, y, z: faceIndex },
  43267. },
  43268. {
  43269. buffer: readBuffer,
  43270. bytesPerRow: bytesPerRow
  43271. },
  43272. {
  43273. width: width,
  43274. height: height
  43275. }
  43276. );
  43277. const typedArrayType = this._getTypedArrayType( format );
  43278. device.queue.submit( [ encoder.finish() ] );
  43279. await readBuffer.mapAsync( GPUMapMode.READ );
  43280. const buffer = readBuffer.getMappedRange();
  43281. return new typedArrayType( buffer );
  43282. }
  43283. /**
  43284. * Returns `true` if the given texture is an environment map.
  43285. *
  43286. * @private
  43287. * @param {Texture} texture - The texture.
  43288. * @return {Boolean} Whether the given texture is an environment map or not.
  43289. */
  43290. _isEnvironmentTexture( texture ) {
  43291. const mapping = texture.mapping;
  43292. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  43293. }
  43294. /**
  43295. * Returns the default GPU texture for the given format.
  43296. *
  43297. * @private
  43298. * @param {String} format - The GPU format.
  43299. * @return {GPUTexture} The GPU texture.
  43300. */
  43301. _getDefaultTextureGPU( format ) {
  43302. let defaultTexture = this.defaultTexture[ format ];
  43303. if ( defaultTexture === undefined ) {
  43304. const texture = new Texture();
  43305. texture.minFilter = NearestFilter;
  43306. texture.magFilter = NearestFilter;
  43307. this.createTexture( texture, { width: 1, height: 1, format } );
  43308. this.defaultTexture[ format ] = defaultTexture = texture;
  43309. }
  43310. return this.backend.get( defaultTexture ).texture;
  43311. }
  43312. /**
  43313. * Returns the default GPU cube texture for the given format.
  43314. *
  43315. * @private
  43316. * @param {String} format - The GPU format.
  43317. * @return {GPUTexture} The GPU texture.
  43318. */
  43319. _getDefaultCubeTextureGPU( format ) {
  43320. let defaultCubeTexture = this.defaultTexture[ format ];
  43321. if ( defaultCubeTexture === undefined ) {
  43322. const texture = new CubeTexture();
  43323. texture.minFilter = NearestFilter;
  43324. texture.magFilter = NearestFilter;
  43325. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  43326. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  43327. }
  43328. return this.backend.get( defaultCubeTexture ).texture;
  43329. }
  43330. /**
  43331. * Returns the default video frame used as default data in context of video textures.
  43332. *
  43333. * @private
  43334. * @return {VideoFrame} The video frame.
  43335. */
  43336. _getDefaultVideoFrame() {
  43337. let defaultVideoFrame = this.defaultVideoFrame;
  43338. if ( defaultVideoFrame === null ) {
  43339. const init = {
  43340. timestamp: 0,
  43341. codedWidth: 1,
  43342. codedHeight: 1,
  43343. format: 'RGBA',
  43344. };
  43345. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  43346. }
  43347. return defaultVideoFrame;
  43348. }
  43349. /**
  43350. * Uploads cube texture image data to the GPU memory.
  43351. *
  43352. * @private
  43353. * @param {Array} images - The cube image data.
  43354. * @param {GPUTexture} textureGPU - The GPU texture.
  43355. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43356. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43357. */
  43358. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  43359. for ( let i = 0; i < 6; i ++ ) {
  43360. const image = images[ i ];
  43361. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  43362. if ( image.isDataTexture ) {
  43363. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43364. } else {
  43365. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43366. }
  43367. }
  43368. }
  43369. /**
  43370. * Uploads texture image data to the GPU memory.
  43371. *
  43372. * @private
  43373. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  43374. * @param {GPUTexture} textureGPU - The GPU texture.
  43375. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43376. * @param {Number} originDepth - The origin depth.
  43377. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43378. */
  43379. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  43380. const device = this.backend.device;
  43381. device.queue.copyExternalImageToTexture(
  43382. {
  43383. source: image,
  43384. flipY: flipY
  43385. }, {
  43386. texture: textureGPU,
  43387. mipLevel: 0,
  43388. origin: { x: 0, y: 0, z: originDepth }
  43389. }, {
  43390. width: image.width,
  43391. height: image.height,
  43392. depthOrArrayLayers: 1
  43393. }
  43394. );
  43395. }
  43396. /**
  43397. * Returns the pass utils singleton.
  43398. *
  43399. * @private
  43400. * @return {WebGPUTexturePassUtils} The utils instance.
  43401. */
  43402. _getPassUtils() {
  43403. let passUtils = this._passUtils;
  43404. if ( passUtils === null ) {
  43405. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  43406. }
  43407. return passUtils;
  43408. }
  43409. /**
  43410. * Generates mipmaps for the given GPU texture.
  43411. *
  43412. * @private
  43413. * @param {GPUTexture} textureGPU - The GPU texture object.
  43414. * @param {Object} textureDescriptorGPU - The texture descriptor.
  43415. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43416. */
  43417. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  43418. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  43419. }
  43420. /**
  43421. * Flip the contents of the given GPU texture along its vertical axis.
  43422. *
  43423. * @private
  43424. * @param {GPUTexture} textureGPU - The GPU texture object.
  43425. * @param {Object} textureDescriptorGPU - The texture descriptor.
  43426. * @param {Number} [originDepth=0] - The origin depth.
  43427. */
  43428. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  43429. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  43430. }
  43431. /**
  43432. * Uploads texture buffer data to the GPU memory.
  43433. *
  43434. * @private
  43435. * @param {Object} image - An object defining the image buffer data.
  43436. * @param {GPUTexture} textureGPU - The GPU texture.
  43437. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43438. * @param {Number} originDepth - The origin depth.
  43439. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43440. * @param {Number} [depth=0] - TODO.
  43441. */
  43442. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  43443. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43444. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  43445. const device = this.backend.device;
  43446. const data = image.data;
  43447. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  43448. const bytesPerRow = image.width * bytesPerTexel;
  43449. device.queue.writeTexture(
  43450. {
  43451. texture: textureGPU,
  43452. mipLevel: 0,
  43453. origin: { x: 0, y: 0, z: originDepth }
  43454. },
  43455. data,
  43456. {
  43457. offset: image.width * image.height * bytesPerTexel * depth,
  43458. bytesPerRow
  43459. },
  43460. {
  43461. width: image.width,
  43462. height: image.height,
  43463. depthOrArrayLayers: 1
  43464. } );
  43465. if ( flipY === true ) {
  43466. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  43467. }
  43468. }
  43469. /**
  43470. * Uploads compressed texture data to the GPU memory.
  43471. *
  43472. * @private
  43473. * @param {Array<Object>} mipmaps - An array with mipmap data.
  43474. * @param {GPUTexture} textureGPU - The GPU texture.
  43475. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43476. */
  43477. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  43478. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43479. const device = this.backend.device;
  43480. const blockData = this._getBlockData( textureDescriptorGPU.format );
  43481. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  43482. for ( let i = 0; i < mipmaps.length; i ++ ) {
  43483. const mipmap = mipmaps[ i ];
  43484. const width = mipmap.width;
  43485. const height = mipmap.height;
  43486. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  43487. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  43488. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  43489. for ( let j = 0; j < depth; j ++ ) {
  43490. device.queue.writeTexture(
  43491. {
  43492. texture: textureGPU,
  43493. mipLevel: i,
  43494. origin: { x: 0, y: 0, z: j }
  43495. },
  43496. mipmap.data,
  43497. {
  43498. offset: j * bytesPerImage,
  43499. bytesPerRow,
  43500. rowsPerImage: Math.ceil( height / blockData.height )
  43501. },
  43502. {
  43503. width: Math.ceil( width / blockData.width ) * blockData.width,
  43504. height: Math.ceil( height / blockData.height ) * blockData.height,
  43505. depthOrArrayLayers: 1
  43506. }
  43507. );
  43508. }
  43509. }
  43510. }
  43511. /**
  43512. * This method is only relevant for compressed texture formats. It returns a block
  43513. * data descriptor for the given GPU compressed texture format.
  43514. *
  43515. * @private
  43516. * @param {String} format - The GPU compressed texture format.
  43517. * @return {Object} The block data descriptor.
  43518. */
  43519. _getBlockData( format ) {
  43520. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  43521. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  43522. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  43523. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  43524. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  43525. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  43526. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  43527. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43528. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43529. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43530. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  43531. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  43532. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  43533. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  43534. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43535. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  43536. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  43537. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  43538. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  43539. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  43540. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  43541. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  43542. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  43543. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  43544. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  43545. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  43546. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  43547. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  43548. }
  43549. /**
  43550. * Converts the three.js uv wrapping constants to GPU address mode constants.
  43551. *
  43552. * @private
  43553. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  43554. * @return {String} The GPU address mode.
  43555. */
  43556. _convertAddressMode( value ) {
  43557. let addressMode = GPUAddressMode.ClampToEdge;
  43558. if ( value === RepeatWrapping ) {
  43559. addressMode = GPUAddressMode.Repeat;
  43560. } else if ( value === MirroredRepeatWrapping ) {
  43561. addressMode = GPUAddressMode.MirrorRepeat;
  43562. }
  43563. return addressMode;
  43564. }
  43565. /**
  43566. * Converts the three.js filter constants to GPU filter constants.
  43567. *
  43568. * @private
  43569. * @param {Number} value - The three.js constant defining a filter mode.
  43570. * @return {String} The GPU filter mode.
  43571. */
  43572. _convertFilterMode( value ) {
  43573. let filterMode = GPUFilterMode.Linear;
  43574. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  43575. filterMode = GPUFilterMode.Nearest;
  43576. }
  43577. return filterMode;
  43578. }
  43579. /**
  43580. * Returns the bytes-per-texel value for the given GPU texture format.
  43581. *
  43582. * @private
  43583. * @param {String} format - The GPU texture format.
  43584. * @return {Number} The bytes-per-texel.
  43585. */
  43586. _getBytesPerTexel( format ) {
  43587. // 8-bit formats
  43588. if ( format === GPUTextureFormat.R8Unorm ||
  43589. format === GPUTextureFormat.R8Snorm ||
  43590. format === GPUTextureFormat.R8Uint ||
  43591. format === GPUTextureFormat.R8Sint ) return 1;
  43592. // 16-bit formats
  43593. if ( format === GPUTextureFormat.R16Uint ||
  43594. format === GPUTextureFormat.R16Sint ||
  43595. format === GPUTextureFormat.R16Float ||
  43596. format === GPUTextureFormat.RG8Unorm ||
  43597. format === GPUTextureFormat.RG8Snorm ||
  43598. format === GPUTextureFormat.RG8Uint ||
  43599. format === GPUTextureFormat.RG8Sint ) return 2;
  43600. // 32-bit formats
  43601. if ( format === GPUTextureFormat.R32Uint ||
  43602. format === GPUTextureFormat.R32Sint ||
  43603. format === GPUTextureFormat.R32Float ||
  43604. format === GPUTextureFormat.RG16Uint ||
  43605. format === GPUTextureFormat.RG16Sint ||
  43606. format === GPUTextureFormat.RG16Float ||
  43607. format === GPUTextureFormat.RGBA8Unorm ||
  43608. format === GPUTextureFormat.RGBA8UnormSRGB ||
  43609. format === GPUTextureFormat.RGBA8Snorm ||
  43610. format === GPUTextureFormat.RGBA8Uint ||
  43611. format === GPUTextureFormat.RGBA8Sint ||
  43612. format === GPUTextureFormat.BGRA8Unorm ||
  43613. format === GPUTextureFormat.BGRA8UnormSRGB ||
  43614. // Packed 32-bit formats
  43615. format === GPUTextureFormat.RGB9E5UFloat ||
  43616. format === GPUTextureFormat.RGB10A2Unorm ||
  43617. format === GPUTextureFormat.RG11B10UFloat ||
  43618. format === GPUTextureFormat.Depth32Float ||
  43619. format === GPUTextureFormat.Depth24Plus ||
  43620. format === GPUTextureFormat.Depth24PlusStencil8 ||
  43621. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  43622. // 64-bit formats
  43623. if ( format === GPUTextureFormat.RG32Uint ||
  43624. format === GPUTextureFormat.RG32Sint ||
  43625. format === GPUTextureFormat.RG32Float ||
  43626. format === GPUTextureFormat.RGBA16Uint ||
  43627. format === GPUTextureFormat.RGBA16Sint ||
  43628. format === GPUTextureFormat.RGBA16Float ) return 8;
  43629. // 128-bit formats
  43630. if ( format === GPUTextureFormat.RGBA32Uint ||
  43631. format === GPUTextureFormat.RGBA32Sint ||
  43632. format === GPUTextureFormat.RGBA32Float ) return 16;
  43633. }
  43634. /**
  43635. * Returns the corresponding typed array type for the given GPU texture format.
  43636. *
  43637. * @private
  43638. * @param {String} format - The GPU texture format.
  43639. * @return {TypedArray.constructor} The typed array type.
  43640. */
  43641. _getTypedArrayType( format ) {
  43642. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  43643. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  43644. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  43645. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  43646. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  43647. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  43648. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  43649. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  43650. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  43651. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  43652. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  43653. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  43654. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  43655. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  43656. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  43657. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  43658. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  43659. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  43660. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  43661. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  43662. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  43663. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  43664. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  43665. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  43666. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  43667. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  43668. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  43669. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  43670. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  43671. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  43672. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  43673. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  43674. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  43675. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  43676. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  43677. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  43678. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  43679. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  43680. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  43681. }
  43682. /**
  43683. * Returns the GPU dimensions for the given texture.
  43684. *
  43685. * @private
  43686. * @param {Texture} texture - The texture.
  43687. * @return {String} The GPU dimension.
  43688. */
  43689. _getDimension( texture ) {
  43690. let dimension;
  43691. if ( texture.isData3DTexture ) {
  43692. dimension = GPUTextureDimension.ThreeD;
  43693. } else {
  43694. dimension = GPUTextureDimension.TwoD;
  43695. }
  43696. return dimension;
  43697. }
  43698. }
  43699. /**
  43700. * Returns the GPU format for the given texture.
  43701. *
  43702. * @param {Texture} texture - The texture.
  43703. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  43704. * It is not necessary to apply the device for most formats.
  43705. * @return {String} The GPU format.
  43706. */
  43707. function getFormat( texture, device = null ) {
  43708. const format = texture.format;
  43709. const type = texture.type;
  43710. const colorSpace = texture.colorSpace;
  43711. let formatGPU;
  43712. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  43713. switch ( format ) {
  43714. case RGBA_S3TC_DXT1_Format:
  43715. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  43716. break;
  43717. case RGBA_S3TC_DXT3_Format:
  43718. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  43719. break;
  43720. case RGBA_S3TC_DXT5_Format:
  43721. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  43722. break;
  43723. case RGB_ETC2_Format:
  43724. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  43725. break;
  43726. case RGBA_ETC2_EAC_Format:
  43727. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  43728. break;
  43729. case RGBA_ASTC_4x4_Format:
  43730. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  43731. break;
  43732. case RGBA_ASTC_5x4_Format:
  43733. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  43734. break;
  43735. case RGBA_ASTC_5x5_Format:
  43736. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  43737. break;
  43738. case RGBA_ASTC_6x5_Format:
  43739. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  43740. break;
  43741. case RGBA_ASTC_6x6_Format:
  43742. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  43743. break;
  43744. case RGBA_ASTC_8x5_Format:
  43745. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  43746. break;
  43747. case RGBA_ASTC_8x6_Format:
  43748. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  43749. break;
  43750. case RGBA_ASTC_8x8_Format:
  43751. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  43752. break;
  43753. case RGBA_ASTC_10x5_Format:
  43754. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  43755. break;
  43756. case RGBA_ASTC_10x6_Format:
  43757. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  43758. break;
  43759. case RGBA_ASTC_10x8_Format:
  43760. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  43761. break;
  43762. case RGBA_ASTC_10x10_Format:
  43763. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  43764. break;
  43765. case RGBA_ASTC_12x10_Format:
  43766. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  43767. break;
  43768. case RGBA_ASTC_12x12_Format:
  43769. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  43770. break;
  43771. case RGBAFormat:
  43772. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43773. break;
  43774. default:
  43775. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43776. }
  43777. } else {
  43778. switch ( format ) {
  43779. case RGBAFormat:
  43780. switch ( type ) {
  43781. case ByteType:
  43782. formatGPU = GPUTextureFormat.RGBA8Snorm;
  43783. break;
  43784. case ShortType:
  43785. formatGPU = GPUTextureFormat.RGBA16Sint;
  43786. break;
  43787. case UnsignedShortType:
  43788. formatGPU = GPUTextureFormat.RGBA16Uint;
  43789. break;
  43790. case UnsignedIntType:
  43791. formatGPU = GPUTextureFormat.RGBA32Uint;
  43792. break;
  43793. case IntType:
  43794. formatGPU = GPUTextureFormat.RGBA32Sint;
  43795. break;
  43796. case UnsignedByteType:
  43797. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43798. break;
  43799. case HalfFloatType:
  43800. formatGPU = GPUTextureFormat.RGBA16Float;
  43801. break;
  43802. case FloatType:
  43803. formatGPU = GPUTextureFormat.RGBA32Float;
  43804. break;
  43805. default:
  43806. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  43807. }
  43808. break;
  43809. case RGBFormat:
  43810. switch ( type ) {
  43811. case UnsignedInt5999Type:
  43812. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  43813. break;
  43814. default:
  43815. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  43816. }
  43817. break;
  43818. case RedFormat:
  43819. switch ( type ) {
  43820. case ByteType:
  43821. formatGPU = GPUTextureFormat.R8Snorm;
  43822. break;
  43823. case ShortType:
  43824. formatGPU = GPUTextureFormat.R16Sint;
  43825. break;
  43826. case UnsignedShortType:
  43827. formatGPU = GPUTextureFormat.R16Uint;
  43828. break;
  43829. case UnsignedIntType:
  43830. formatGPU = GPUTextureFormat.R32Uint;
  43831. break;
  43832. case IntType:
  43833. formatGPU = GPUTextureFormat.R32Sint;
  43834. break;
  43835. case UnsignedByteType:
  43836. formatGPU = GPUTextureFormat.R8Unorm;
  43837. break;
  43838. case HalfFloatType:
  43839. formatGPU = GPUTextureFormat.R16Float;
  43840. break;
  43841. case FloatType:
  43842. formatGPU = GPUTextureFormat.R32Float;
  43843. break;
  43844. default:
  43845. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  43846. }
  43847. break;
  43848. case RGFormat:
  43849. switch ( type ) {
  43850. case ByteType:
  43851. formatGPU = GPUTextureFormat.RG8Snorm;
  43852. break;
  43853. case ShortType:
  43854. formatGPU = GPUTextureFormat.RG16Sint;
  43855. break;
  43856. case UnsignedShortType:
  43857. formatGPU = GPUTextureFormat.RG16Uint;
  43858. break;
  43859. case UnsignedIntType:
  43860. formatGPU = GPUTextureFormat.RG32Uint;
  43861. break;
  43862. case IntType:
  43863. formatGPU = GPUTextureFormat.RG32Sint;
  43864. break;
  43865. case UnsignedByteType:
  43866. formatGPU = GPUTextureFormat.RG8Unorm;
  43867. break;
  43868. case HalfFloatType:
  43869. formatGPU = GPUTextureFormat.RG16Float;
  43870. break;
  43871. case FloatType:
  43872. formatGPU = GPUTextureFormat.RG32Float;
  43873. break;
  43874. default:
  43875. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  43876. }
  43877. break;
  43878. case DepthFormat:
  43879. switch ( type ) {
  43880. case UnsignedShortType:
  43881. formatGPU = GPUTextureFormat.Depth16Unorm;
  43882. break;
  43883. case UnsignedIntType:
  43884. formatGPU = GPUTextureFormat.Depth24Plus;
  43885. break;
  43886. case FloatType:
  43887. formatGPU = GPUTextureFormat.Depth32Float;
  43888. break;
  43889. default:
  43890. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  43891. }
  43892. break;
  43893. case DepthStencilFormat:
  43894. switch ( type ) {
  43895. case UnsignedInt248Type:
  43896. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  43897. break;
  43898. case FloatType:
  43899. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  43900. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  43901. }
  43902. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  43903. break;
  43904. default:
  43905. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  43906. }
  43907. break;
  43908. case RedIntegerFormat:
  43909. switch ( type ) {
  43910. case IntType:
  43911. formatGPU = GPUTextureFormat.R32Sint;
  43912. break;
  43913. case UnsignedIntType:
  43914. formatGPU = GPUTextureFormat.R32Uint;
  43915. break;
  43916. default:
  43917. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  43918. }
  43919. break;
  43920. case RGIntegerFormat:
  43921. switch ( type ) {
  43922. case IntType:
  43923. formatGPU = GPUTextureFormat.RG32Sint;
  43924. break;
  43925. case UnsignedIntType:
  43926. formatGPU = GPUTextureFormat.RG32Uint;
  43927. break;
  43928. default:
  43929. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  43930. }
  43931. break;
  43932. case RGBAIntegerFormat:
  43933. switch ( type ) {
  43934. case IntType:
  43935. formatGPU = GPUTextureFormat.RGBA32Sint;
  43936. break;
  43937. case UnsignedIntType:
  43938. formatGPU = GPUTextureFormat.RGBA32Uint;
  43939. break;
  43940. default:
  43941. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43942. }
  43943. break;
  43944. default:
  43945. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43946. }
  43947. }
  43948. return formatGPU;
  43949. }
  43950. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43951. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43952. const wgslTypeLib$1 = {
  43953. 'f32': 'float',
  43954. 'i32': 'int',
  43955. 'u32': 'uint',
  43956. 'bool': 'bool',
  43957. 'vec2<f32>': 'vec2',
  43958. 'vec2<i32>': 'ivec2',
  43959. 'vec2<u32>': 'uvec2',
  43960. 'vec2<bool>': 'bvec2',
  43961. 'vec2f': 'vec2',
  43962. 'vec2i': 'ivec2',
  43963. 'vec2u': 'uvec2',
  43964. 'vec2b': 'bvec2',
  43965. 'vec3<f32>': 'vec3',
  43966. 'vec3<i32>': 'ivec3',
  43967. 'vec3<u32>': 'uvec3',
  43968. 'vec3<bool>': 'bvec3',
  43969. 'vec3f': 'vec3',
  43970. 'vec3i': 'ivec3',
  43971. 'vec3u': 'uvec3',
  43972. 'vec3b': 'bvec3',
  43973. 'vec4<f32>': 'vec4',
  43974. 'vec4<i32>': 'ivec4',
  43975. 'vec4<u32>': 'uvec4',
  43976. 'vec4<bool>': 'bvec4',
  43977. 'vec4f': 'vec4',
  43978. 'vec4i': 'ivec4',
  43979. 'vec4u': 'uvec4',
  43980. 'vec4b': 'bvec4',
  43981. 'mat2x2<f32>': 'mat2',
  43982. 'mat2x2f': 'mat2',
  43983. 'mat3x3<f32>': 'mat3',
  43984. 'mat3x3f': 'mat3',
  43985. 'mat4x4<f32>': 'mat4',
  43986. 'mat4x4f': 'mat4',
  43987. 'sampler': 'sampler',
  43988. 'texture_1d': 'texture',
  43989. 'texture_2d': 'texture',
  43990. 'texture_2d_array': 'texture',
  43991. 'texture_multisampled_2d': 'cubeTexture',
  43992. 'texture_depth_2d': 'depthTexture',
  43993. 'texture_depth_multisampled_2d': 'depthTexture',
  43994. 'texture_3d': 'texture3D',
  43995. 'texture_cube': 'cubeTexture',
  43996. 'texture_cube_array': 'cubeTexture',
  43997. 'texture_storage_1d': 'storageTexture',
  43998. 'texture_storage_2d': 'storageTexture',
  43999. 'texture_storage_2d_array': 'storageTexture',
  44000. 'texture_storage_3d': 'storageTexture'
  44001. };
  44002. const parse = ( source ) => {
  44003. source = source.trim();
  44004. const declaration = source.match( declarationRegexp );
  44005. if ( declaration !== null && declaration.length === 4 ) {
  44006. const inputsCode = declaration[ 2 ];
  44007. const propsMatches = [];
  44008. let match = null;
  44009. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  44010. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  44011. }
  44012. // Process matches to correctly pair names and types
  44013. const inputs = [];
  44014. for ( let i = 0; i < propsMatches.length; i ++ ) {
  44015. const { name, type } = propsMatches[ i ];
  44016. let resolvedType = type;
  44017. if ( resolvedType.startsWith( 'ptr' ) ) {
  44018. resolvedType = 'pointer';
  44019. } else {
  44020. if ( resolvedType.startsWith( 'texture' ) ) {
  44021. resolvedType = type.split( '<' )[ 0 ];
  44022. }
  44023. resolvedType = wgslTypeLib$1[ resolvedType ];
  44024. }
  44025. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  44026. }
  44027. const blockCode = source.substring( declaration[ 0 ].length );
  44028. const outputType = declaration[ 3 ] || 'void';
  44029. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  44030. const type = wgslTypeLib$1[ outputType ] || outputType;
  44031. return {
  44032. type,
  44033. inputs,
  44034. name,
  44035. inputsCode,
  44036. blockCode,
  44037. outputType
  44038. };
  44039. } else {
  44040. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  44041. }
  44042. };
  44043. /**
  44044. * This class represents a WSL node function.
  44045. *
  44046. * @augments NodeFunction
  44047. */
  44048. class WGSLNodeFunction extends NodeFunction {
  44049. /**
  44050. * Constructs a new WGSL node function.
  44051. *
  44052. * @param {String} source - The WGSL source.
  44053. */
  44054. constructor( source ) {
  44055. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  44056. super( type, inputs, name );
  44057. this.inputsCode = inputsCode;
  44058. this.blockCode = blockCode;
  44059. this.outputType = outputType;
  44060. }
  44061. /**
  44062. * This method returns the WGSL code of the node function.
  44063. *
  44064. * @param {String} [name=this.name] - The function's name.
  44065. * @return {String} The shader code.
  44066. */
  44067. getCode( name = this.name ) {
  44068. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  44069. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  44070. }
  44071. }
  44072. /**
  44073. * A WGSL node parser.
  44074. *
  44075. * @augments NodeParser
  44076. */
  44077. class WGSLNodeParser extends NodeParser {
  44078. /**
  44079. * The method parses the given WGSL code an returns a node function.
  44080. *
  44081. * @param {String} source - The WGSL code.
  44082. * @return {WGSLNodeFunction} A node function.
  44083. */
  44084. parseFunction( source ) {
  44085. return new WGSLNodeFunction( source );
  44086. }
  44087. }
  44088. // GPUShaderStage is not defined in browsers not supporting WebGPU
  44089. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  44090. const accessNames = {
  44091. [ NodeAccess.READ_ONLY ]: 'read',
  44092. [ NodeAccess.WRITE_ONLY ]: 'write',
  44093. [ NodeAccess.READ_WRITE ]: 'read_write'
  44094. };
  44095. const wrapNames = {
  44096. [ RepeatWrapping ]: 'repeat',
  44097. [ ClampToEdgeWrapping ]: 'clamp',
  44098. [ MirroredRepeatWrapping ]: 'mirror'
  44099. };
  44100. const gpuShaderStageLib = {
  44101. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  44102. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  44103. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  44104. };
  44105. const supports = {
  44106. instance: true,
  44107. swizzleAssign: false,
  44108. storageBuffer: true
  44109. };
  44110. const wgslFnOpLib = {
  44111. '^^': 'tsl_xor'
  44112. };
  44113. const wgslTypeLib = {
  44114. float: 'f32',
  44115. int: 'i32',
  44116. uint: 'u32',
  44117. bool: 'bool',
  44118. color: 'vec3<f32>',
  44119. vec2: 'vec2<f32>',
  44120. ivec2: 'vec2<i32>',
  44121. uvec2: 'vec2<u32>',
  44122. bvec2: 'vec2<bool>',
  44123. vec3: 'vec3<f32>',
  44124. ivec3: 'vec3<i32>',
  44125. uvec3: 'vec3<u32>',
  44126. bvec3: 'vec3<bool>',
  44127. vec4: 'vec4<f32>',
  44128. ivec4: 'vec4<i32>',
  44129. uvec4: 'vec4<u32>',
  44130. bvec4: 'vec4<bool>',
  44131. mat2: 'mat2x2<f32>',
  44132. mat3: 'mat3x3<f32>',
  44133. mat4: 'mat4x4<f32>'
  44134. };
  44135. const wgslCodeCache = {};
  44136. const wgslPolyfill = {
  44137. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  44138. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  44139. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  44140. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  44141. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  44142. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  44143. 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 ); }' ),
  44144. 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 ); }' ),
  44145. 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 ); }' ),
  44146. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  44147. 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 ); }' ),
  44148. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  44149. biquadraticTexture: new CodeNode( /* wgsl */`
  44150. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  44151. let res = vec2f( iRes );
  44152. let uvScaled = coord * res;
  44153. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  44154. // https://www.shadertoy.com/view/WtyXRy
  44155. let uv = uvWrapping - 0.5;
  44156. let iuv = floor( uv );
  44157. let f = fract( uv );
  44158. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  44159. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  44160. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  44161. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  44162. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  44163. }
  44164. ` )
  44165. };
  44166. const wgslMethods = {
  44167. dFdx: 'dpdx',
  44168. dFdy: '- dpdy',
  44169. mod_float: 'tsl_mod_float',
  44170. mod_vec2: 'tsl_mod_vec2',
  44171. mod_vec3: 'tsl_mod_vec3',
  44172. mod_vec4: 'tsl_mod_vec4',
  44173. equals_bool: 'tsl_equals_bool',
  44174. equals_bvec2: 'tsl_equals_bvec2',
  44175. equals_bvec3: 'tsl_equals_bvec3',
  44176. equals_bvec4: 'tsl_equals_bvec4',
  44177. inversesqrt: 'inverseSqrt',
  44178. bitcast: 'bitcast<f32>'
  44179. };
  44180. // WebGPU issue: does not support pow() with negative base on Windows
  44181. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  44182. 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 ); }' );
  44183. 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 ] );
  44184. 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 ] );
  44185. 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 ] );
  44186. wgslMethods.pow_float = 'tsl_pow_float';
  44187. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  44188. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  44189. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  44190. }
  44191. //
  44192. let diagnostics = '';
  44193. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  44194. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  44195. }
  44196. /**
  44197. * A node builder targeting WGSL.
  44198. *
  44199. * This module generates WGSL shader code from node materials and also
  44200. * generates the respective bindings and vertex buffer definitions. These
  44201. * data are later used by the renderer to create render and compute pipelines
  44202. * for render objects.
  44203. *
  44204. * @augments NodeBuilder
  44205. */
  44206. class WGSLNodeBuilder extends NodeBuilder {
  44207. /**
  44208. * Constructs a new WGSL node builder renderer.
  44209. *
  44210. * @param {Object3D} object - The 3D object.
  44211. * @param {Renderer} renderer - The renderer.
  44212. */
  44213. constructor( object, renderer ) {
  44214. super( object, renderer, new WGSLNodeParser() );
  44215. /**
  44216. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  44217. * another dictionary which manages UBOs per group ('render','frame','object').
  44218. *
  44219. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  44220. */
  44221. this.uniformGroups = {};
  44222. /**
  44223. * A dictionary that holds for each shader stage a Map of builtins.
  44224. *
  44225. * @type {Object<String,Map<String,Object>>}
  44226. */
  44227. this.builtins = {};
  44228. /**
  44229. * A dictionary that holds for each shader stage a Set of directives.
  44230. *
  44231. * @type {Object<String,Set<String>>}
  44232. */
  44233. this.directives = {};
  44234. /**
  44235. * A map for managing scope arrays. Only relevant for when using
  44236. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  44237. *
  44238. * @type {Map<String,Object>}
  44239. */
  44240. this.scopedArrays = new Map();
  44241. }
  44242. /**
  44243. * Checks if the given texture requires a manual conversion to the working color space.
  44244. *
  44245. * @param {Texture} texture - The texture to check.
  44246. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  44247. */
  44248. needsToWorkingColorSpace( texture ) {
  44249. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44250. }
  44251. /**
  44252. * Generates the WGSL snippet for sampled textures.
  44253. *
  44254. * @private
  44255. * @param {Texture} texture - The texture.
  44256. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44257. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44258. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44259. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44260. * @return {String} The WGSL snippet.
  44261. */
  44262. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44263. if ( shaderStage === 'fragment' ) {
  44264. if ( depthSnippet ) {
  44265. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  44266. } else {
  44267. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  44268. }
  44269. } else if ( this.isFilteredTexture( texture ) ) {
  44270. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  44271. } else {
  44272. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  44273. }
  44274. }
  44275. /**
  44276. * Generates the WGSL snippet when sampling video textures.
  44277. *
  44278. * @private
  44279. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  44280. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44281. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44282. * @return {String} The WGSL snippet.
  44283. */
  44284. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  44285. if ( shaderStage === 'fragment' ) {
  44286. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  44287. } else {
  44288. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  44289. }
  44290. }
  44291. /**
  44292. * Generates the WGSL snippet when sampling textures with explicit mip level.
  44293. *
  44294. * @private
  44295. * @param {Texture} texture - The texture.
  44296. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44297. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44298. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44299. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44300. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44301. * @return {String} The WGSL snippet.
  44302. */
  44303. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44304. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  44305. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  44306. } else if ( this.isFilteredTexture( texture ) ) {
  44307. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  44308. } else {
  44309. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  44310. }
  44311. }
  44312. /**
  44313. * Generates a wrap function used in context of textures.
  44314. *
  44315. * @param {Texture} texture - The texture to generate the function for.
  44316. * @return {String} The name of the generated function.
  44317. */
  44318. generateWrapFunction( texture ) {
  44319. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  44320. let nodeCode = wgslCodeCache[ functionName ];
  44321. if ( nodeCode === undefined ) {
  44322. const includes = [];
  44323. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  44324. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  44325. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  44326. const addWrapSnippet = ( wrap, axis ) => {
  44327. if ( wrap === RepeatWrapping ) {
  44328. includes.push( wgslPolyfill.repeatWrapping_float );
  44329. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  44330. } else if ( wrap === ClampToEdgeWrapping ) {
  44331. includes.push( wgslPolyfill.clampWrapping_float );
  44332. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  44333. } else if ( wrap === MirroredRepeatWrapping ) {
  44334. includes.push( wgslPolyfill.mirrorWrapping_float );
  44335. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  44336. } else {
  44337. code += `\t\tcoord.${ axis }`;
  44338. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  44339. }
  44340. };
  44341. addWrapSnippet( texture.wrapS, 'x' );
  44342. code += ',\n';
  44343. addWrapSnippet( texture.wrapT, 'y' );
  44344. if ( texture.isData3DTexture ) {
  44345. code += ',\n';
  44346. addWrapSnippet( texture.wrapR, 'z' );
  44347. }
  44348. code += '\n\t);\n\n}\n';
  44349. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  44350. }
  44351. nodeCode.build( this );
  44352. return functionName;
  44353. }
  44354. /**
  44355. * Generates the array declaration string.
  44356. *
  44357. * @param {String} type - The type.
  44358. * @param {Number?} [count] - The count.
  44359. * @return {String} The generated value as a shader string.
  44360. */
  44361. generateArrayDeclaration( type, count ) {
  44362. return `array< ${ this.getType( type ) }, ${ count } >`;
  44363. }
  44364. /**
  44365. * Generates a WGSL variable that holds the texture dimension of the given texture.
  44366. * It also returns information about the the number of layers (elements) of an arrayed
  44367. * texture as well as the cube face count of cube textures.
  44368. *
  44369. * @param {Texture} texture - The texture to generate the function for.
  44370. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  44371. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44372. * @return {String} The name of the dimension variable.
  44373. */
  44374. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  44375. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  44376. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  44377. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  44378. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  44379. let textureDimensionsParams;
  44380. let dimensionType;
  44381. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  44382. const isMultisampled = primarySamples > 1;
  44383. if ( texture.isData3DTexture ) {
  44384. dimensionType = 'vec3<u32>';
  44385. } else {
  44386. // Regular 2D textures, depth textures, etc.
  44387. dimensionType = 'vec2<u32>';
  44388. }
  44389. // Build parameters string based on texture type and multisampling
  44390. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  44391. textureDimensionsParams = textureProperty;
  44392. } else {
  44393. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  44394. }
  44395. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  44396. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  44397. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  44398. textureData.arrayLayerCount = new VarNode(
  44399. new ExpressionNode(
  44400. `textureNumLayers(${textureProperty})`,
  44401. 'u32'
  44402. )
  44403. );
  44404. }
  44405. // For cube textures, we know it's always 6 faces
  44406. if ( texture.isTextureCube ) {
  44407. textureData.cubeFaceCount = new VarNode(
  44408. new ExpressionNode( '6u', 'u32' )
  44409. );
  44410. }
  44411. }
  44412. return textureDimensionNode.build( this );
  44413. }
  44414. /**
  44415. * Generates the WGSL snippet for a manual filtered texture.
  44416. *
  44417. * @param {Texture} texture - The texture.
  44418. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44419. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44420. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44421. * @return {String} The WGSL snippet.
  44422. */
  44423. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  44424. this._include( 'biquadraticTexture' );
  44425. const wrapFunction = this.generateWrapFunction( texture );
  44426. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  44427. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  44428. }
  44429. /**
  44430. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  44431. * Since it's a lookup, no sampling or filtering is applied.
  44432. *
  44433. * @param {Texture} texture - The texture.
  44434. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44435. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44436. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44437. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44438. * @return {String} The WGSL snippet.
  44439. */
  44440. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  44441. const wrapFunction = this.generateWrapFunction( texture );
  44442. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  44443. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  44444. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  44445. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  44446. }
  44447. /**
  44448. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  44449. *
  44450. * @param {Texture} texture - The texture.
  44451. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44452. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44453. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44454. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44455. * @return {String} The WGSL snippet.
  44456. */
  44457. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  44458. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  44459. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  44460. } else if ( depthSnippet ) {
  44461. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  44462. } else {
  44463. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  44464. }
  44465. }
  44466. /**
  44467. * Generates the WGSL snippet that writes a single texel to a texture.
  44468. *
  44469. * @param {Texture} texture - The texture.
  44470. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44471. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44472. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  44473. * @return {String} The WGSL snippet.
  44474. */
  44475. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  44476. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  44477. }
  44478. /**
  44479. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  44480. *
  44481. * @param {Texture} texture - The texture.
  44482. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  44483. */
  44484. isSampleCompare( texture ) {
  44485. return texture.isDepthTexture === true && texture.compareFunction !== null;
  44486. }
  44487. /**
  44488. * Returns `true` if the given texture is unfilterable.
  44489. *
  44490. * @param {Texture} texture - The texture.
  44491. * @return {Boolean} Whether the given texture is unfilterable or not.
  44492. */
  44493. isUnfilterable( texture ) {
  44494. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  44495. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  44496. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  44497. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  44498. }
  44499. /**
  44500. * Generates the WGSL snippet for sampling/loading the given texture.
  44501. *
  44502. * @param {Texture} texture - The texture.
  44503. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44504. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44505. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44506. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44507. * @return {String} The WGSL snippet.
  44508. */
  44509. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44510. let snippet = null;
  44511. if ( texture.isVideoTexture === true ) {
  44512. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44513. } else if ( this.isUnfilterable( texture ) ) {
  44514. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  44515. } else {
  44516. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  44517. }
  44518. return snippet;
  44519. }
  44520. /**
  44521. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  44522. *
  44523. * @param {Texture} texture - The texture.
  44524. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44525. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44526. * @param {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  44527. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44528. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44529. * @return {String} The WGSL snippet.
  44530. */
  44531. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44532. if ( shaderStage === 'fragment' ) {
  44533. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  44534. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44535. } else {
  44536. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  44537. }
  44538. }
  44539. /**
  44540. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  44541. * against a reference value.
  44542. *
  44543. * @param {Texture} texture - The texture.
  44544. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44545. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44546. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  44547. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44548. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44549. * @return {String} The WGSL snippet.
  44550. */
  44551. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44552. if ( shaderStage === 'fragment' ) {
  44553. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  44554. } else {
  44555. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44556. }
  44557. }
  44558. /**
  44559. * Generates the WGSL snippet when sampling textures with explicit mip level.
  44560. *
  44561. * @param {Texture} texture - The texture.
  44562. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44563. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44564. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44565. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44566. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44567. * @return {String} The WGSL snippet.
  44568. */
  44569. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44570. let snippet = null;
  44571. if ( texture.isVideoTexture === true ) {
  44572. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44573. } else {
  44574. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  44575. }
  44576. return snippet;
  44577. }
  44578. /**
  44579. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  44580. *
  44581. * @param {Texture} texture - The texture.
  44582. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44583. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44584. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  44585. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44586. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44587. * @return {String} The WGSL snippet.
  44588. */
  44589. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44590. if ( shaderStage === 'fragment' ) {
  44591. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  44592. } else {
  44593. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  44594. }
  44595. }
  44596. /**
  44597. * Returns a WGSL snippet that represents the property name of the given node.
  44598. *
  44599. * @param {Node} node - The node.
  44600. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44601. * @return {String} The property name.
  44602. */
  44603. getPropertyName( node, shaderStage = this.shaderStage ) {
  44604. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  44605. if ( shaderStage === 'vertex' ) {
  44606. return `varyings.${ node.name }`;
  44607. }
  44608. } else if ( node.isNodeUniform === true ) {
  44609. const name = node.name;
  44610. const type = node.type;
  44611. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44612. return name;
  44613. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44614. return `NodeBuffer_${ node.id }.${name}`;
  44615. } else {
  44616. return node.groupNode.name + '.' + name;
  44617. }
  44618. }
  44619. return super.getPropertyName( node );
  44620. }
  44621. /**
  44622. * Returns the output struct name.
  44623. *
  44624. * @return {String} The name of the output struct.
  44625. */
  44626. getOutputStructName() {
  44627. return 'output';
  44628. }
  44629. /**
  44630. * Returns uniforms group count for the given shader stage.
  44631. *
  44632. * @private
  44633. * @param {String} shaderStage - The shader stage.
  44634. * @return {Number} The uniforms group count for the given shader stage.
  44635. */
  44636. _getUniformGroupCount( shaderStage ) {
  44637. return Object.keys( this.uniforms[ shaderStage ] ).length;
  44638. }
  44639. /**
  44640. * Returns the native shader operator name for a given generic name.
  44641. *
  44642. * @param {String} op - The operator name to resolve.
  44643. * @return {String} The resolved operator name.
  44644. */
  44645. getFunctionOperator( op ) {
  44646. const fnOp = wgslFnOpLib[ op ];
  44647. if ( fnOp !== undefined ) {
  44648. this._include( fnOp );
  44649. return fnOp;
  44650. }
  44651. return null;
  44652. }
  44653. /**
  44654. * Returns the node access for the given node and shader stage.
  44655. *
  44656. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  44657. * @param {String} shaderStage - The shader stage.
  44658. * @return {String} The node access.
  44659. */
  44660. getNodeAccess( node, shaderStage ) {
  44661. if ( shaderStage !== 'compute' )
  44662. return NodeAccess.READ_ONLY;
  44663. return node.access;
  44664. }
  44665. /**
  44666. * Returns A WGSL snippet representing the storage access.
  44667. *
  44668. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  44669. * @param {String} shaderStage - The shader stage.
  44670. * @return {String} The WGSL snippet representing the storage access.
  44671. */
  44672. getStorageAccess( node, shaderStage ) {
  44673. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  44674. }
  44675. /**
  44676. * This method is one of the more important ones since it's responsible
  44677. * for generating a matching binding instance for the given uniform node.
  44678. *
  44679. * These bindings are later used in the renderer to create bind groups
  44680. * and layouts.
  44681. *
  44682. * @param {UniformNode} node - The uniform node.
  44683. * @param {String} type - The node data type.
  44684. * @param {String} shaderStage - The shader stage.
  44685. * @param {String?} [name=null] - An optional uniform name.
  44686. * @return {NodeUniform} The node uniform object.
  44687. */
  44688. getUniformFromNode( node, type, shaderStage, name = null ) {
  44689. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44690. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44691. if ( nodeData.uniformGPU === undefined ) {
  44692. let uniformGPU;
  44693. const group = node.groupNode;
  44694. const groupName = group.name;
  44695. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44696. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44697. let texture = null;
  44698. const access = this.getNodeAccess( node, shaderStage );
  44699. if ( type === 'texture' || type === 'storageTexture' ) {
  44700. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  44701. } else if ( type === 'cubeTexture' ) {
  44702. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  44703. } else if ( type === 'texture3D' ) {
  44704. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  44705. }
  44706. texture.store = node.isStorageTextureNode === true;
  44707. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44708. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  44709. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  44710. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44711. bindings.push( sampler, texture );
  44712. uniformGPU = [ sampler, texture ];
  44713. } else {
  44714. bindings.push( texture );
  44715. uniformGPU = [ texture ];
  44716. }
  44717. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44718. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  44719. const buffer = new bufferClass( node, group );
  44720. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44721. bindings.push( buffer );
  44722. uniformGPU = buffer;
  44723. } else {
  44724. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44725. let uniformsGroup = uniformsStage[ groupName ];
  44726. if ( uniformsGroup === undefined ) {
  44727. uniformsGroup = new NodeUniformsGroup( groupName, group );
  44728. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44729. uniformsStage[ groupName ] = uniformsGroup;
  44730. bindings.push( uniformsGroup );
  44731. }
  44732. uniformGPU = this.getNodeUniform( uniformNode, type );
  44733. uniformsGroup.addUniform( uniformGPU );
  44734. }
  44735. nodeData.uniformGPU = uniformGPU;
  44736. }
  44737. return uniformNode;
  44738. }
  44739. /**
  44740. * This method should be used whenever builtins are required in nodes.
  44741. * The internal builtins data structure will make sure builtins are
  44742. * defined in the WGSL source.
  44743. *
  44744. * @param {String} name - The builtin name.
  44745. * @param {String} property - The property name.
  44746. * @param {String} type - The node data type.
  44747. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44748. * @return {String} The property name.
  44749. */
  44750. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  44751. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  44752. if ( map.has( name ) === false ) {
  44753. map.set( name, {
  44754. name,
  44755. property,
  44756. type
  44757. } );
  44758. }
  44759. return property;
  44760. }
  44761. /**
  44762. * Returns `true` if the given builtin is defined in the given shader stage.
  44763. *
  44764. * @param {String} name - The builtin name.
  44765. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44766. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  44767. */
  44768. hasBuiltin( name, shaderStage = this.shaderStage ) {
  44769. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  44770. }
  44771. /**
  44772. * Returns the vertex index builtin.
  44773. *
  44774. * @return {String} The vertex index.
  44775. */
  44776. getVertexIndex() {
  44777. if ( this.shaderStage === 'vertex' ) {
  44778. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  44779. }
  44780. return 'vertexIndex';
  44781. }
  44782. /**
  44783. * Builds the given shader node.
  44784. *
  44785. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44786. * @return {String} The WGSL function code.
  44787. */
  44788. buildFunctionCode( shaderNode ) {
  44789. const layout = shaderNode.layout;
  44790. const flowData = this.flowShaderNode( shaderNode );
  44791. const parameters = [];
  44792. for ( const input of layout.inputs ) {
  44793. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  44794. }
  44795. //
  44796. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  44797. ${ flowData.vars }
  44798. ${ flowData.code }
  44799. `;
  44800. if ( flowData.result ) {
  44801. code += `\treturn ${ flowData.result };\n`;
  44802. }
  44803. code += '\n}\n';
  44804. //
  44805. return code;
  44806. }
  44807. /**
  44808. * Returns the instance index builtin.
  44809. *
  44810. * @return {String} The instance index.
  44811. */
  44812. getInstanceIndex() {
  44813. if ( this.shaderStage === 'vertex' ) {
  44814. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  44815. }
  44816. return 'instanceIndex';
  44817. }
  44818. /**
  44819. * Returns the invocation local index builtin.
  44820. *
  44821. * @return {String} The invocation local index.
  44822. */
  44823. getInvocationLocalIndex() {
  44824. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  44825. }
  44826. /**
  44827. * Returns the subgroup size builtin.
  44828. *
  44829. * @return {String} The subgroup size.
  44830. */
  44831. getSubgroupSize() {
  44832. this.enableSubGroups();
  44833. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44834. }
  44835. /**
  44836. * Returns the invocation subgroup index builtin.
  44837. *
  44838. * @return {String} The invocation subgroup index.
  44839. */
  44840. getInvocationSubgroupIndex() {
  44841. this.enableSubGroups();
  44842. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  44843. }
  44844. /**
  44845. * Returns the subgroup index builtin.
  44846. *
  44847. * @return {String} The subgroup index.
  44848. */
  44849. getSubgroupIndex() {
  44850. this.enableSubGroups();
  44851. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  44852. }
  44853. /**
  44854. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  44855. *
  44856. * @return {null} Null.
  44857. */
  44858. getDrawIndex() {
  44859. return null;
  44860. }
  44861. /**
  44862. * Returns the front facing builtin.
  44863. *
  44864. * @return {String} The front facing builtin.
  44865. */
  44866. getFrontFacing() {
  44867. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  44868. }
  44869. /**
  44870. * Returns the frag coord builtin.
  44871. *
  44872. * @return {String} The frag coord builtin.
  44873. */
  44874. getFragCoord() {
  44875. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  44876. }
  44877. /**
  44878. * Returns the frag depth builtin.
  44879. *
  44880. * @return {String} The frag depth builtin.
  44881. */
  44882. getFragDepth() {
  44883. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  44884. }
  44885. /**
  44886. * Returns the clip distances builtin.
  44887. *
  44888. * @return {String} The clip distances builtin.
  44889. */
  44890. getClipDistance() {
  44891. return 'varyings.hw_clip_distances';
  44892. }
  44893. /**
  44894. * Whether to flip texture data along its vertical axis or not.
  44895. *
  44896. * @return {Boolean} Returns always `false` in context of WGSL.
  44897. */
  44898. isFlipY() {
  44899. return false;
  44900. }
  44901. /**
  44902. * Enables the given directive for the given shader stage.
  44903. *
  44904. * @param {String} name - The directive name.
  44905. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  44906. */
  44907. enableDirective( name, shaderStage = this.shaderStage ) {
  44908. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  44909. stage.add( name );
  44910. }
  44911. /**
  44912. * Returns the directives of the given shader stage as a WGSL string.
  44913. *
  44914. * @param {String} shaderStage - The shader stage.
  44915. * @return {String} A WGSL snippet that enables the directives of the given stage.
  44916. */
  44917. getDirectives( shaderStage ) {
  44918. const snippets = [];
  44919. const directives = this.directives[ shaderStage ];
  44920. if ( directives !== undefined ) {
  44921. for ( const directive of directives ) {
  44922. snippets.push( `enable ${directive};` );
  44923. }
  44924. }
  44925. return snippets.join( '\n' );
  44926. }
  44927. /**
  44928. * Enables the 'subgroups' directive.
  44929. */
  44930. enableSubGroups() {
  44931. this.enableDirective( 'subgroups' );
  44932. }
  44933. /**
  44934. * Enables the 'subgroups-f16' directive.
  44935. */
  44936. enableSubgroupsF16() {
  44937. this.enableDirective( 'subgroups-f16' );
  44938. }
  44939. /**
  44940. * Enables the 'clip_distances' directive.
  44941. */
  44942. enableClipDistances() {
  44943. this.enableDirective( 'clip_distances' );
  44944. }
  44945. /**
  44946. * Enables the 'f16' directive.
  44947. */
  44948. enableShaderF16() {
  44949. this.enableDirective( 'f16' );
  44950. }
  44951. /**
  44952. * Enables the 'dual_source_blending' directive.
  44953. */
  44954. enableDualSourceBlending() {
  44955. this.enableDirective( 'dual_source_blending' );
  44956. }
  44957. /**
  44958. * Enables hardware clipping.
  44959. *
  44960. * @param {String} planeCount - The clipping plane count.
  44961. */
  44962. enableHardwareClipping( planeCount ) {
  44963. this.enableClipDistances();
  44964. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  44965. }
  44966. /**
  44967. * Returns the builtins of the given shader stage as a WGSL string.
  44968. *
  44969. * @param {String} shaderStage - The shader stage.
  44970. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  44971. */
  44972. getBuiltins( shaderStage ) {
  44973. const snippets = [];
  44974. const builtins = this.builtins[ shaderStage ];
  44975. if ( builtins !== undefined ) {
  44976. for ( const { name, property, type } of builtins.values() ) {
  44977. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  44978. }
  44979. }
  44980. return snippets.join( ',\n\t' );
  44981. }
  44982. /**
  44983. * This method should be used when a new scoped buffer is used in context of
  44984. * compute shaders. It adds the array to the internal data structure which is
  44985. * later used to generate the respective WGSL.
  44986. *
  44987. * @param {String} name - The array name.
  44988. * @param {String} scope - The scope.
  44989. * @param {String} bufferType - The buffer type.
  44990. * @param {String} bufferCount - The buffer count.
  44991. * @return {String} The array name.
  44992. */
  44993. getScopedArray( name, scope, bufferType, bufferCount ) {
  44994. if ( this.scopedArrays.has( name ) === false ) {
  44995. this.scopedArrays.set( name, {
  44996. name,
  44997. scope,
  44998. bufferType,
  44999. bufferCount
  45000. } );
  45001. }
  45002. return name;
  45003. }
  45004. /**
  45005. * Returns the scoped arrays of the given shader stage as a WGSL string.
  45006. *
  45007. * @param {String} shaderStage - The shader stage.
  45008. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  45009. * Returns `undefined` when used in the vertex or fragment stage.
  45010. */
  45011. getScopedArrays( shaderStage ) {
  45012. if ( shaderStage !== 'compute' ) {
  45013. return;
  45014. }
  45015. const snippets = [];
  45016. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  45017. const type = this.getType( bufferType );
  45018. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  45019. }
  45020. return snippets.join( '\n' );
  45021. }
  45022. /**
  45023. * Returns the shader attributes of the given shader stage as a WGSL string.
  45024. *
  45025. * @param {String} shaderStage - The shader stage.
  45026. * @return {String} The WGSL snippet that defines the shader attributes.
  45027. */
  45028. getAttributes( shaderStage ) {
  45029. const snippets = [];
  45030. if ( shaderStage === 'compute' ) {
  45031. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  45032. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  45033. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  45034. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  45035. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  45036. this.enableDirective( 'subgroups', shaderStage );
  45037. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45038. }
  45039. }
  45040. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45041. const builtins = this.getBuiltins( 'attribute' );
  45042. if ( builtins ) snippets.push( builtins );
  45043. const attributes = this.getAttributesArray();
  45044. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  45045. const attribute = attributes[ index ];
  45046. const name = attribute.name;
  45047. const type = this.getType( attribute.type );
  45048. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  45049. }
  45050. }
  45051. return snippets.join( ',\n\t' );
  45052. }
  45053. /**
  45054. * Returns the members of the given struct type node as a WGSL string.
  45055. *
  45056. * @param {StructTypeNode} struct - The struct type node.
  45057. * @return {String} The WGSL snippet that defines the struct members.
  45058. */
  45059. getStructMembers( struct ) {
  45060. const snippets = [];
  45061. const members = struct.getMemberTypes();
  45062. for ( let i = 0; i < members.length; i ++ ) {
  45063. const member = members[ i ];
  45064. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  45065. }
  45066. const builtins = this.getBuiltins( 'output' );
  45067. if ( builtins ) snippets.push( '\t' + builtins );
  45068. return snippets.join( ',\n' );
  45069. }
  45070. /**
  45071. * Returns the structs of the given shader stage as a WGSL string.
  45072. *
  45073. * @param {String} shaderStage - The shader stage.
  45074. * @return {String} The WGSL snippet that defines the structs.
  45075. */
  45076. getStructs( shaderStage ) {
  45077. const snippets = [];
  45078. const structs = this.structs[ shaderStage ];
  45079. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  45080. const struct = structs[ index ];
  45081. const name = struct.name;
  45082. let snippet = `\struct ${ name } {\n`;
  45083. snippet += this.getStructMembers( struct );
  45084. snippet += '\n}';
  45085. snippets.push( snippet );
  45086. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  45087. }
  45088. return snippets.join( '\n\n' );
  45089. }
  45090. /**
  45091. * Returns a WGSL string representing a variable.
  45092. *
  45093. * @param {String} type - The variable's type.
  45094. * @param {String} name - The variable's name.
  45095. * @param {Number?} [count=null] - The array length.
  45096. * @return {String} The WGSL snippet that defines a variable.
  45097. */
  45098. getVar( type, name, count = null ) {
  45099. let snippet = `var ${ name } : `;
  45100. if ( count !== null ) {
  45101. snippet += this.generateArrayDeclaration( type, count );
  45102. } else {
  45103. snippet += this.getType( type );
  45104. }
  45105. return snippet;
  45106. }
  45107. /**
  45108. * Returns the variables of the given shader stage as a WGSL string.
  45109. *
  45110. * @param {String} shaderStage - The shader stage.
  45111. * @return {String} The WGSL snippet that defines the variables.
  45112. */
  45113. getVars( shaderStage ) {
  45114. const snippets = [];
  45115. const vars = this.vars[ shaderStage ];
  45116. if ( vars !== undefined ) {
  45117. for ( const variable of vars ) {
  45118. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  45119. }
  45120. }
  45121. return `\n${ snippets.join( '\n' ) }\n`;
  45122. }
  45123. /**
  45124. * Returns the varyings of the given shader stage as a WGSL string.
  45125. *
  45126. * @param {String} shaderStage - The shader stage.
  45127. * @return {String} The WGSL snippet that defines the varyings.
  45128. */
  45129. getVaryings( shaderStage ) {
  45130. const snippets = [];
  45131. if ( shaderStage === 'vertex' ) {
  45132. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  45133. }
  45134. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  45135. const varyings = this.varyings;
  45136. const vars = this.vars[ shaderStage ];
  45137. for ( let index = 0; index < varyings.length; index ++ ) {
  45138. const varying = varyings[ index ];
  45139. if ( varying.needsInterpolation ) {
  45140. let attributesSnippet = `@location( ${index} )`;
  45141. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  45142. attributesSnippet += ' @interpolate( flat )';
  45143. }
  45144. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  45145. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  45146. vars.push( varying );
  45147. }
  45148. }
  45149. }
  45150. const builtins = this.getBuiltins( shaderStage );
  45151. if ( builtins ) snippets.push( builtins );
  45152. const code = snippets.join( ',\n\t' );
  45153. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  45154. }
  45155. /**
  45156. * Returns the uniforms of the given shader stage as a WGSL string.
  45157. *
  45158. * @param {String} shaderStage - The shader stage.
  45159. * @return {String} The WGSL snippet that defines the uniforms.
  45160. */
  45161. getUniforms( shaderStage ) {
  45162. const uniforms = this.uniforms[ shaderStage ];
  45163. const bindingSnippets = [];
  45164. const bufferSnippets = [];
  45165. const structSnippets = [];
  45166. const uniformGroups = {};
  45167. for ( const uniform of uniforms ) {
  45168. const groupName = uniform.groupNode.name;
  45169. const uniformIndexes = this.bindingsIndexes[ groupName ];
  45170. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  45171. const texture = uniform.node.value;
  45172. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  45173. if ( this.isSampleCompare( texture ) ) {
  45174. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  45175. } else {
  45176. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  45177. }
  45178. }
  45179. let textureType;
  45180. let multisampled = '';
  45181. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45182. if ( primarySamples > 1 ) {
  45183. multisampled = '_multisampled';
  45184. }
  45185. if ( texture.isCubeTexture === true ) {
  45186. textureType = 'texture_cube<f32>';
  45187. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45188. textureType = 'texture_2d_array<f32>';
  45189. } else if ( texture.isDepthTexture === true ) {
  45190. textureType = `texture_depth${multisampled}_2d`;
  45191. } else if ( texture.isVideoTexture === true ) {
  45192. textureType = 'texture_external';
  45193. } else if ( texture.isData3DTexture === true ) {
  45194. textureType = 'texture_3d<f32>';
  45195. } else if ( uniform.node.isStorageTextureNode === true ) {
  45196. const format = getFormat( texture );
  45197. const access = this.getStorageAccess( uniform.node, shaderStage );
  45198. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  45199. } else {
  45200. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  45201. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  45202. }
  45203. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  45204. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  45205. const bufferNode = uniform.node;
  45206. const bufferType = this.getType( bufferNode.bufferType );
  45207. const bufferCount = bufferNode.bufferCount;
  45208. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  45209. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  45210. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  45211. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  45212. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  45213. } else {
  45214. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  45215. const groupName = uniform.groupNode.name;
  45216. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  45217. index: uniformIndexes.binding ++,
  45218. id: uniformIndexes.group,
  45219. snippets: []
  45220. } );
  45221. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  45222. }
  45223. }
  45224. for ( const name in uniformGroups ) {
  45225. const group = uniformGroups[ name ];
  45226. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  45227. }
  45228. let code = bindingSnippets.join( '\n' );
  45229. code += bufferSnippets.join( '\n' );
  45230. code += structSnippets.join( '\n' );
  45231. return code;
  45232. }
  45233. /**
  45234. * Controls the code build of the shader stages.
  45235. */
  45236. buildCode() {
  45237. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45238. this.sortBindingGroups();
  45239. for ( const shaderStage in shadersData ) {
  45240. const stageData = shadersData[ shaderStage ];
  45241. stageData.uniforms = this.getUniforms( shaderStage );
  45242. stageData.attributes = this.getAttributes( shaderStage );
  45243. stageData.varyings = this.getVaryings( shaderStage );
  45244. stageData.structs = this.getStructs( shaderStage );
  45245. stageData.vars = this.getVars( shaderStage );
  45246. stageData.codes = this.getCodes( shaderStage );
  45247. stageData.directives = this.getDirectives( shaderStage );
  45248. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  45249. //
  45250. let flow = '// code\n\n';
  45251. flow += this.flowCode[ shaderStage ];
  45252. const flowNodes = this.flowNodes[ shaderStage ];
  45253. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45254. const outputNode = mainNode.outputNode;
  45255. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  45256. for ( const node of flowNodes ) {
  45257. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45258. const slotName = node.name;
  45259. if ( slotName ) {
  45260. if ( flow.length > 0 ) flow += '\n';
  45261. flow += `\t// flow -> ${ slotName }\n`;
  45262. }
  45263. flow += `${ flowSlotData.code }\n\t`;
  45264. if ( node === mainNode && shaderStage !== 'compute' ) {
  45265. flow += '// result\n\n\t';
  45266. if ( shaderStage === 'vertex' ) {
  45267. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  45268. } else if ( shaderStage === 'fragment' ) {
  45269. if ( isOutputStruct ) {
  45270. stageData.returnType = outputNode.nodeType;
  45271. flow += `return ${ flowSlotData.result };`;
  45272. } else {
  45273. let structSnippet = '\t@location(0) color: vec4<f32>';
  45274. const builtins = this.getBuiltins( 'output' );
  45275. if ( builtins ) structSnippet += ',\n\t' + builtins;
  45276. stageData.returnType = 'OutputStruct';
  45277. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  45278. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  45279. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  45280. }
  45281. }
  45282. }
  45283. }
  45284. stageData.flow = flow;
  45285. }
  45286. if ( this.material !== null ) {
  45287. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  45288. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  45289. } else {
  45290. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  45291. }
  45292. }
  45293. /**
  45294. * Returns the native shader method name for a given generic name.
  45295. *
  45296. * @param {String} method - The method name to resolve.
  45297. * @param {String} [output=null] - An optional output.
  45298. * @return {String} The resolved WGSL method name.
  45299. */
  45300. getMethod( method, output = null ) {
  45301. let wgslMethod;
  45302. if ( output !== null ) {
  45303. wgslMethod = this._getWGSLMethod( method + '_' + output );
  45304. }
  45305. if ( wgslMethod === undefined ) {
  45306. wgslMethod = this._getWGSLMethod( method );
  45307. }
  45308. return wgslMethod || method;
  45309. }
  45310. /**
  45311. * Returns the WGSL type of the given node data type.
  45312. *
  45313. * @param {String} type - The node data type.
  45314. * @return {String} The WGSL type.
  45315. */
  45316. getType( type ) {
  45317. return wgslTypeLib[ type ] || type;
  45318. }
  45319. /**
  45320. * Whether the requested feature is available or not.
  45321. *
  45322. * @param {String} name - The requested feature.
  45323. * @return {Boolean} Whether the requested feature is supported or not.
  45324. */
  45325. isAvailable( name ) {
  45326. let result = supports[ name ];
  45327. if ( result === undefined ) {
  45328. if ( name === 'float32Filterable' ) {
  45329. result = this.renderer.hasFeature( 'float32-filterable' );
  45330. } else if ( name === 'clipDistance' ) {
  45331. result = this.renderer.hasFeature( 'clip-distances' );
  45332. }
  45333. supports[ name ] = result;
  45334. }
  45335. return result;
  45336. }
  45337. /**
  45338. * Returns the native shader method name for a given generic name.
  45339. *
  45340. * @private
  45341. * @param {String} method - The method name to resolve.
  45342. * @return {String} The resolved WGSL method name.
  45343. */
  45344. _getWGSLMethod( method ) {
  45345. if ( wgslPolyfill[ method ] !== undefined ) {
  45346. this._include( method );
  45347. }
  45348. return wgslMethods[ method ];
  45349. }
  45350. /**
  45351. * Includes the given method name into the current
  45352. * function node.
  45353. *
  45354. * @private
  45355. * @param {String} name - The method name to include.
  45356. * @return {CodeNode} The respective code node.
  45357. */
  45358. _include( name ) {
  45359. const codeNode = wgslPolyfill[ name ];
  45360. codeNode.build( this );
  45361. if ( this.currentFunctionNode !== null ) {
  45362. this.currentFunctionNode.includes.push( codeNode );
  45363. }
  45364. return codeNode;
  45365. }
  45366. /**
  45367. * Returns a WGSL vertex shader based on the given shader data.
  45368. *
  45369. * @private
  45370. * @param {Object} shaderData - The shader data.
  45371. * @return {String} The vertex shader.
  45372. */
  45373. _getWGSLVertexCode( shaderData ) {
  45374. return `${ this.getSignature() }
  45375. // directives
  45376. ${shaderData.directives}
  45377. // uniforms
  45378. ${shaderData.uniforms}
  45379. // varyings
  45380. ${shaderData.varyings}
  45381. var<private> varyings : VaryingsStruct;
  45382. // codes
  45383. ${shaderData.codes}
  45384. @vertex
  45385. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  45386. // vars
  45387. ${shaderData.vars}
  45388. // flow
  45389. ${shaderData.flow}
  45390. return varyings;
  45391. }
  45392. `;
  45393. }
  45394. /**
  45395. * Returns a WGSL fragment shader based on the given shader data.
  45396. *
  45397. * @private
  45398. * @param {Object} shaderData - The shader data.
  45399. * @return {String} The vertex shader.
  45400. */
  45401. _getWGSLFragmentCode( shaderData ) {
  45402. return `${ this.getSignature() }
  45403. // global
  45404. ${ diagnostics }
  45405. // uniforms
  45406. ${shaderData.uniforms}
  45407. // structs
  45408. ${shaderData.structs}
  45409. // codes
  45410. ${shaderData.codes}
  45411. @fragment
  45412. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  45413. // vars
  45414. ${shaderData.vars}
  45415. // flow
  45416. ${shaderData.flow}
  45417. }
  45418. `;
  45419. }
  45420. /**
  45421. * Returns a WGSL compute shader based on the given shader data.
  45422. *
  45423. * @private
  45424. * @param {Object} shaderData - The shader data.
  45425. * @param {String} workgroupSize - The workgroup size.
  45426. * @return {String} The vertex shader.
  45427. */
  45428. _getWGSLComputeCode( shaderData, workgroupSize ) {
  45429. return `${ this.getSignature() }
  45430. // directives
  45431. ${shaderData.directives}
  45432. // system
  45433. var<private> instanceIndex : u32;
  45434. // locals
  45435. ${shaderData.scopedArrays}
  45436. // uniforms
  45437. ${shaderData.uniforms}
  45438. // codes
  45439. ${shaderData.codes}
  45440. @compute @workgroup_size( ${workgroupSize} )
  45441. fn main( ${shaderData.attributes} ) {
  45442. // system
  45443. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  45444. // vars
  45445. ${shaderData.vars}
  45446. // flow
  45447. ${shaderData.flow}
  45448. }
  45449. `;
  45450. }
  45451. /**
  45452. * Returns a WGSL struct based on the given name and variables.
  45453. *
  45454. * @private
  45455. * @param {String} name - The struct name.
  45456. * @param {String} vars - The struct variables.
  45457. * @return {String} The WGSL snippet representing a struct.
  45458. */
  45459. _getWGSLStruct( name, vars ) {
  45460. return `
  45461. struct ${name} {
  45462. ${vars}
  45463. };`;
  45464. }
  45465. /**
  45466. * Returns a WGSL struct binding.
  45467. *
  45468. * @private
  45469. * @param {String} name - The struct name.
  45470. * @param {String} vars - The struct variables.
  45471. * @param {String} access - The access.
  45472. * @param {Number} [binding=0] - The binding index.
  45473. * @param {Number} [group=0] - The group index.
  45474. * @return {String} The WGSL snippet representing a struct binding.
  45475. */
  45476. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  45477. const structName = name + 'Struct';
  45478. const structSnippet = this._getWGSLStruct( structName, vars );
  45479. return `${structSnippet}
  45480. @binding( ${binding} ) @group( ${group} )
  45481. var<${access}> ${name} : ${structName};`;
  45482. }
  45483. }
  45484. /**
  45485. * A WebGPU backend utility module with common helpers.
  45486. *
  45487. * @private
  45488. */
  45489. class WebGPUUtils {
  45490. /**
  45491. * Constructs a new utility object.
  45492. *
  45493. * @param {WebGPUBackend} backend - The WebGPU backend.
  45494. */
  45495. constructor( backend ) {
  45496. /**
  45497. * A reference to the WebGPU backend.
  45498. *
  45499. * @type {WebGPUBackend}
  45500. */
  45501. this.backend = backend;
  45502. }
  45503. /**
  45504. * Returns the depth/stencil GPU format for the given render context.
  45505. *
  45506. * @param {RenderContext} renderContext - The render context.
  45507. * @return {String} The depth/stencil GPU texture format.
  45508. */
  45509. getCurrentDepthStencilFormat( renderContext ) {
  45510. let format;
  45511. if ( renderContext.depthTexture !== null ) {
  45512. format = this.getTextureFormatGPU( renderContext.depthTexture );
  45513. } else if ( renderContext.depth && renderContext.stencil ) {
  45514. format = GPUTextureFormat.Depth24PlusStencil8;
  45515. } else if ( renderContext.depth ) {
  45516. format = GPUTextureFormat.Depth24Plus;
  45517. }
  45518. return format;
  45519. }
  45520. /**
  45521. * Returns the GPU format for the given texture.
  45522. *
  45523. * @param {Texture} texture - The texture.
  45524. * @return {String} The GPU texture format.
  45525. */
  45526. getTextureFormatGPU( texture ) {
  45527. return this.backend.get( texture ).format;
  45528. }
  45529. /**
  45530. * Returns an object that defines the multi-sampling state of the given texture.
  45531. *
  45532. * @param {Texture} texture - The texture.
  45533. * @return {Object} The multi-sampling state.
  45534. */
  45535. getTextureSampleData( texture ) {
  45536. let samples;
  45537. if ( texture.isFramebufferTexture ) {
  45538. samples = 1;
  45539. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  45540. const renderer = this.backend.renderer;
  45541. const renderTarget = renderer.getRenderTarget();
  45542. samples = renderTarget ? renderTarget.samples : renderer.samples;
  45543. } else if ( texture.renderTarget ) {
  45544. samples = texture.renderTarget.samples;
  45545. }
  45546. samples = samples || 1;
  45547. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  45548. const primarySamples = isMSAA ? 1 : samples;
  45549. return { samples, primarySamples, isMSAA };
  45550. }
  45551. /**
  45552. * Returns the default color attachment's GPU format of the current render context.
  45553. *
  45554. * @param {RenderContext} renderContext - The render context.
  45555. * @return {String} The GPU texture format of the default color attachment.
  45556. */
  45557. getCurrentColorFormat( renderContext ) {
  45558. let format;
  45559. if ( renderContext.textures !== null ) {
  45560. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  45561. } else {
  45562. format = this.getPreferredCanvasFormat(); // default context format
  45563. }
  45564. return format;
  45565. }
  45566. /**
  45567. * Returns the output color space of the current render context.
  45568. *
  45569. * @param {RenderContext} renderContext - The render context.
  45570. * @return {String} The output color space.
  45571. */
  45572. getCurrentColorSpace( renderContext ) {
  45573. if ( renderContext.textures !== null ) {
  45574. return renderContext.textures[ 0 ].colorSpace;
  45575. }
  45576. return this.backend.renderer.outputColorSpace;
  45577. }
  45578. /**
  45579. * Returns GPU primitive topology for the given object and material.
  45580. *
  45581. * @param {Object3D} object - The 3D object.
  45582. * @param {Material} material - The material.
  45583. * @return {String} The GPU primitive topology.
  45584. */
  45585. getPrimitiveTopology( object, material ) {
  45586. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  45587. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  45588. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  45589. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  45590. }
  45591. /**
  45592. * Returns a modified sample count from the given sample count value.
  45593. *
  45594. * That is required since WebGPU does not support arbitrary sample counts.
  45595. *
  45596. * @param {Number} sampleCount - The input sample count.
  45597. * @return {Number} The (potentially updated) output sample count.
  45598. */
  45599. getSampleCount( sampleCount ) {
  45600. let count = 1;
  45601. if ( sampleCount > 1 ) {
  45602. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  45603. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  45604. if ( count === 2 ) {
  45605. count = 4;
  45606. }
  45607. }
  45608. return count;
  45609. }
  45610. /**
  45611. * Returns the sample count of the given render context.
  45612. *
  45613. * @param {RenderContext} renderContext - The render context.
  45614. * @return {Number} The sample count.
  45615. */
  45616. getSampleCountRenderContext( renderContext ) {
  45617. if ( renderContext.textures !== null ) {
  45618. return this.getSampleCount( renderContext.sampleCount );
  45619. }
  45620. return this.getSampleCount( this.backend.renderer.samples );
  45621. }
  45622. /**
  45623. * Returns the preferred canvas format.
  45624. *
  45625. * There is a separate method for this so it's possible to
  45626. * honor edge cases for specific devices.
  45627. *
  45628. * @return {String} The GPU texture format of the canvas.
  45629. */
  45630. getPreferredCanvasFormat() {
  45631. const outputType = this.backend.parameters.outputType;
  45632. if ( outputType === undefined ) {
  45633. return navigator.gpu.getPreferredCanvasFormat();
  45634. } else if ( outputType === UnsignedByteType ) {
  45635. return GPUTextureFormat.BGRA8Unorm;
  45636. } else if ( outputType === HalfFloatType ) {
  45637. return GPUTextureFormat.RGBA16Float;
  45638. } else {
  45639. throw new Error( 'Unsupported outputType' );
  45640. }
  45641. }
  45642. }
  45643. const typedArraysToVertexFormatPrefix = new Map( [
  45644. [ Int8Array, [ 'sint8', 'snorm8' ]],
  45645. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  45646. [ Int16Array, [ 'sint16', 'snorm16' ]],
  45647. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  45648. [ Int32Array, [ 'sint32', 'snorm32' ]],
  45649. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  45650. [ Float32Array, [ 'float32', ]],
  45651. ] );
  45652. const typedAttributeToVertexFormatPrefix = new Map( [
  45653. [ Float16BufferAttribute, [ 'float16', ]],
  45654. ] );
  45655. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  45656. [ Int32Array, 'sint32' ],
  45657. [ Int16Array, 'sint32' ], // patch for INT16
  45658. [ Uint32Array, 'uint32' ],
  45659. [ Uint16Array, 'uint32' ], // patch for UINT16
  45660. [ Float32Array, 'float32' ]
  45661. ] );
  45662. /**
  45663. * A WebGPU backend utility module for managing shader attributes.
  45664. *
  45665. * @private
  45666. */
  45667. class WebGPUAttributeUtils {
  45668. /**
  45669. * Constructs a new utility object.
  45670. *
  45671. * @param {WebGPUBackend} backend - The WebGPU backend.
  45672. */
  45673. constructor( backend ) {
  45674. /**
  45675. * A reference to the WebGPU backend.
  45676. *
  45677. * @type {WebGPUBackend}
  45678. */
  45679. this.backend = backend;
  45680. }
  45681. /**
  45682. * Creates the GPU buffer for the given buffer attribute.
  45683. *
  45684. * @param {BufferAttribute} attribute - The buffer attribute.
  45685. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  45686. */
  45687. createAttribute( attribute, usage ) {
  45688. const bufferAttribute = this._getBufferAttribute( attribute );
  45689. const backend = this.backend;
  45690. const bufferData = backend.get( bufferAttribute );
  45691. let buffer = bufferData.buffer;
  45692. if ( buffer === undefined ) {
  45693. const device = backend.device;
  45694. let array = bufferAttribute.array;
  45695. // patch for INT16 and UINT16
  45696. if ( attribute.normalized === false ) {
  45697. if ( array.constructor === Int16Array ) {
  45698. array = new Int32Array( array );
  45699. } else if ( array.constructor === Uint16Array ) {
  45700. array = new Uint32Array( array );
  45701. if ( usage & GPUBufferUsage.INDEX ) {
  45702. for ( let i = 0; i < array.length; i ++ ) {
  45703. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  45704. }
  45705. }
  45706. }
  45707. }
  45708. bufferAttribute.array = array;
  45709. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  45710. array = new array.constructor( bufferAttribute.count * 4 );
  45711. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  45712. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  45713. }
  45714. // Update BufferAttribute
  45715. bufferAttribute.itemSize = 4;
  45716. bufferAttribute.array = array;
  45717. }
  45718. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  45719. buffer = device.createBuffer( {
  45720. label: bufferAttribute.name,
  45721. size: size,
  45722. usage: usage,
  45723. mappedAtCreation: true
  45724. } );
  45725. new array.constructor( buffer.getMappedRange() ).set( array );
  45726. buffer.unmap();
  45727. bufferData.buffer = buffer;
  45728. }
  45729. }
  45730. /**
  45731. * Updates the GPU buffer of the given buffer attribute.
  45732. *
  45733. * @param {BufferAttribute} attribute - The buffer attribute.
  45734. */
  45735. updateAttribute( attribute ) {
  45736. const bufferAttribute = this._getBufferAttribute( attribute );
  45737. const backend = this.backend;
  45738. const device = backend.device;
  45739. const buffer = backend.get( bufferAttribute ).buffer;
  45740. const array = bufferAttribute.array;
  45741. const isTypedArray = this._isTypedArray( array );
  45742. const updateRanges = bufferAttribute.updateRanges;
  45743. if ( updateRanges.length === 0 ) {
  45744. // Not using update ranges
  45745. device.queue.writeBuffer(
  45746. buffer,
  45747. 0,
  45748. array,
  45749. 0
  45750. );
  45751. } else {
  45752. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  45753. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45754. const range = updateRanges[ i ];
  45755. const dataOffset = range.start * byteOffsetFactor;
  45756. const size = range.count * byteOffsetFactor;
  45757. device.queue.writeBuffer(
  45758. buffer,
  45759. 0,
  45760. array,
  45761. dataOffset,
  45762. size
  45763. );
  45764. }
  45765. bufferAttribute.clearUpdateRanges();
  45766. }
  45767. }
  45768. /**
  45769. * This method creates the vertex buffer layout data which are
  45770. * require when creating a render pipeline for the given render object.
  45771. *
  45772. * @param {RenderObject} renderObject - The render object.
  45773. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  45774. */
  45775. createShaderVertexBuffers( renderObject ) {
  45776. const attributes = renderObject.getAttributes();
  45777. const vertexBuffers = new Map();
  45778. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  45779. const geometryAttribute = attributes[ slot ];
  45780. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  45781. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  45782. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  45783. if ( vertexBufferLayout === undefined ) {
  45784. let arrayStride, stepMode;
  45785. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  45786. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  45787. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45788. } else {
  45789. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  45790. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45791. }
  45792. // patch for INT16 and UINT16
  45793. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  45794. arrayStride = 4;
  45795. }
  45796. vertexBufferLayout = {
  45797. arrayStride,
  45798. attributes: [],
  45799. stepMode
  45800. };
  45801. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  45802. }
  45803. const format = this._getVertexFormat( geometryAttribute );
  45804. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  45805. vertexBufferLayout.attributes.push( {
  45806. shaderLocation: slot,
  45807. offset,
  45808. format
  45809. } );
  45810. }
  45811. return Array.from( vertexBuffers.values() );
  45812. }
  45813. /**
  45814. * Destroys the GPU buffer of the given buffer attribute.
  45815. *
  45816. * @param {BufferAttribute} attribute - The buffer attribute.
  45817. */
  45818. destroyAttribute( attribute ) {
  45819. const backend = this.backend;
  45820. const data = backend.get( this._getBufferAttribute( attribute ) );
  45821. data.buffer.destroy();
  45822. backend.delete( attribute );
  45823. }
  45824. /**
  45825. * This method performs a readback operation by moving buffer data from
  45826. * a storage buffer attribute from the GPU to the CPU.
  45827. *
  45828. * @async
  45829. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45830. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45831. */
  45832. async getArrayBufferAsync( attribute ) {
  45833. const backend = this.backend;
  45834. const device = backend.device;
  45835. const data = backend.get( this._getBufferAttribute( attribute ) );
  45836. const bufferGPU = data.buffer;
  45837. const size = bufferGPU.size;
  45838. const readBufferGPU = device.createBuffer( {
  45839. label: `${ attribute.name }_readback`,
  45840. size,
  45841. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45842. } );
  45843. const cmdEncoder = device.createCommandEncoder( {
  45844. label: `readback_encoder_${ attribute.name }`
  45845. } );
  45846. cmdEncoder.copyBufferToBuffer(
  45847. bufferGPU,
  45848. 0,
  45849. readBufferGPU,
  45850. 0,
  45851. size
  45852. );
  45853. const gpuCommands = cmdEncoder.finish();
  45854. device.queue.submit( [ gpuCommands ] );
  45855. await readBufferGPU.mapAsync( GPUMapMode.READ );
  45856. const arrayBuffer = readBufferGPU.getMappedRange();
  45857. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  45858. readBufferGPU.unmap();
  45859. return dstBuffer.buffer;
  45860. }
  45861. /**
  45862. * Returns the vertex format of the given buffer attribute.
  45863. *
  45864. * @private
  45865. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  45866. * @return {String} The vertex format (e.g. 'float32x3').
  45867. */
  45868. _getVertexFormat( geometryAttribute ) {
  45869. const { itemSize, normalized } = geometryAttribute;
  45870. const ArrayType = geometryAttribute.array.constructor;
  45871. const AttributeType = geometryAttribute.constructor;
  45872. let format;
  45873. if ( itemSize === 1 ) {
  45874. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  45875. } else {
  45876. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  45877. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  45878. if ( prefix ) {
  45879. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  45880. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  45881. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  45882. if ( paddedItemSize % 1 ) {
  45883. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  45884. }
  45885. format = `${prefix}x${paddedItemSize}`;
  45886. }
  45887. }
  45888. if ( ! format ) {
  45889. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  45890. }
  45891. return format;
  45892. }
  45893. /**
  45894. * Returns `true` if the given array is a typed array.
  45895. *
  45896. * @private
  45897. * @param {Any} array - The array.
  45898. * @return {Boolean} Whether the given array is a typed array or not.
  45899. */
  45900. _isTypedArray( array ) {
  45901. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  45902. }
  45903. /**
  45904. * Utility method for handling interleaved buffer attributes correctly.
  45905. * To process them, their `InterleavedBuffer` is returned.
  45906. *
  45907. * @private
  45908. * @param {BufferAttribute} attribute - The attribute.
  45909. * @return {BufferAttribute|InterleavedBuffer}
  45910. */
  45911. _getBufferAttribute( attribute ) {
  45912. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  45913. return attribute;
  45914. }
  45915. }
  45916. /**
  45917. * A WebGPU backend utility module for managing bindings.
  45918. *
  45919. * When reading the documentation it's helpful to keep in mind that
  45920. * all class definitions starting with 'GPU*' are modules from the
  45921. * WebGPU API. So for example `BindGroup` is a class from the engine
  45922. * whereas `GPUBindGroup` is a class from WebGPU.
  45923. *
  45924. * @private
  45925. */
  45926. class WebGPUBindingUtils {
  45927. /**
  45928. * Constructs a new utility object.
  45929. *
  45930. * @param {WebGPUBackend} backend - The WebGPU backend.
  45931. */
  45932. constructor( backend ) {
  45933. /**
  45934. * A reference to the WebGPU backend.
  45935. *
  45936. * @type {WebGPUBackend}
  45937. */
  45938. this.backend = backend;
  45939. /**
  45940. * A cache for managing bind group layouts.
  45941. *
  45942. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  45943. */
  45944. this.bindGroupLayoutCache = new WeakMap();
  45945. }
  45946. /**
  45947. * Creates a GPU bind group layout for the given bind group.
  45948. *
  45949. * @param {BindGroup} bindGroup - The bind group.
  45950. * @return {GPUBindGroupLayout} The GPU bind group layout.
  45951. */
  45952. createBindingsLayout( bindGroup ) {
  45953. const backend = this.backend;
  45954. const device = backend.device;
  45955. const entries = [];
  45956. let index = 0;
  45957. for ( const binding of bindGroup.bindings ) {
  45958. const bindingGPU = {
  45959. binding: index ++,
  45960. visibility: binding.visibility
  45961. };
  45962. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  45963. const buffer = {}; // GPUBufferBindingLayout
  45964. if ( binding.isStorageBuffer ) {
  45965. if ( binding.visibility & 4 ) {
  45966. // compute
  45967. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  45968. buffer.type = GPUBufferBindingType.Storage;
  45969. } else {
  45970. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45971. }
  45972. } else {
  45973. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45974. }
  45975. }
  45976. bindingGPU.buffer = buffer;
  45977. } else if ( binding.isSampler ) {
  45978. const sampler = {}; // GPUSamplerBindingLayout
  45979. if ( binding.texture.isDepthTexture ) {
  45980. if ( binding.texture.compareFunction !== null ) {
  45981. sampler.type = 'comparison';
  45982. }
  45983. }
  45984. bindingGPU.sampler = sampler;
  45985. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  45986. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  45987. } else if ( binding.isSampledTexture && binding.store ) {
  45988. const storageTexture = {}; // GPUStorageTextureBindingLayout
  45989. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  45990. const access = binding.access;
  45991. if ( access === NodeAccess.READ_WRITE ) {
  45992. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  45993. } else if ( access === NodeAccess.WRITE_ONLY ) {
  45994. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  45995. } else {
  45996. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  45997. }
  45998. bindingGPU.storageTexture = storageTexture;
  45999. } else if ( binding.isSampledTexture ) {
  46000. const texture = {}; // GPUTextureBindingLayout
  46001. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  46002. if ( primarySamples > 1 ) {
  46003. texture.multisampled = true;
  46004. if ( ! binding.texture.isDepthTexture ) {
  46005. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46006. }
  46007. }
  46008. if ( binding.texture.isDepthTexture ) {
  46009. texture.sampleType = GPUTextureSampleType.Depth;
  46010. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  46011. const type = binding.texture.type;
  46012. if ( type === IntType ) {
  46013. texture.sampleType = GPUTextureSampleType.SInt;
  46014. } else if ( type === UnsignedIntType ) {
  46015. texture.sampleType = GPUTextureSampleType.UInt;
  46016. } else if ( type === FloatType ) {
  46017. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  46018. texture.sampleType = GPUTextureSampleType.Float;
  46019. } else {
  46020. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46021. }
  46022. }
  46023. }
  46024. if ( binding.isSampledCubeTexture ) {
  46025. texture.viewDimension = GPUTextureViewDimension.Cube;
  46026. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46027. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  46028. } else if ( binding.isSampledTexture3D ) {
  46029. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  46030. }
  46031. bindingGPU.texture = texture;
  46032. } else {
  46033. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  46034. }
  46035. entries.push( bindingGPU );
  46036. }
  46037. return device.createBindGroupLayout( { entries } );
  46038. }
  46039. /**
  46040. * Creates bindings from the given bind group definition.
  46041. *
  46042. * @param {BindGroup} bindGroup - The bind group.
  46043. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46044. * @param {Number} cacheIndex - The cache index.
  46045. * @param {Number} version - The version.
  46046. */
  46047. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  46048. const { backend, bindGroupLayoutCache } = this;
  46049. const bindingsData = backend.get( bindGroup );
  46050. // setup (static) binding layout and (dynamic) binding group
  46051. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  46052. if ( bindLayoutGPU === undefined ) {
  46053. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  46054. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  46055. }
  46056. let bindGroupGPU;
  46057. if ( cacheIndex > 0 ) {
  46058. if ( bindingsData.groups === undefined ) {
  46059. bindingsData.groups = [];
  46060. bindingsData.versions = [];
  46061. }
  46062. if ( bindingsData.versions[ cacheIndex ] === version ) {
  46063. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  46064. }
  46065. }
  46066. if ( bindGroupGPU === undefined ) {
  46067. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  46068. if ( cacheIndex > 0 ) {
  46069. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  46070. bindingsData.versions[ cacheIndex ] = version;
  46071. }
  46072. }
  46073. bindingsData.group = bindGroupGPU;
  46074. bindingsData.layout = bindLayoutGPU;
  46075. }
  46076. /**
  46077. * Updates a buffer binding.
  46078. *
  46079. * @param {Buffer} binding - The buffer binding to update.
  46080. */
  46081. updateBinding( binding ) {
  46082. const backend = this.backend;
  46083. const device = backend.device;
  46084. const buffer = binding.buffer;
  46085. const bufferGPU = backend.get( binding ).buffer;
  46086. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  46087. }
  46088. /**
  46089. * Creates a GPU bind group for the camera index.
  46090. *
  46091. * @param {Uint32Array} data - The index data.
  46092. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  46093. * @return {GPUBindGroup} The GPU bind group.
  46094. */
  46095. createBindGroupIndex( data, layout ) {
  46096. const backend = this.backend;
  46097. const device = backend.device;
  46098. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46099. const index = data[ 0 ];
  46100. const buffer = device.createBuffer( {
  46101. label: 'bindingCameraIndex_' + index,
  46102. size: 16, // uint(4) * 4
  46103. usage: usage
  46104. } );
  46105. device.queue.writeBuffer( buffer, 0, data, 0 );
  46106. const entries = [ { binding: 0, resource: { buffer } } ];
  46107. return device.createBindGroup( {
  46108. label: 'bindGroupCameraIndex_' + index,
  46109. layout,
  46110. entries
  46111. } );
  46112. }
  46113. /**
  46114. * Creates a GPU bind group for the given bind group and GPU layout.
  46115. *
  46116. * @param {BindGroup} bindGroup - The bind group.
  46117. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  46118. * @return {GPUBindGroup} The GPU bind group.
  46119. */
  46120. createBindGroup( bindGroup, layoutGPU ) {
  46121. const backend = this.backend;
  46122. const device = backend.device;
  46123. let bindingPoint = 0;
  46124. const entriesGPU = [];
  46125. for ( const binding of bindGroup.bindings ) {
  46126. if ( binding.isUniformBuffer ) {
  46127. const bindingData = backend.get( binding );
  46128. if ( bindingData.buffer === undefined ) {
  46129. const byteLength = binding.byteLength;
  46130. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46131. const bufferGPU = device.createBuffer( {
  46132. label: 'bindingBuffer_' + binding.name,
  46133. size: byteLength,
  46134. usage: usage
  46135. } );
  46136. bindingData.buffer = bufferGPU;
  46137. }
  46138. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46139. } else if ( binding.isStorageBuffer ) {
  46140. const bindingData = backend.get( binding );
  46141. if ( bindingData.buffer === undefined ) {
  46142. const attribute = binding.attribute;
  46143. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  46144. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  46145. bindingData.buffer = backend.get( attribute ).buffer;
  46146. }
  46147. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46148. } else if ( binding.isSampler ) {
  46149. const textureGPU = backend.get( binding.texture );
  46150. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  46151. } else if ( binding.isSampledTexture ) {
  46152. const textureData = backend.get( binding.texture );
  46153. let resourceGPU;
  46154. if ( textureData.externalTexture !== undefined ) {
  46155. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  46156. } else {
  46157. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  46158. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  46159. resourceGPU = textureData[ propertyName ];
  46160. if ( resourceGPU === undefined ) {
  46161. const aspectGPU = GPUTextureAspect.All;
  46162. let dimensionViewGPU;
  46163. if ( binding.isSampledCubeTexture ) {
  46164. dimensionViewGPU = GPUTextureViewDimension.Cube;
  46165. } else if ( binding.isSampledTexture3D ) {
  46166. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  46167. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46168. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  46169. } else {
  46170. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  46171. }
  46172. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  46173. }
  46174. }
  46175. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  46176. }
  46177. bindingPoint ++;
  46178. }
  46179. return device.createBindGroup( {
  46180. label: 'bindGroup_' + bindGroup.name,
  46181. layout: layoutGPU,
  46182. entries: entriesGPU
  46183. } );
  46184. }
  46185. }
  46186. /**
  46187. * A WebGPU backend utility module for managing pipelines.
  46188. *
  46189. * @private
  46190. */
  46191. class WebGPUPipelineUtils {
  46192. /**
  46193. * Constructs a new utility object.
  46194. *
  46195. * @param {WebGPUBackend} backend - The WebGPU backend.
  46196. */
  46197. constructor( backend ) {
  46198. /**
  46199. * A reference to the WebGPU backend.
  46200. *
  46201. * @type {WebGPUBackend}
  46202. */
  46203. this.backend = backend;
  46204. }
  46205. /**
  46206. * Returns the sample count derived from the given render context.
  46207. *
  46208. * @private
  46209. * @param {RenderContext} renderContext - The render context.
  46210. * @return {Number} The sample count.
  46211. */
  46212. _getSampleCount( renderContext ) {
  46213. return this.backend.utils.getSampleCountRenderContext( renderContext );
  46214. }
  46215. /**
  46216. * Creates a render pipeline for the given render object.
  46217. *
  46218. * @param {RenderObject} renderObject - The render object.
  46219. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46220. */
  46221. createRenderPipeline( renderObject, promises ) {
  46222. const { object, material, geometry, pipeline } = renderObject;
  46223. const { vertexProgram, fragmentProgram } = pipeline;
  46224. const backend = this.backend;
  46225. const device = backend.device;
  46226. const utils = backend.utils;
  46227. const pipelineData = backend.get( pipeline );
  46228. // bind group layouts
  46229. const bindGroupLayouts = [];
  46230. for ( const bindGroup of renderObject.getBindings() ) {
  46231. const bindingsData = backend.get( bindGroup );
  46232. bindGroupLayouts.push( bindingsData.layout );
  46233. }
  46234. // vertex buffers
  46235. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  46236. // blending
  46237. let blending;
  46238. if ( material.transparent === true && material.blending !== NoBlending ) {
  46239. blending = this._getBlending( material );
  46240. }
  46241. // stencil
  46242. let stencilFront = {};
  46243. if ( material.stencilWrite === true ) {
  46244. stencilFront = {
  46245. compare: this._getStencilCompare( material ),
  46246. failOp: this._getStencilOperation( material.stencilFail ),
  46247. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  46248. passOp: this._getStencilOperation( material.stencilZPass )
  46249. };
  46250. }
  46251. const colorWriteMask = this._getColorWriteMask( material );
  46252. const targets = [];
  46253. if ( renderObject.context.textures !== null ) {
  46254. const textures = renderObject.context.textures;
  46255. for ( let i = 0; i < textures.length; i ++ ) {
  46256. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  46257. targets.push( {
  46258. format: colorFormat,
  46259. blend: blending,
  46260. writeMask: colorWriteMask
  46261. } );
  46262. }
  46263. } else {
  46264. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  46265. targets.push( {
  46266. format: colorFormat,
  46267. blend: blending,
  46268. writeMask: colorWriteMask
  46269. } );
  46270. }
  46271. const vertexModule = backend.get( vertexProgram ).module;
  46272. const fragmentModule = backend.get( fragmentProgram ).module;
  46273. const primitiveState = this._getPrimitiveState( object, geometry, material );
  46274. const depthCompare = this._getDepthCompare( material );
  46275. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  46276. const sampleCount = this._getSampleCount( renderObject.context );
  46277. const pipelineDescriptor = {
  46278. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  46279. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  46280. fragment: Object.assign( {}, fragmentModule, { targets } ),
  46281. primitive: primitiveState,
  46282. multisample: {
  46283. count: sampleCount,
  46284. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  46285. },
  46286. layout: device.createPipelineLayout( {
  46287. bindGroupLayouts
  46288. } )
  46289. };
  46290. const depthStencil = {};
  46291. const renderDepth = renderObject.context.depth;
  46292. const renderStencil = renderObject.context.stencil;
  46293. if ( renderDepth === true || renderStencil === true ) {
  46294. if ( renderDepth === true ) {
  46295. depthStencil.format = depthStencilFormat;
  46296. depthStencil.depthWriteEnabled = material.depthWrite;
  46297. depthStencil.depthCompare = depthCompare;
  46298. }
  46299. if ( renderStencil === true ) {
  46300. depthStencil.stencilFront = stencilFront;
  46301. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  46302. depthStencil.stencilReadMask = material.stencilFuncMask;
  46303. depthStencil.stencilWriteMask = material.stencilWriteMask;
  46304. }
  46305. pipelineDescriptor.depthStencil = depthStencil;
  46306. }
  46307. if ( promises === null ) {
  46308. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  46309. } else {
  46310. const p = new Promise( ( resolve /*, reject*/ ) => {
  46311. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  46312. pipelineData.pipeline = pipeline;
  46313. resolve();
  46314. } );
  46315. } );
  46316. promises.push( p );
  46317. }
  46318. }
  46319. /**
  46320. * Creates GPU render bundle encoder for the given render context.
  46321. *
  46322. * @param {RenderContext} renderContext - The render context.
  46323. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  46324. */
  46325. createBundleEncoder( renderContext ) {
  46326. const backend = this.backend;
  46327. const { utils, device } = backend;
  46328. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  46329. const colorFormat = utils.getCurrentColorFormat( renderContext );
  46330. const sampleCount = this._getSampleCount( renderContext );
  46331. const descriptor = {
  46332. label: 'renderBundleEncoder',
  46333. colorFormats: [ colorFormat ],
  46334. depthStencilFormat,
  46335. sampleCount
  46336. };
  46337. return device.createRenderBundleEncoder( descriptor );
  46338. }
  46339. /**
  46340. * Creates a compute pipeline for the given compute node.
  46341. *
  46342. * @param {ComputePipeline} pipeline - The compute pipeline.
  46343. * @param {Array<BindGroup>} bindings - The bindings.
  46344. */
  46345. createComputePipeline( pipeline, bindings ) {
  46346. const backend = this.backend;
  46347. const device = backend.device;
  46348. const computeProgram = backend.get( pipeline.computeProgram ).module;
  46349. const pipelineGPU = backend.get( pipeline );
  46350. // bind group layouts
  46351. const bindGroupLayouts = [];
  46352. for ( const bindingsGroup of bindings ) {
  46353. const bindingsData = backend.get( bindingsGroup );
  46354. bindGroupLayouts.push( bindingsData.layout );
  46355. }
  46356. pipelineGPU.pipeline = device.createComputePipeline( {
  46357. compute: computeProgram,
  46358. layout: device.createPipelineLayout( {
  46359. bindGroupLayouts
  46360. } )
  46361. } );
  46362. }
  46363. /**
  46364. * Returns the blending state as a descriptor object required
  46365. * for the pipeline creation.
  46366. *
  46367. * @private
  46368. * @param {Material} material - The material.
  46369. * @return {Object} The blending state.
  46370. */
  46371. _getBlending( material ) {
  46372. let color, alpha;
  46373. const blending = material.blending;
  46374. const blendSrc = material.blendSrc;
  46375. const blendDst = material.blendDst;
  46376. const blendEquation = material.blendEquation;
  46377. if ( blending === CustomBlending ) {
  46378. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  46379. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  46380. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  46381. color = {
  46382. srcFactor: this._getBlendFactor( blendSrc ),
  46383. dstFactor: this._getBlendFactor( blendDst ),
  46384. operation: this._getBlendOperation( blendEquation )
  46385. };
  46386. alpha = {
  46387. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  46388. dstFactor: this._getBlendFactor( blendDstAlpha ),
  46389. operation: this._getBlendOperation( blendEquationAlpha )
  46390. };
  46391. } else {
  46392. const premultipliedAlpha = material.premultipliedAlpha;
  46393. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  46394. color = {
  46395. srcFactor: srcRGB,
  46396. dstFactor: dstRGB,
  46397. operation: GPUBlendOperation.Add
  46398. };
  46399. alpha = {
  46400. srcFactor: srcAlpha,
  46401. dstFactor: dstAlpha,
  46402. operation: GPUBlendOperation.Add
  46403. };
  46404. };
  46405. if ( premultipliedAlpha ) {
  46406. switch ( blending ) {
  46407. case NormalBlending:
  46408. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  46409. break;
  46410. case AdditiveBlending:
  46411. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  46412. break;
  46413. case SubtractiveBlending:
  46414. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  46415. break;
  46416. case MultiplyBlending:
  46417. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  46418. break;
  46419. }
  46420. } else {
  46421. switch ( blending ) {
  46422. case NormalBlending:
  46423. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  46424. break;
  46425. case AdditiveBlending:
  46426. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  46427. break;
  46428. case SubtractiveBlending:
  46429. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  46430. break;
  46431. case MultiplyBlending:
  46432. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  46433. break;
  46434. }
  46435. }
  46436. }
  46437. if ( color !== undefined && alpha !== undefined ) {
  46438. return { color, alpha };
  46439. } else {
  46440. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  46441. }
  46442. }
  46443. /**
  46444. * Returns the GPU blend factor which is required for the pipeline creation.
  46445. *
  46446. * @private
  46447. * @param {Number} blend - The blend factor as a three.js constant.
  46448. * @return {String} The GPU blend factor.
  46449. */
  46450. _getBlendFactor( blend ) {
  46451. let blendFactor;
  46452. switch ( blend ) {
  46453. case ZeroFactor:
  46454. blendFactor = GPUBlendFactor.Zero;
  46455. break;
  46456. case OneFactor:
  46457. blendFactor = GPUBlendFactor.One;
  46458. break;
  46459. case SrcColorFactor:
  46460. blendFactor = GPUBlendFactor.Src;
  46461. break;
  46462. case OneMinusSrcColorFactor:
  46463. blendFactor = GPUBlendFactor.OneMinusSrc;
  46464. break;
  46465. case SrcAlphaFactor:
  46466. blendFactor = GPUBlendFactor.SrcAlpha;
  46467. break;
  46468. case OneMinusSrcAlphaFactor:
  46469. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  46470. break;
  46471. case DstColorFactor:
  46472. blendFactor = GPUBlendFactor.Dst;
  46473. break;
  46474. case OneMinusDstColorFactor:
  46475. blendFactor = GPUBlendFactor.OneMinusDstColor;
  46476. break;
  46477. case DstAlphaFactor:
  46478. blendFactor = GPUBlendFactor.DstAlpha;
  46479. break;
  46480. case OneMinusDstAlphaFactor:
  46481. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  46482. break;
  46483. case SrcAlphaSaturateFactor:
  46484. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  46485. break;
  46486. case BlendColorFactor:
  46487. blendFactor = GPUBlendFactor.Constant;
  46488. break;
  46489. case OneMinusBlendColorFactor:
  46490. blendFactor = GPUBlendFactor.OneMinusConstant;
  46491. break;
  46492. default:
  46493. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  46494. }
  46495. return blendFactor;
  46496. }
  46497. /**
  46498. * Returns the GPU stencil compare function which is required for the pipeline creation.
  46499. *
  46500. * @private
  46501. * @param {Material} material - The material.
  46502. * @return {String} The GPU stencil compare function.
  46503. */
  46504. _getStencilCompare( material ) {
  46505. let stencilCompare;
  46506. const stencilFunc = material.stencilFunc;
  46507. switch ( stencilFunc ) {
  46508. case NeverStencilFunc:
  46509. stencilCompare = GPUCompareFunction.Never;
  46510. break;
  46511. case AlwaysStencilFunc:
  46512. stencilCompare = GPUCompareFunction.Always;
  46513. break;
  46514. case LessStencilFunc:
  46515. stencilCompare = GPUCompareFunction.Less;
  46516. break;
  46517. case LessEqualStencilFunc:
  46518. stencilCompare = GPUCompareFunction.LessEqual;
  46519. break;
  46520. case EqualStencilFunc:
  46521. stencilCompare = GPUCompareFunction.Equal;
  46522. break;
  46523. case GreaterEqualStencilFunc:
  46524. stencilCompare = GPUCompareFunction.GreaterEqual;
  46525. break;
  46526. case GreaterStencilFunc:
  46527. stencilCompare = GPUCompareFunction.Greater;
  46528. break;
  46529. case NotEqualStencilFunc:
  46530. stencilCompare = GPUCompareFunction.NotEqual;
  46531. break;
  46532. default:
  46533. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  46534. }
  46535. return stencilCompare;
  46536. }
  46537. /**
  46538. * Returns the GPU stencil operation which is required for the pipeline creation.
  46539. *
  46540. * @private
  46541. * @param {Number} op - A three.js constant defining the stencil operation.
  46542. * @return {String} The GPU stencil operation.
  46543. */
  46544. _getStencilOperation( op ) {
  46545. let stencilOperation;
  46546. switch ( op ) {
  46547. case KeepStencilOp:
  46548. stencilOperation = GPUStencilOperation.Keep;
  46549. break;
  46550. case ZeroStencilOp:
  46551. stencilOperation = GPUStencilOperation.Zero;
  46552. break;
  46553. case ReplaceStencilOp:
  46554. stencilOperation = GPUStencilOperation.Replace;
  46555. break;
  46556. case InvertStencilOp:
  46557. stencilOperation = GPUStencilOperation.Invert;
  46558. break;
  46559. case IncrementStencilOp:
  46560. stencilOperation = GPUStencilOperation.IncrementClamp;
  46561. break;
  46562. case DecrementStencilOp:
  46563. stencilOperation = GPUStencilOperation.DecrementClamp;
  46564. break;
  46565. case IncrementWrapStencilOp:
  46566. stencilOperation = GPUStencilOperation.IncrementWrap;
  46567. break;
  46568. case DecrementWrapStencilOp:
  46569. stencilOperation = GPUStencilOperation.DecrementWrap;
  46570. break;
  46571. default:
  46572. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  46573. }
  46574. return stencilOperation;
  46575. }
  46576. /**
  46577. * Returns the GPU blend operation which is required for the pipeline creation.
  46578. *
  46579. * @private
  46580. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  46581. * @return {String} The GPU blend operation.
  46582. */
  46583. _getBlendOperation( blendEquation ) {
  46584. let blendOperation;
  46585. switch ( blendEquation ) {
  46586. case AddEquation:
  46587. blendOperation = GPUBlendOperation.Add;
  46588. break;
  46589. case SubtractEquation:
  46590. blendOperation = GPUBlendOperation.Subtract;
  46591. break;
  46592. case ReverseSubtractEquation:
  46593. blendOperation = GPUBlendOperation.ReverseSubtract;
  46594. break;
  46595. case MinEquation:
  46596. blendOperation = GPUBlendOperation.Min;
  46597. break;
  46598. case MaxEquation:
  46599. blendOperation = GPUBlendOperation.Max;
  46600. break;
  46601. default:
  46602. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  46603. }
  46604. return blendOperation;
  46605. }
  46606. /**
  46607. * Returns the primitive state as a descriptor object required
  46608. * for the pipeline creation.
  46609. *
  46610. * @private
  46611. * @param {Object3D} object - The 3D object.
  46612. * @param {BufferGeometry} geometry - The geometry.
  46613. * @param {Material} material - The material.
  46614. * @return {Object} The primitive state.
  46615. */
  46616. _getPrimitiveState( object, geometry, material ) {
  46617. const descriptor = {};
  46618. const utils = this.backend.utils;
  46619. descriptor.topology = utils.getPrimitiveTopology( object, material );
  46620. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  46621. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46622. }
  46623. switch ( material.side ) {
  46624. case FrontSide:
  46625. descriptor.frontFace = GPUFrontFace.CCW;
  46626. descriptor.cullMode = GPUCullMode.Back;
  46627. break;
  46628. case BackSide:
  46629. descriptor.frontFace = GPUFrontFace.CCW;
  46630. descriptor.cullMode = GPUCullMode.Front;
  46631. break;
  46632. case DoubleSide:
  46633. descriptor.frontFace = GPUFrontFace.CCW;
  46634. descriptor.cullMode = GPUCullMode.None;
  46635. break;
  46636. default:
  46637. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  46638. break;
  46639. }
  46640. return descriptor;
  46641. }
  46642. /**
  46643. * Returns the GPU color write mask which is required for the pipeline creation.
  46644. *
  46645. * @private
  46646. * @param {Material} material - The material.
  46647. * @return {String} The GPU color write mask.
  46648. */
  46649. _getColorWriteMask( material ) {
  46650. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  46651. }
  46652. /**
  46653. * Returns the GPU depth compare function which is required for the pipeline creation.
  46654. *
  46655. * @private
  46656. * @param {Material} material - The material.
  46657. * @return {String} The GPU depth compare function.
  46658. */
  46659. _getDepthCompare( material ) {
  46660. let depthCompare;
  46661. if ( material.depthTest === false ) {
  46662. depthCompare = GPUCompareFunction.Always;
  46663. } else {
  46664. const depthFunc = material.depthFunc;
  46665. switch ( depthFunc ) {
  46666. case NeverDepth:
  46667. depthCompare = GPUCompareFunction.Never;
  46668. break;
  46669. case AlwaysDepth:
  46670. depthCompare = GPUCompareFunction.Always;
  46671. break;
  46672. case LessDepth:
  46673. depthCompare = GPUCompareFunction.Less;
  46674. break;
  46675. case LessEqualDepth:
  46676. depthCompare = GPUCompareFunction.LessEqual;
  46677. break;
  46678. case EqualDepth:
  46679. depthCompare = GPUCompareFunction.Equal;
  46680. break;
  46681. case GreaterEqualDepth:
  46682. depthCompare = GPUCompareFunction.GreaterEqual;
  46683. break;
  46684. case GreaterDepth:
  46685. depthCompare = GPUCompareFunction.Greater;
  46686. break;
  46687. case NotEqualDepth:
  46688. depthCompare = GPUCompareFunction.NotEqual;
  46689. break;
  46690. default:
  46691. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  46692. }
  46693. }
  46694. return depthCompare;
  46695. }
  46696. }
  46697. /**
  46698. * Manages a pool of WebGPU timestamp queries for performance measurement.
  46699. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  46700. * @extends TimestampQueryPool
  46701. */
  46702. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  46703. /**
  46704. * Creates a new WebGPU timestamp query pool.
  46705. * @param {GPUDevice} device - The WebGPU device to create queries on.
  46706. * @param {string} type - The type identifier for this query pool.
  46707. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  46708. */
  46709. constructor( device, type, maxQueries = 2048 ) {
  46710. super( maxQueries );
  46711. this.device = device;
  46712. this.type = type;
  46713. this.querySet = this.device.createQuerySet( {
  46714. type: 'timestamp',
  46715. count: this.maxQueries,
  46716. label: `queryset_global_timestamp_${type}`
  46717. } );
  46718. const bufferSize = this.maxQueries * 8;
  46719. this.resolveBuffer = this.device.createBuffer( {
  46720. label: `buffer_timestamp_resolve_${type}`,
  46721. size: bufferSize,
  46722. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  46723. } );
  46724. this.resultBuffer = this.device.createBuffer( {
  46725. label: `buffer_timestamp_result_${type}`,
  46726. size: bufferSize,
  46727. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46728. } );
  46729. }
  46730. /**
  46731. * Allocates a pair of queries for a given render context.
  46732. * @param {Object} renderContext - The render context to allocate queries for.
  46733. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  46734. */
  46735. allocateQueriesForContext( renderContext ) {
  46736. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  46737. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  46738. warnOnce( 'WebGPUTimestampQueryPool: Maximum number of queries exceeded.' );
  46739. return null;
  46740. }
  46741. const baseOffset = this.currentQueryIndex;
  46742. this.currentQueryIndex += 2;
  46743. this.queryOffsets.set( renderContext.id, baseOffset );
  46744. return baseOffset;
  46745. }
  46746. /**
  46747. * Asynchronously resolves all pending queries and returns the total duration.
  46748. * If there's already a pending resolve operation, returns that promise instead.
  46749. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  46750. */
  46751. async resolveQueriesAsync() {
  46752. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  46753. return this.lastValue;
  46754. }
  46755. if ( this.pendingResolve ) {
  46756. return this.pendingResolve;
  46757. }
  46758. this.pendingResolve = this._resolveQueries();
  46759. try {
  46760. const result = await this.pendingResolve;
  46761. return result;
  46762. } finally {
  46763. this.pendingResolve = null;
  46764. }
  46765. }
  46766. /**
  46767. * Internal method to resolve queries and calculate total duration.
  46768. * @private
  46769. * @returns {Promise<number>} The total duration in milliseconds.
  46770. */
  46771. async _resolveQueries() {
  46772. if ( this.isDisposed ) {
  46773. return this.lastValue;
  46774. }
  46775. try {
  46776. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  46777. return this.lastValue;
  46778. }
  46779. const currentOffsets = new Map( this.queryOffsets );
  46780. const queryCount = this.currentQueryIndex;
  46781. const bytesUsed = queryCount * 8;
  46782. // Reset state before GPU work
  46783. this.currentQueryIndex = 0;
  46784. this.queryOffsets.clear();
  46785. const commandEncoder = this.device.createCommandEncoder();
  46786. commandEncoder.resolveQuerySet(
  46787. this.querySet,
  46788. 0,
  46789. queryCount,
  46790. this.resolveBuffer,
  46791. 0
  46792. );
  46793. commandEncoder.copyBufferToBuffer(
  46794. this.resolveBuffer,
  46795. 0,
  46796. this.resultBuffer,
  46797. 0,
  46798. bytesUsed
  46799. );
  46800. const commandBuffer = commandEncoder.finish();
  46801. this.device.queue.submit( [ commandBuffer ] );
  46802. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  46803. return this.lastValue;
  46804. }
  46805. // Create and track the mapping operation
  46806. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  46807. if ( this.isDisposed ) {
  46808. if ( this.resultBuffer.mapState === 'mapped' ) {
  46809. this.resultBuffer.unmap();
  46810. }
  46811. return this.lastValue;
  46812. }
  46813. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  46814. let totalDuration = 0;
  46815. for ( const [ , baseOffset ] of currentOffsets ) {
  46816. const startTime = times[ baseOffset ];
  46817. const endTime = times[ baseOffset + 1 ];
  46818. const duration = Number( endTime - startTime ) / 1e6;
  46819. totalDuration += duration;
  46820. }
  46821. this.resultBuffer.unmap();
  46822. this.lastValue = totalDuration;
  46823. return totalDuration;
  46824. } catch ( error ) {
  46825. console.error( 'Error resolving queries:', error );
  46826. if ( this.resultBuffer.mapState === 'mapped' ) {
  46827. this.resultBuffer.unmap();
  46828. }
  46829. return this.lastValue;
  46830. }
  46831. }
  46832. async dispose() {
  46833. if ( this.isDisposed ) {
  46834. return;
  46835. }
  46836. this.isDisposed = true;
  46837. // Wait for pending resolve operation
  46838. if ( this.pendingResolve ) {
  46839. try {
  46840. await this.pendingResolve;
  46841. } catch ( error ) {
  46842. console.error( 'Error waiting for pending resolve:', error );
  46843. }
  46844. }
  46845. // Ensure buffer is unmapped before destroying
  46846. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  46847. try {
  46848. this.resultBuffer.unmap();
  46849. } catch ( error ) {
  46850. console.error( 'Error unmapping buffer:', error );
  46851. }
  46852. }
  46853. // Destroy resources
  46854. if ( this.querySet ) {
  46855. this.querySet.destroy();
  46856. this.querySet = null;
  46857. }
  46858. if ( this.resolveBuffer ) {
  46859. this.resolveBuffer.destroy();
  46860. this.resolveBuffer = null;
  46861. }
  46862. if ( this.resultBuffer ) {
  46863. this.resultBuffer.destroy();
  46864. this.resultBuffer = null;
  46865. }
  46866. this.queryOffsets.clear();
  46867. this.pendingResolve = null;
  46868. }
  46869. }
  46870. /*// debugger tools
  46871. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  46872. //*/
  46873. /**
  46874. * A backend implementation targeting WebGPU.
  46875. *
  46876. * @private
  46877. * @augments Backend
  46878. */
  46879. class WebGPUBackend extends Backend {
  46880. /**
  46881. * Constructs a new WebGPU backend.
  46882. *
  46883. * @param {Object} parameters - The configuration parameter.
  46884. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46885. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46886. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46887. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46888. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46889. * @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.
  46890. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46891. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  46892. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  46893. * @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.
  46894. * @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.
  46895. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  46896. */
  46897. constructor( parameters = {} ) {
  46898. super( parameters );
  46899. /**
  46900. * This flag can be used for type testing.
  46901. *
  46902. * @type {Boolean}
  46903. * @readonly
  46904. * @default true
  46905. */
  46906. this.isWebGPUBackend = true;
  46907. // some parameters require default values other than "undefined"
  46908. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  46909. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  46910. /**
  46911. * Whether to track timestamps with a Timestamp Query API or not.
  46912. *
  46913. * @type {Boolean}
  46914. * @default false
  46915. */
  46916. this.trackTimestamp = ( parameters.trackTimestamp === true );
  46917. /**
  46918. * A reference to the device.
  46919. *
  46920. * @type {GPUDevice?}
  46921. * @default null
  46922. */
  46923. this.device = null;
  46924. /**
  46925. * A reference to the context.
  46926. *
  46927. * @type {GPUCanvasContext?}
  46928. * @default null
  46929. */
  46930. this.context = null;
  46931. /**
  46932. * A reference to the color attachment of the default framebuffer.
  46933. *
  46934. * @type {GPUTexture?}
  46935. * @default null
  46936. */
  46937. this.colorBuffer = null;
  46938. /**
  46939. * A reference to the default render pass descriptor.
  46940. *
  46941. * @type {Object?}
  46942. * @default null
  46943. */
  46944. this.defaultRenderPassdescriptor = null;
  46945. /**
  46946. * A reference to a backend module holding common utility functions.
  46947. *
  46948. * @type {WebGPUUtils}
  46949. */
  46950. this.utils = new WebGPUUtils( this );
  46951. /**
  46952. * A reference to a backend module holding shader attribute-related
  46953. * utility functions.
  46954. *
  46955. * @type {WebGPUAttributeUtils}
  46956. */
  46957. this.attributeUtils = new WebGPUAttributeUtils( this );
  46958. /**
  46959. * A reference to a backend module holding shader binding-related
  46960. * utility functions.
  46961. *
  46962. * @type {WebGPUBindingUtils}
  46963. */
  46964. this.bindingUtils = new WebGPUBindingUtils( this );
  46965. /**
  46966. * A reference to a backend module holding shader pipeline-related
  46967. * utility functions.
  46968. *
  46969. * @type {WebGPUPipelineUtils}
  46970. */
  46971. this.pipelineUtils = new WebGPUPipelineUtils( this );
  46972. /**
  46973. * A reference to a backend module holding shader texture-related
  46974. * utility functions.
  46975. *
  46976. * @type {WebGPUTextureUtils}
  46977. */
  46978. this.textureUtils = new WebGPUTextureUtils( this );
  46979. /**
  46980. * A map that manages the resolve buffers for occlusion queries.
  46981. *
  46982. * @type {Map<Number,GPUBuffer>}
  46983. */
  46984. this.occludedResolveCache = new Map();
  46985. }
  46986. /**
  46987. * Initializes the backend so it is ready for usage.
  46988. *
  46989. * @async
  46990. * @param {Renderer} renderer - The renderer.
  46991. * @return {Promise} A Promise that resolves when the backend has been initialized.
  46992. */
  46993. async init( renderer ) {
  46994. await super.init( renderer );
  46995. //
  46996. const parameters = this.parameters;
  46997. // create the device if it is not passed with parameters
  46998. let device;
  46999. if ( parameters.device === undefined ) {
  47000. const adapterOptions = {
  47001. powerPreference: parameters.powerPreference
  47002. };
  47003. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  47004. if ( adapter === null ) {
  47005. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  47006. }
  47007. // feature support
  47008. const features = Object.values( GPUFeatureName );
  47009. const supportedFeatures = [];
  47010. for ( const name of features ) {
  47011. if ( adapter.features.has( name ) ) {
  47012. supportedFeatures.push( name );
  47013. }
  47014. }
  47015. const deviceDescriptor = {
  47016. requiredFeatures: supportedFeatures,
  47017. requiredLimits: parameters.requiredLimits
  47018. };
  47019. device = await adapter.requestDevice( deviceDescriptor );
  47020. } else {
  47021. device = parameters.device;
  47022. }
  47023. device.lost.then( ( info ) => {
  47024. const deviceLossInfo = {
  47025. api: 'WebGPU',
  47026. message: info.message || 'Unknown reason',
  47027. reason: info.reason || null,
  47028. originalEvent: info
  47029. };
  47030. renderer.onDeviceLost( deviceLossInfo );
  47031. } );
  47032. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  47033. this.device = device;
  47034. this.context = context;
  47035. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  47036. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  47037. this.context.configure( {
  47038. device: this.device,
  47039. format: this.utils.getPreferredCanvasFormat(),
  47040. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  47041. alphaMode: alphaMode
  47042. } );
  47043. this.updateSize();
  47044. }
  47045. /**
  47046. * The coordinate system of the backend.
  47047. *
  47048. * @type {Number}
  47049. * @readonly
  47050. */
  47051. get coordinateSystem() {
  47052. return WebGPUCoordinateSystem;
  47053. }
  47054. /**
  47055. * This method performs a readback operation by moving buffer data from
  47056. * a storage buffer attribute from the GPU to the CPU.
  47057. *
  47058. * @async
  47059. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47060. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47061. */
  47062. async getArrayBufferAsync( attribute ) {
  47063. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47064. }
  47065. /**
  47066. * Returns the backend's rendering context.
  47067. *
  47068. * @return {GPUCanvasContext} The rendering context.
  47069. */
  47070. getContext() {
  47071. return this.context;
  47072. }
  47073. /**
  47074. * Returns the default render pass descriptor.
  47075. *
  47076. * In WebGPU, the default framebuffer must be configured
  47077. * like custom framebuffers so the backend needs a render
  47078. * pass descriptor even when rendering directly to screen.
  47079. *
  47080. * @private
  47081. * @return {Object} The render pass descriptor.
  47082. */
  47083. _getDefaultRenderPassDescriptor() {
  47084. let descriptor = this.defaultRenderPassdescriptor;
  47085. if ( descriptor === null ) {
  47086. const renderer = this.renderer;
  47087. descriptor = {
  47088. colorAttachments: [ {
  47089. view: null
  47090. } ],
  47091. };
  47092. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  47093. descriptor.depthStencilAttachment = {
  47094. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  47095. };
  47096. }
  47097. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47098. if ( this.renderer.samples > 0 ) {
  47099. colorAttachment.view = this.colorBuffer.createView();
  47100. } else {
  47101. colorAttachment.resolveTarget = undefined;
  47102. }
  47103. this.defaultRenderPassdescriptor = descriptor;
  47104. }
  47105. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47106. if ( this.renderer.samples > 0 ) {
  47107. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  47108. } else {
  47109. colorAttachment.view = this.context.getCurrentTexture().createView();
  47110. }
  47111. return descriptor;
  47112. }
  47113. /**
  47114. * Returns the render pass descriptor for the given render context.
  47115. *
  47116. * @private
  47117. * @param {RenderContext} renderContext - The render context.
  47118. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  47119. * @return {Object} The render pass descriptor.
  47120. */
  47121. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  47122. const renderTarget = renderContext.renderTarget;
  47123. const renderTargetData = this.get( renderTarget );
  47124. let descriptors = renderTargetData.descriptors;
  47125. if ( descriptors === undefined ||
  47126. renderTargetData.width !== renderTarget.width ||
  47127. renderTargetData.height !== renderTarget.height ||
  47128. renderTargetData.dimensions !== renderTarget.dimensions ||
  47129. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  47130. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  47131. renderTargetData.samples !== renderTarget.samples ||
  47132. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  47133. ) {
  47134. descriptors = {};
  47135. renderTargetData.descriptors = descriptors;
  47136. // dispose
  47137. const onDispose = () => {
  47138. renderTarget.removeEventListener( 'dispose', onDispose );
  47139. this.delete( renderTarget );
  47140. };
  47141. renderTarget.addEventListener( 'dispose', onDispose );
  47142. }
  47143. const cacheKey = renderContext.getCacheKey();
  47144. let descriptor = descriptors[ cacheKey ];
  47145. if ( descriptor === undefined ) {
  47146. const textures = renderContext.textures;
  47147. const colorAttachments = [];
  47148. let sliceIndex;
  47149. for ( let i = 0; i < textures.length; i ++ ) {
  47150. const textureData = this.get( textures[ i ] );
  47151. const viewDescriptor = {
  47152. label: `colorAttachment_${ i }`,
  47153. baseMipLevel: renderContext.activeMipmapLevel,
  47154. mipLevelCount: 1,
  47155. baseArrayLayer: renderContext.activeCubeFace,
  47156. arrayLayerCount: 1,
  47157. dimension: GPUTextureViewDimension.TwoD
  47158. };
  47159. if ( renderTarget.isRenderTarget3D ) {
  47160. sliceIndex = renderContext.activeCubeFace;
  47161. viewDescriptor.baseArrayLayer = 0;
  47162. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  47163. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47164. } else if ( renderTarget.isRenderTargetArray ) {
  47165. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  47166. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47167. }
  47168. const textureView = textureData.texture.createView( viewDescriptor );
  47169. let view, resolveTarget;
  47170. if ( textureData.msaaTexture !== undefined ) {
  47171. view = textureData.msaaTexture.createView();
  47172. resolveTarget = textureView;
  47173. } else {
  47174. view = textureView;
  47175. resolveTarget = undefined;
  47176. }
  47177. colorAttachments.push( {
  47178. view,
  47179. depthSlice: sliceIndex,
  47180. resolveTarget,
  47181. loadOp: GPULoadOp.Load,
  47182. storeOp: GPUStoreOp.Store,
  47183. ...colorAttachmentsConfig
  47184. } );
  47185. }
  47186. descriptor = {
  47187. colorAttachments,
  47188. };
  47189. if ( renderContext.depth ) {
  47190. const depthTextureData = this.get( renderContext.depthTexture );
  47191. const depthStencilAttachment = {
  47192. view: depthTextureData.texture.createView()
  47193. };
  47194. descriptor.depthStencilAttachment = depthStencilAttachment;
  47195. }
  47196. descriptors[ cacheKey ] = descriptor;
  47197. renderTargetData.width = renderTarget.width;
  47198. renderTargetData.height = renderTarget.height;
  47199. renderTargetData.samples = renderTarget.samples;
  47200. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  47201. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  47202. renderTargetData.dimensions = renderTarget.dimensions;
  47203. renderTargetData.depthSlice = sliceIndex;
  47204. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  47205. }
  47206. return descriptor;
  47207. }
  47208. /**
  47209. * This method is executed at the beginning of a render call and prepares
  47210. * the WebGPU state for upcoming render calls
  47211. *
  47212. * @param {RenderContext} renderContext - The render context.
  47213. */
  47214. beginRender( renderContext ) {
  47215. const renderContextData = this.get( renderContext );
  47216. const device = this.device;
  47217. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47218. let occlusionQuerySet;
  47219. if ( occlusionQueryCount > 0 ) {
  47220. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  47221. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  47222. // Get a reference to the array of objects with queries. The renderContextData property
  47223. // can be changed by another render pass before the buffer.mapAsyc() completes.
  47224. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  47225. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  47226. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47227. //
  47228. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  47229. renderContextData.occlusionQuerySet = occlusionQuerySet;
  47230. renderContextData.occlusionQueryIndex = 0;
  47231. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47232. renderContextData.lastOcclusionObject = null;
  47233. }
  47234. let descriptor;
  47235. if ( renderContext.textures === null ) {
  47236. descriptor = this._getDefaultRenderPassDescriptor();
  47237. } else {
  47238. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  47239. }
  47240. this.initTimestampQuery( renderContext, descriptor );
  47241. descriptor.occlusionQuerySet = occlusionQuerySet;
  47242. const depthStencilAttachment = descriptor.depthStencilAttachment;
  47243. if ( renderContext.textures !== null ) {
  47244. const colorAttachments = descriptor.colorAttachments;
  47245. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  47246. const colorAttachment = colorAttachments[ i ];
  47247. if ( renderContext.clearColor ) {
  47248. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  47249. colorAttachment.loadOp = GPULoadOp.Clear;
  47250. colorAttachment.storeOp = GPUStoreOp.Store;
  47251. } else {
  47252. colorAttachment.loadOp = GPULoadOp.Load;
  47253. colorAttachment.storeOp = GPUStoreOp.Store;
  47254. }
  47255. }
  47256. } else {
  47257. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47258. if ( renderContext.clearColor ) {
  47259. colorAttachment.clearValue = renderContext.clearColorValue;
  47260. colorAttachment.loadOp = GPULoadOp.Clear;
  47261. colorAttachment.storeOp = GPUStoreOp.Store;
  47262. } else {
  47263. colorAttachment.loadOp = GPULoadOp.Load;
  47264. colorAttachment.storeOp = GPUStoreOp.Store;
  47265. }
  47266. }
  47267. //
  47268. if ( renderContext.depth ) {
  47269. if ( renderContext.clearDepth ) {
  47270. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  47271. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  47272. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47273. } else {
  47274. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47275. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47276. }
  47277. }
  47278. if ( renderContext.stencil ) {
  47279. if ( renderContext.clearStencil ) {
  47280. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  47281. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  47282. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47283. } else {
  47284. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47285. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47286. }
  47287. }
  47288. //
  47289. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  47290. const currentPass = encoder.beginRenderPass( descriptor );
  47291. //
  47292. renderContextData.descriptor = descriptor;
  47293. renderContextData.encoder = encoder;
  47294. renderContextData.currentPass = currentPass;
  47295. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47296. renderContextData.renderBundles = [];
  47297. //
  47298. if ( renderContext.viewport ) {
  47299. this.updateViewport( renderContext );
  47300. }
  47301. if ( renderContext.scissor ) {
  47302. const { x, y, width, height } = renderContext.scissorValue;
  47303. currentPass.setScissorRect( x, y, width, height );
  47304. }
  47305. }
  47306. /**
  47307. * This method is executed at the end of a render call and finalizes work
  47308. * after draw calls.
  47309. *
  47310. * @param {RenderContext} renderContext - The render context.
  47311. */
  47312. finishRender( renderContext ) {
  47313. const renderContextData = this.get( renderContext );
  47314. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47315. if ( renderContextData.renderBundles.length > 0 ) {
  47316. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  47317. }
  47318. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47319. renderContextData.currentPass.endOcclusionQuery();
  47320. }
  47321. renderContextData.currentPass.end();
  47322. if ( occlusionQueryCount > 0 ) {
  47323. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  47324. //
  47325. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  47326. if ( queryResolveBuffer === undefined ) {
  47327. queryResolveBuffer = this.device.createBuffer(
  47328. {
  47329. size: bufferSize,
  47330. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  47331. }
  47332. );
  47333. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  47334. }
  47335. //
  47336. const readBuffer = this.device.createBuffer(
  47337. {
  47338. size: bufferSize,
  47339. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47340. }
  47341. );
  47342. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  47343. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  47344. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  47345. renderContextData.occlusionQueryBuffer = readBuffer;
  47346. //
  47347. this.resolveOccludedAsync( renderContext );
  47348. }
  47349. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  47350. //
  47351. if ( renderContext.textures !== null ) {
  47352. const textures = renderContext.textures;
  47353. for ( let i = 0; i < textures.length; i ++ ) {
  47354. const texture = textures[ i ];
  47355. if ( texture.generateMipmaps === true ) {
  47356. this.textureUtils.generateMipmaps( texture );
  47357. }
  47358. }
  47359. }
  47360. }
  47361. /**
  47362. * Returns `true` if the given 3D object is fully occluded by other
  47363. * 3D objects in the scene.
  47364. *
  47365. * @param {RenderContext} renderContext - The render context.
  47366. * @param {Object3D} object - The 3D object to test.
  47367. * @return {Boolean} Whether the 3D object is fully occluded or not.
  47368. */
  47369. isOccluded( renderContext, object ) {
  47370. const renderContextData = this.get( renderContext );
  47371. return renderContextData.occluded && renderContextData.occluded.has( object );
  47372. }
  47373. /**
  47374. * This method processes the result of occlusion queries and writes it
  47375. * into render context data.
  47376. *
  47377. * @async
  47378. * @param {RenderContext} renderContext - The render context.
  47379. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  47380. */
  47381. async resolveOccludedAsync( renderContext ) {
  47382. const renderContextData = this.get( renderContext );
  47383. // handle occlusion query results
  47384. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  47385. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  47386. const occluded = new WeakSet();
  47387. renderContextData.currentOcclusionQueryObjects = null;
  47388. renderContextData.currentOcclusionQueryBuffer = null;
  47389. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  47390. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  47391. const results = new BigUint64Array( buffer );
  47392. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  47393. if ( results[ i ] === BigInt( 0 ) ) {
  47394. occluded.add( currentOcclusionQueryObjects[ i ] );
  47395. }
  47396. }
  47397. currentOcclusionQueryBuffer.destroy();
  47398. renderContextData.occluded = occluded;
  47399. }
  47400. }
  47401. /**
  47402. * Updates the viewport with the values from the given render context.
  47403. *
  47404. * @param {RenderContext} renderContext - The render context.
  47405. */
  47406. updateViewport( renderContext ) {
  47407. const { currentPass } = this.get( renderContext );
  47408. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  47409. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  47410. }
  47411. /**
  47412. * Performs a clear operation.
  47413. *
  47414. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  47415. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  47416. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  47417. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  47418. */
  47419. clear( color, depth, stencil, renderTargetContext = null ) {
  47420. const device = this.device;
  47421. const renderer = this.renderer;
  47422. let colorAttachments = [];
  47423. let depthStencilAttachment;
  47424. let clearValue;
  47425. let supportsDepth;
  47426. let supportsStencil;
  47427. if ( color ) {
  47428. const clearColor = this.getClearColor();
  47429. if ( this.renderer.alpha === true ) {
  47430. // premultiply alpha
  47431. const a = clearColor.a;
  47432. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  47433. } else {
  47434. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  47435. }
  47436. }
  47437. if ( renderTargetContext === null ) {
  47438. supportsDepth = renderer.depth;
  47439. supportsStencil = renderer.stencil;
  47440. const descriptor = this._getDefaultRenderPassDescriptor();
  47441. if ( color ) {
  47442. colorAttachments = descriptor.colorAttachments;
  47443. const colorAttachment = colorAttachments[ 0 ];
  47444. colorAttachment.clearValue = clearValue;
  47445. colorAttachment.loadOp = GPULoadOp.Clear;
  47446. colorAttachment.storeOp = GPUStoreOp.Store;
  47447. }
  47448. if ( supportsDepth || supportsStencil ) {
  47449. depthStencilAttachment = descriptor.depthStencilAttachment;
  47450. }
  47451. } else {
  47452. supportsDepth = renderTargetContext.depth;
  47453. supportsStencil = renderTargetContext.stencil;
  47454. if ( color ) {
  47455. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  47456. colorAttachments = descriptor.colorAttachments;
  47457. }
  47458. if ( supportsDepth || supportsStencil ) {
  47459. const depthTextureData = this.get( renderTargetContext.depthTexture );
  47460. depthStencilAttachment = {
  47461. view: depthTextureData.texture.createView()
  47462. };
  47463. }
  47464. }
  47465. //
  47466. if ( supportsDepth ) {
  47467. if ( depth ) {
  47468. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  47469. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  47470. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47471. } else {
  47472. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47473. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47474. }
  47475. }
  47476. //
  47477. if ( supportsStencil ) {
  47478. if ( stencil ) {
  47479. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  47480. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  47481. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47482. } else {
  47483. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47484. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47485. }
  47486. }
  47487. //
  47488. const encoder = device.createCommandEncoder( { label: 'clear' } );
  47489. const currentPass = encoder.beginRenderPass( {
  47490. colorAttachments,
  47491. depthStencilAttachment
  47492. } );
  47493. currentPass.end();
  47494. device.queue.submit( [ encoder.finish() ] );
  47495. }
  47496. // compute
  47497. /**
  47498. * This method is executed at the beginning of a compute call and
  47499. * prepares the state for upcoming compute tasks.
  47500. *
  47501. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47502. */
  47503. beginCompute( computeGroup ) {
  47504. const groupGPU = this.get( computeGroup );
  47505. const descriptor = {
  47506. label: 'computeGroup_' + computeGroup.id
  47507. };
  47508. this.initTimestampQuery( computeGroup, descriptor );
  47509. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  47510. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  47511. }
  47512. /**
  47513. * Executes a compute command for the given compute node.
  47514. *
  47515. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47516. * @param {Node} computeNode - The compute node.
  47517. * @param {Array<BindGroup>} bindings - The bindings.
  47518. * @param {ComputePipeline} pipeline - The compute pipeline.
  47519. */
  47520. compute( computeGroup, computeNode, bindings, pipeline ) {
  47521. const { passEncoderGPU } = this.get( computeGroup );
  47522. // pipeline
  47523. const pipelineGPU = this.get( pipeline ).pipeline;
  47524. passEncoderGPU.setPipeline( pipelineGPU );
  47525. // bind groups
  47526. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  47527. const bindGroup = bindings[ i ];
  47528. const bindingsData = this.get( bindGroup );
  47529. passEncoderGPU.setBindGroup( i, bindingsData.group );
  47530. }
  47531. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  47532. const computeNodeData = this.get( computeNode );
  47533. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  47534. const { dispatchSize } = computeNodeData;
  47535. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  47536. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  47537. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  47538. } else {
  47539. dispatchSize.x = computeNode.dispatchCount;
  47540. }
  47541. passEncoderGPU.dispatchWorkgroups(
  47542. dispatchSize.x,
  47543. dispatchSize.y,
  47544. dispatchSize.z
  47545. );
  47546. }
  47547. /**
  47548. * This method is executed at the end of a compute call and
  47549. * finalizes work after compute tasks.
  47550. *
  47551. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47552. */
  47553. finishCompute( computeGroup ) {
  47554. const groupData = this.get( computeGroup );
  47555. groupData.passEncoderGPU.end();
  47556. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  47557. }
  47558. /**
  47559. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  47560. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  47561. *
  47562. * @async
  47563. * @return {Promise} A Promise that resolves when synchronization has been finished.
  47564. */
  47565. async waitForGPU() {
  47566. await this.device.queue.onSubmittedWorkDone();
  47567. }
  47568. // render object
  47569. /**
  47570. * Executes a draw command for the given render object.
  47571. *
  47572. * @param {RenderObject} renderObject - The render object to draw.
  47573. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47574. */
  47575. draw( renderObject, info ) {
  47576. const { object, context, pipeline } = renderObject;
  47577. const bindings = renderObject.getBindings();
  47578. const renderContextData = this.get( context );
  47579. const pipelineGPU = this.get( pipeline ).pipeline;
  47580. const currentSets = renderContextData.currentSets;
  47581. const passEncoderGPU = renderContextData.currentPass;
  47582. const drawParams = renderObject.getDrawParameters();
  47583. if ( drawParams === null ) return;
  47584. // pipeline
  47585. if ( currentSets.pipeline !== pipelineGPU ) {
  47586. passEncoderGPU.setPipeline( pipelineGPU );
  47587. currentSets.pipeline = pipelineGPU;
  47588. }
  47589. // bind groups
  47590. const currentBindingGroups = currentSets.bindingGroups;
  47591. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  47592. const bindGroup = bindings[ i ];
  47593. const bindingsData = this.get( bindGroup );
  47594. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  47595. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  47596. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  47597. }
  47598. }
  47599. // attributes
  47600. const index = renderObject.getIndex();
  47601. const hasIndex = ( index !== null );
  47602. // index
  47603. if ( hasIndex === true ) {
  47604. if ( currentSets.index !== index ) {
  47605. const buffer = this.get( index ).buffer;
  47606. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  47607. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  47608. currentSets.index = index;
  47609. }
  47610. }
  47611. // vertex buffers
  47612. const vertexBuffers = renderObject.getVertexBuffers();
  47613. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  47614. const vertexBuffer = vertexBuffers[ i ];
  47615. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  47616. const buffer = this.get( vertexBuffer ).buffer;
  47617. passEncoderGPU.setVertexBuffer( i, buffer );
  47618. currentSets.attributes[ i ] = vertexBuffer;
  47619. }
  47620. }
  47621. // occlusion queries - handle multiple consecutive draw calls for an object
  47622. if ( renderContextData.occlusionQuerySet !== undefined ) {
  47623. const lastObject = renderContextData.lastOcclusionObject;
  47624. if ( lastObject !== object ) {
  47625. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47626. passEncoderGPU.endOcclusionQuery();
  47627. renderContextData.occlusionQueryIndex ++;
  47628. }
  47629. if ( object.occlusionTest === true ) {
  47630. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  47631. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  47632. }
  47633. renderContextData.lastOcclusionObject = object;
  47634. }
  47635. }
  47636. // draw
  47637. const draw = () => {
  47638. if ( object.isBatchedMesh === true ) {
  47639. const starts = object._multiDrawStarts;
  47640. const counts = object._multiDrawCounts;
  47641. const drawCount = object._multiDrawCount;
  47642. const drawInstances = object._multiDrawInstances;
  47643. for ( let i = 0; i < drawCount; i ++ ) {
  47644. const count = drawInstances ? drawInstances[ i ] : 1;
  47645. const firstInstance = count > 1 ? 0 : i;
  47646. if ( hasIndex === true ) {
  47647. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  47648. } else {
  47649. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  47650. }
  47651. }
  47652. } else if ( hasIndex === true ) {
  47653. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  47654. const indirect = renderObject.getIndirect();
  47655. if ( indirect !== null ) {
  47656. const buffer = this.get( indirect ).buffer;
  47657. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  47658. } else {
  47659. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  47660. }
  47661. info.update( object, indexCount, instanceCount );
  47662. } else {
  47663. const { vertexCount, instanceCount, firstVertex } = drawParams;
  47664. const indirect = renderObject.getIndirect();
  47665. if ( indirect !== null ) {
  47666. const buffer = this.get( indirect ).buffer;
  47667. passEncoderGPU.drawIndirect( buffer, 0 );
  47668. } else {
  47669. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  47670. }
  47671. info.update( object, vertexCount, instanceCount );
  47672. }
  47673. };
  47674. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  47675. const cameraData = this.get( renderObject.camera );
  47676. const cameras = renderObject.camera.cameras;
  47677. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  47678. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  47679. const bindingsData = this.get( cameraIndex );
  47680. const indexesGPU = [];
  47681. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  47682. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47683. data[ 0 ] = i;
  47684. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  47685. indexesGPU.push( bindGroupIndex );
  47686. }
  47687. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  47688. }
  47689. const pixelRatio = this.renderer.getPixelRatio();
  47690. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47691. const subCamera = cameras[ i ];
  47692. if ( object.layers.test( subCamera.layers ) ) {
  47693. const vp = subCamera.viewport;
  47694. passEncoderGPU.setViewport(
  47695. Math.floor( vp.x * pixelRatio ),
  47696. Math.floor( vp.y * pixelRatio ),
  47697. Math.floor( vp.width * pixelRatio ),
  47698. Math.floor( vp.height * pixelRatio ),
  47699. context.viewportValue.minDepth,
  47700. context.viewportValue.maxDepth
  47701. );
  47702. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  47703. draw();
  47704. }
  47705. }
  47706. } else {
  47707. draw();
  47708. }
  47709. }
  47710. // cache key
  47711. /**
  47712. * Returns `true` if the render pipeline requires an update.
  47713. *
  47714. * @param {RenderObject} renderObject - The render object.
  47715. * @return {Boolean} Whether the render pipeline requires an update or not.
  47716. */
  47717. needsRenderUpdate( renderObject ) {
  47718. const data = this.get( renderObject );
  47719. const { object, material } = renderObject;
  47720. const utils = this.utils;
  47721. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  47722. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  47723. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  47724. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  47725. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  47726. let needsUpdate = false;
  47727. if ( data.material !== material || data.materialVersion !== material.version ||
  47728. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  47729. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  47730. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  47731. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  47732. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  47733. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  47734. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  47735. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  47736. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  47737. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  47738. data.primitiveTopology !== primitiveTopology ||
  47739. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  47740. ) {
  47741. data.material = material; data.materialVersion = material.version;
  47742. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  47743. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  47744. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  47745. data.colorWrite = material.colorWrite;
  47746. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  47747. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  47748. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  47749. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  47750. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  47751. data.sampleCount = sampleCount;
  47752. data.colorSpace = colorSpace;
  47753. data.colorFormat = colorFormat;
  47754. data.depthStencilFormat = depthStencilFormat;
  47755. data.primitiveTopology = primitiveTopology;
  47756. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  47757. needsUpdate = true;
  47758. }
  47759. return needsUpdate;
  47760. }
  47761. /**
  47762. * Returns a cache key that is used to identify render pipelines.
  47763. *
  47764. * @param {RenderObject} renderObject - The render object.
  47765. * @return {String} The cache key.
  47766. */
  47767. getRenderCacheKey( renderObject ) {
  47768. const { object, material } = renderObject;
  47769. const utils = this.utils;
  47770. const renderContext = renderObject.context;
  47771. return [
  47772. material.transparent, material.blending, material.premultipliedAlpha,
  47773. material.blendSrc, material.blendDst, material.blendEquation,
  47774. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  47775. material.colorWrite,
  47776. material.depthWrite, material.depthTest, material.depthFunc,
  47777. material.stencilWrite, material.stencilFunc,
  47778. material.stencilFail, material.stencilZFail, material.stencilZPass,
  47779. material.stencilFuncMask, material.stencilWriteMask,
  47780. material.side,
  47781. utils.getSampleCountRenderContext( renderContext ),
  47782. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  47783. utils.getPrimitiveTopology( object, material ),
  47784. renderObject.getGeometryCacheKey(),
  47785. renderObject.clippingContextCacheKey
  47786. ].join();
  47787. }
  47788. // textures
  47789. /**
  47790. * Creates a GPU sampler for the given texture.
  47791. *
  47792. * @param {Texture} texture - The texture to create the sampler for.
  47793. */
  47794. createSampler( texture ) {
  47795. this.textureUtils.createSampler( texture );
  47796. }
  47797. /**
  47798. * Destroys the GPU sampler for the given texture.
  47799. *
  47800. * @param {Texture} texture - The texture to destroy the sampler for.
  47801. */
  47802. destroySampler( texture ) {
  47803. this.textureUtils.destroySampler( texture );
  47804. }
  47805. /**
  47806. * Creates a default texture for the given texture that can be used
  47807. * as a placeholder until the actual texture is ready for usage.
  47808. *
  47809. * @param {Texture} texture - The texture to create a default texture for.
  47810. */
  47811. createDefaultTexture( texture ) {
  47812. this.textureUtils.createDefaultTexture( texture );
  47813. }
  47814. /**
  47815. * Defines a texture on the GPU for the given texture object.
  47816. *
  47817. * @param {Texture} texture - The texture.
  47818. * @param {Object} [options={}] - Optional configuration parameter.
  47819. */
  47820. createTexture( texture, options ) {
  47821. this.textureUtils.createTexture( texture, options );
  47822. }
  47823. /**
  47824. * Uploads the updated texture data to the GPU.
  47825. *
  47826. * @param {Texture} texture - The texture.
  47827. * @param {Object} [options={}] - Optional configuration parameter.
  47828. */
  47829. updateTexture( texture, options ) {
  47830. this.textureUtils.updateTexture( texture, options );
  47831. }
  47832. /**
  47833. * Generates mipmaps for the given texture.
  47834. *
  47835. * @param {Texture} texture - The texture.
  47836. */
  47837. generateMipmaps( texture ) {
  47838. this.textureUtils.generateMipmaps( texture );
  47839. }
  47840. /**
  47841. * Destroys the GPU data for the given texture object.
  47842. *
  47843. * @param {Texture} texture - The texture.
  47844. */
  47845. destroyTexture( texture ) {
  47846. this.textureUtils.destroyTexture( texture );
  47847. }
  47848. /**
  47849. * Returns texture data as a typed array.
  47850. *
  47851. * @async
  47852. * @param {Texture} texture - The texture to copy.
  47853. * @param {Number} x - The x coordinate of the copy origin.
  47854. * @param {Number} y - The y coordinate of the copy origin.
  47855. * @param {Number} width - The width of the copy.
  47856. * @param {Number} height - The height of the copy.
  47857. * @param {Number} faceIndex - The face index.
  47858. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47859. */
  47860. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47861. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47862. }
  47863. /**
  47864. * Inits a time stamp query for the given render context.
  47865. *
  47866. * @param {RenderContext} renderContext - The render context.
  47867. * @param {Object} descriptor - The query descriptor.
  47868. */
  47869. initTimestampQuery( renderContext, descriptor ) {
  47870. if ( ! this.trackTimestamp ) return;
  47871. const type = renderContext.isComputeNode ? 'compute' : 'render';
  47872. if ( ! this.timestampQueryPool[ type ] ) {
  47873. // TODO: Variable maxQueries?
  47874. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  47875. }
  47876. const timestampQueryPool = this.timestampQueryPool[ type ];
  47877. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  47878. descriptor.timestampWrites = {
  47879. querySet: timestampQueryPool.querySet,
  47880. beginningOfPassWriteIndex: baseOffset,
  47881. endOfPassWriteIndex: baseOffset + 1,
  47882. };
  47883. }
  47884. // node builder
  47885. /**
  47886. * Returns a node builder for the given render object.
  47887. *
  47888. * @param {RenderObject} object - The render object.
  47889. * @param {Renderer} renderer - The renderer.
  47890. * @return {WGSLNodeBuilder} The node builder.
  47891. */
  47892. createNodeBuilder( object, renderer ) {
  47893. return new WGSLNodeBuilder( object, renderer );
  47894. }
  47895. // program
  47896. /**
  47897. * Creates a shader program from the given programmable stage.
  47898. *
  47899. * @param {ProgrammableStage} program - The programmable stage.
  47900. */
  47901. createProgram( program ) {
  47902. const programGPU = this.get( program );
  47903. programGPU.module = {
  47904. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  47905. entryPoint: 'main'
  47906. };
  47907. }
  47908. /**
  47909. * Destroys the shader program of the given programmable stage.
  47910. *
  47911. * @param {ProgrammableStage} program - The programmable stage.
  47912. */
  47913. destroyProgram( program ) {
  47914. this.delete( program );
  47915. }
  47916. // pipelines
  47917. /**
  47918. * Creates a render pipeline for the given render object.
  47919. *
  47920. * @param {RenderObject} renderObject - The render object.
  47921. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47922. */
  47923. createRenderPipeline( renderObject, promises ) {
  47924. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  47925. }
  47926. /**
  47927. * Creates a compute pipeline for the given compute node.
  47928. *
  47929. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47930. * @param {Array<BindGroup>} bindings - The bindings.
  47931. */
  47932. createComputePipeline( computePipeline, bindings ) {
  47933. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  47934. }
  47935. /**
  47936. * Prepares the state for encoding render bundles.
  47937. *
  47938. * @param {RenderContext} renderContext - The render context.
  47939. */
  47940. beginBundle( renderContext ) {
  47941. const renderContextData = this.get( renderContext );
  47942. renderContextData._currentPass = renderContextData.currentPass;
  47943. renderContextData._currentSets = renderContextData.currentSets;
  47944. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47945. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  47946. }
  47947. /**
  47948. * After processing render bundles this method finalizes related work.
  47949. *
  47950. * @param {RenderContext} renderContext - The render context.
  47951. * @param {RenderBundle} bundle - The render bundle.
  47952. */
  47953. finishBundle( renderContext, bundle ) {
  47954. const renderContextData = this.get( renderContext );
  47955. const bundleEncoder = renderContextData.currentPass;
  47956. const bundleGPU = bundleEncoder.finish();
  47957. this.get( bundle ).bundleGPU = bundleGPU;
  47958. // restore render pass state
  47959. renderContextData.currentSets = renderContextData._currentSets;
  47960. renderContextData.currentPass = renderContextData._currentPass;
  47961. }
  47962. /**
  47963. * Adds a render bundle to the render context data.
  47964. *
  47965. * @param {RenderContext} renderContext - The render context.
  47966. * @param {RenderBundle} bundle - The render bundle to add.
  47967. */
  47968. addBundle( renderContext, bundle ) {
  47969. const renderContextData = this.get( renderContext );
  47970. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  47971. }
  47972. // bindings
  47973. /**
  47974. * Creates bindings from the given bind group definition.
  47975. *
  47976. * @param {BindGroup} bindGroup - The bind group.
  47977. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47978. * @param {Number} cacheIndex - The cache index.
  47979. * @param {Number} version - The version.
  47980. */
  47981. createBindings( bindGroup, bindings, cacheIndex, version ) {
  47982. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47983. }
  47984. /**
  47985. * Updates the given bind group definition.
  47986. *
  47987. * @param {BindGroup} bindGroup - The bind group.
  47988. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47989. * @param {Number} cacheIndex - The cache index.
  47990. * @param {Number} version - The version.
  47991. */
  47992. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  47993. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47994. }
  47995. /**
  47996. * Updates a buffer binding.
  47997. *
  47998. * @param {Buffer} binding - The buffer binding to update.
  47999. */
  48000. updateBinding( binding ) {
  48001. this.bindingUtils.updateBinding( binding );
  48002. }
  48003. // attributes
  48004. /**
  48005. * Creates the buffer of an indexed shader attribute.
  48006. *
  48007. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48008. */
  48009. createIndexAttribute( attribute ) {
  48010. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48011. }
  48012. /**
  48013. * Creates the GPU buffer of a shader attribute.
  48014. *
  48015. * @param {BufferAttribute} attribute - The buffer attribute.
  48016. */
  48017. createAttribute( attribute ) {
  48018. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48019. }
  48020. /**
  48021. * Creates the GPU buffer of a storage attribute.
  48022. *
  48023. * @param {BufferAttribute} attribute - The buffer attribute.
  48024. */
  48025. createStorageAttribute( attribute ) {
  48026. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48027. }
  48028. /**
  48029. * Creates the GPU buffer of an indirect storage attribute.
  48030. *
  48031. * @param {BufferAttribute} attribute - The buffer attribute.
  48032. */
  48033. createIndirectStorageAttribute( attribute ) {
  48034. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48035. }
  48036. /**
  48037. * Updates the GPU buffer of a shader attribute.
  48038. *
  48039. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48040. */
  48041. updateAttribute( attribute ) {
  48042. this.attributeUtils.updateAttribute( attribute );
  48043. }
  48044. /**
  48045. * Destroys the GPU buffer of a shader attribute.
  48046. *
  48047. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48048. */
  48049. destroyAttribute( attribute ) {
  48050. this.attributeUtils.destroyAttribute( attribute );
  48051. }
  48052. // canvas
  48053. /**
  48054. * Triggers an update of the default render pass descriptor.
  48055. */
  48056. updateSize() {
  48057. this.colorBuffer = this.textureUtils.getColorBuffer();
  48058. this.defaultRenderPassdescriptor = null;
  48059. }
  48060. // utils public
  48061. /**
  48062. * Returns the maximum anisotropy texture filtering value.
  48063. *
  48064. * @return {Number} The maximum anisotropy texture filtering value.
  48065. */
  48066. getMaxAnisotropy() {
  48067. return 16;
  48068. }
  48069. /**
  48070. * Checks if the given feature is supported by the backend.
  48071. *
  48072. * @param {String} name - The feature's name.
  48073. * @return {Boolean} Whether the feature is supported or not.
  48074. */
  48075. hasFeature( name ) {
  48076. return this.device.features.has( name );
  48077. }
  48078. /**
  48079. * Copies data of the given source texture to the given destination texture.
  48080. *
  48081. * @param {Texture} srcTexture - The source texture.
  48082. * @param {Texture} dstTexture - The destination texture.
  48083. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  48084. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  48085. * @param {Number} [level=0] - The mip level to copy.
  48086. */
  48087. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  48088. let dstX = 0;
  48089. let dstY = 0;
  48090. let dstLayer = 0;
  48091. let srcX = 0;
  48092. let srcY = 0;
  48093. let srcLayer = 0;
  48094. let srcWidth = srcTexture.image.width;
  48095. let srcHeight = srcTexture.image.height;
  48096. if ( srcRegion !== null ) {
  48097. srcX = srcRegion.x;
  48098. srcY = srcRegion.y;
  48099. srcLayer = srcRegion.z || 0;
  48100. srcWidth = srcRegion.width;
  48101. srcHeight = srcRegion.height;
  48102. }
  48103. if ( dstPosition !== null ) {
  48104. dstX = dstPosition.x;
  48105. dstY = dstPosition.y;
  48106. dstLayer = dstPosition.z || 0;
  48107. }
  48108. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  48109. const sourceGPU = this.get( srcTexture ).texture;
  48110. const destinationGPU = this.get( dstTexture ).texture;
  48111. encoder.copyTextureToTexture(
  48112. {
  48113. texture: sourceGPU,
  48114. mipLevel: level,
  48115. origin: { x: srcX, y: srcY, z: srcLayer }
  48116. },
  48117. {
  48118. texture: destinationGPU,
  48119. mipLevel: level,
  48120. origin: { x: dstX, y: dstY, z: dstLayer }
  48121. },
  48122. [
  48123. srcWidth,
  48124. srcHeight,
  48125. 1
  48126. ]
  48127. );
  48128. this.device.queue.submit( [ encoder.finish() ] );
  48129. }
  48130. /**
  48131. * Copies the current bound framebuffer to the given texture.
  48132. *
  48133. * @param {Texture} texture - The destination texture.
  48134. * @param {RenderContext} renderContext - The render context.
  48135. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48136. */
  48137. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48138. const renderContextData = this.get( renderContext );
  48139. let sourceGPU = null;
  48140. if ( renderContext.renderTarget ) {
  48141. if ( texture.isDepthTexture ) {
  48142. sourceGPU = this.get( renderContext.depthTexture ).texture;
  48143. } else {
  48144. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  48145. }
  48146. } else {
  48147. if ( texture.isDepthTexture ) {
  48148. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  48149. } else {
  48150. sourceGPU = this.context.getCurrentTexture();
  48151. }
  48152. }
  48153. const destinationGPU = this.get( texture ).texture;
  48154. if ( sourceGPU.format !== destinationGPU.format ) {
  48155. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  48156. return;
  48157. }
  48158. let encoder;
  48159. if ( renderContextData.currentPass ) {
  48160. renderContextData.currentPass.end();
  48161. encoder = renderContextData.encoder;
  48162. } else {
  48163. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  48164. }
  48165. encoder.copyTextureToTexture(
  48166. {
  48167. texture: sourceGPU,
  48168. origin: [ rectangle.x, rectangle.y, 0 ],
  48169. },
  48170. {
  48171. texture: destinationGPU
  48172. },
  48173. [
  48174. rectangle.z,
  48175. rectangle.w
  48176. ]
  48177. );
  48178. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  48179. if ( renderContextData.currentPass ) {
  48180. const { descriptor } = renderContextData;
  48181. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  48182. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  48183. }
  48184. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48185. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48186. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  48187. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48188. if ( renderContext.viewport ) {
  48189. this.updateViewport( renderContext );
  48190. }
  48191. if ( renderContext.scissor ) {
  48192. const { x, y, width, height } = renderContext.scissorValue;
  48193. renderContextData.currentPass.setScissorRect( x, y, width, height );
  48194. }
  48195. } else {
  48196. this.device.queue.submit( [ encoder.finish() ] );
  48197. }
  48198. }
  48199. }
  48200. class IESSpotLight extends SpotLight {
  48201. constructor( color, intensity, distance, angle, penumbra, decay ) {
  48202. super( color, intensity, distance, angle, penumbra, decay );
  48203. this.iesMap = null;
  48204. }
  48205. copy( source, recursive ) {
  48206. super.copy( source, recursive );
  48207. this.iesMap = source.iesMap;
  48208. return this;
  48209. }
  48210. }
  48211. /**
  48212. * This version of a node library represents a basic version
  48213. * just focusing on lights and tone mapping techniques.
  48214. *
  48215. * @private
  48216. * @augments NodeLibrary
  48217. */
  48218. class BasicNodeLibrary extends NodeLibrary {
  48219. /**
  48220. * Constructs a new basic node library.
  48221. */
  48222. constructor() {
  48223. super();
  48224. this.addLight( PointLightNode, PointLight );
  48225. this.addLight( DirectionalLightNode, DirectionalLight );
  48226. this.addLight( RectAreaLightNode, RectAreaLight );
  48227. this.addLight( SpotLightNode, SpotLight );
  48228. this.addLight( AmbientLightNode, AmbientLight );
  48229. this.addLight( HemisphereLightNode, HemisphereLight );
  48230. this.addLight( LightProbeNode, LightProbe );
  48231. this.addLight( IESSpotLightNode, IESSpotLight );
  48232. this.addToneMapping( linearToneMapping, LinearToneMapping );
  48233. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  48234. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  48235. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  48236. this.addToneMapping( agxToneMapping, AgXToneMapping );
  48237. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  48238. }
  48239. }
  48240. /**
  48241. * This alternative version of {@link WebGPURenderer} only supports node materials.
  48242. * So classes like `MeshBasicMaterial` are not compatible.
  48243. *
  48244. * @augments module:Renderer~Renderer
  48245. */
  48246. class WebGPURenderer extends Renderer {
  48247. /**
  48248. * Constructs a new WebGPU renderer.
  48249. *
  48250. * @param {Object} parameters - The configuration parameter.
  48251. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48252. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48253. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48254. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48255. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48256. * @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
  48257. * to overwrite the default.
  48258. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it
  48259. * WebGL 2 backend no matter if WebGPU is supported or not.
  48260. */
  48261. constructor( parameters = {} ) {
  48262. let BackendClass;
  48263. if ( parameters.forceWebGL ) {
  48264. BackendClass = WebGLBackend;
  48265. } else {
  48266. BackendClass = WebGPUBackend;
  48267. parameters.getFallback = () => {
  48268. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  48269. return new WebGLBackend( parameters );
  48270. };
  48271. }
  48272. const backend = new BackendClass( parameters );
  48273. super( backend, parameters );
  48274. /**
  48275. * The generic default value is overwritten with the
  48276. * standard node library for type mapping. Material
  48277. * mapping is not supported with this version.
  48278. *
  48279. * @type {BasicNodeLibrary}
  48280. */
  48281. this.library = new BasicNodeLibrary();
  48282. /**
  48283. * This flag can be used for type testing.
  48284. *
  48285. * @type {Boolean}
  48286. * @readonly
  48287. * @default true
  48288. */
  48289. this.isWebGPURenderer = true;
  48290. }
  48291. }
  48292. /**
  48293. * A specialized group which enables applications access to the
  48294. * Render Bundle API of WebGPU. The group with all its descendant nodes
  48295. * are considered as one render bundle and processed as such by
  48296. * the renderer.
  48297. *
  48298. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  48299. * With a WebGL backend, the group can technically be rendered but without
  48300. * any performance improvements.
  48301. *
  48302. * @augments Group
  48303. */
  48304. class BundleGroup extends Group {
  48305. /**
  48306. * Constructs a new bundle group.
  48307. */
  48308. constructor() {
  48309. super();
  48310. /**
  48311. * This flag can be used for type testing.
  48312. *
  48313. * @type {Boolean}
  48314. * @readonly
  48315. * @default true
  48316. */
  48317. this.isBundleGroup = true;
  48318. /**
  48319. * This property is only relevant for detecting types
  48320. * during serialization/deserialization. It should always
  48321. * match the class name.
  48322. *
  48323. * @type {String}
  48324. * @readonly
  48325. * @default 'BundleGroup'
  48326. */
  48327. this.type = 'BundleGroup';
  48328. /**
  48329. * Whether the bundle is static or not. When set to `true`, the structure
  48330. * is assumed to be static and does not change. E.g. no new objects are
  48331. * added to the group
  48332. *
  48333. * If a change is required, an update can still be forced by setting the
  48334. * `needsUpdate` flag to `true`.
  48335. *
  48336. * @type {Boolean}
  48337. * @default true
  48338. */
  48339. this.static = true;
  48340. /**
  48341. * The bundle group's version.
  48342. *
  48343. * @type {Number}
  48344. * @readonly
  48345. * @default 0
  48346. */
  48347. this.version = 0;
  48348. }
  48349. /**
  48350. * Set this property to `true` when the bundle group has changed.
  48351. *
  48352. * @type {Boolean}
  48353. * @default false
  48354. * @param {Boolean} value
  48355. */
  48356. set needsUpdate( value ) {
  48357. if ( value === true ) this.version ++;
  48358. }
  48359. }
  48360. /**
  48361. * This module is responsible to manage the post processing setups in apps.
  48362. * You usually create a single instance of this class and use it to define
  48363. * the output of your post processing effect chain.
  48364. * ```js
  48365. * const postProcessing = new PostProcessing( renderer );
  48366. *
  48367. * const scenePass = pass( scene, camera );
  48368. *
  48369. * postProcessing.outputNode = scenePass;
  48370. * ```
  48371. */
  48372. class PostProcessing {
  48373. /**
  48374. * Constructs a new post processing management module.
  48375. *
  48376. * @param {Renderer} renderer - A reference to the renderer.
  48377. * @param {Node<vec4>} outputNode - An optional output node.
  48378. */
  48379. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  48380. /**
  48381. * A reference to the renderer.
  48382. *
  48383. * @type {Renderer}
  48384. */
  48385. this.renderer = renderer;
  48386. /**
  48387. * A node which defines the final output of the post
  48388. * processing. This is usually the last node in a chain
  48389. * of effect nodes.
  48390. *
  48391. * @type {Node<vec4>}
  48392. */
  48393. this.outputNode = outputNode;
  48394. /**
  48395. * Whether the default output tone mapping and color
  48396. * space transformation should be enabled or not.
  48397. *
  48398. * It is enabled by default by it must be disabled when
  48399. * effects must be executed after tone mapping and color
  48400. * space conversion. A typical example is FXAA which
  48401. * requires sRGB input.
  48402. *
  48403. * When set to `false`, the app must control the output
  48404. * transformation with `RenderOutputNode`.
  48405. *
  48406. * ```js
  48407. * const outputPass = renderOutput( scenePass );
  48408. * ```
  48409. *
  48410. * @type {Boolean}
  48411. */
  48412. this.outputColorTransform = true;
  48413. /**
  48414. * Must be set to `true` when the output node changes.
  48415. *
  48416. * @type {Node<vec4>}
  48417. */
  48418. this.needsUpdate = true;
  48419. const material = new NodeMaterial();
  48420. material.name = 'PostProcessing';
  48421. /**
  48422. * The full screen quad that is used to render
  48423. * the effects.
  48424. *
  48425. * @private
  48426. * @type {QuadMesh}
  48427. */
  48428. this._quadMesh = new QuadMesh( material );
  48429. }
  48430. /**
  48431. * When `PostProcessing` is used to apply post processing effects,
  48432. * the application must use this version of `render()` inside
  48433. * its animation loop (not the one from the renderer).
  48434. */
  48435. render() {
  48436. this._update();
  48437. const renderer = this.renderer;
  48438. const toneMapping = renderer.toneMapping;
  48439. const outputColorSpace = renderer.outputColorSpace;
  48440. renderer.toneMapping = NoToneMapping;
  48441. renderer.outputColorSpace = LinearSRGBColorSpace;
  48442. //
  48443. this._quadMesh.render( renderer );
  48444. //
  48445. renderer.toneMapping = toneMapping;
  48446. renderer.outputColorSpace = outputColorSpace;
  48447. }
  48448. /**
  48449. * Frees internal resources.
  48450. */
  48451. dispose() {
  48452. this._quadMesh.material.dispose();
  48453. }
  48454. /**
  48455. * Updates the state of the module.
  48456. *
  48457. * @private
  48458. */
  48459. _update() {
  48460. if ( this.needsUpdate === true ) {
  48461. const renderer = this.renderer;
  48462. const toneMapping = renderer.toneMapping;
  48463. const outputColorSpace = renderer.outputColorSpace;
  48464. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  48465. this._quadMesh.material.needsUpdate = true;
  48466. this.needsUpdate = false;
  48467. }
  48468. }
  48469. /**
  48470. * When `PostProcessing` is used to apply post processing effects,
  48471. * the application must use this version of `renderAsync()` inside
  48472. * its animation loop (not the one from the renderer).
  48473. *
  48474. * @async
  48475. * @return {Promise} A Promise that resolves when the render has been finished.
  48476. */
  48477. async renderAsync() {
  48478. this._update();
  48479. const renderer = this.renderer;
  48480. const toneMapping = renderer.toneMapping;
  48481. const outputColorSpace = renderer.outputColorSpace;
  48482. renderer.toneMapping = NoToneMapping;
  48483. renderer.outputColorSpace = LinearSRGBColorSpace;
  48484. //
  48485. await this._quadMesh.renderAsync( renderer );
  48486. //
  48487. renderer.toneMapping = toneMapping;
  48488. renderer.outputColorSpace = outputColorSpace;
  48489. }
  48490. }
  48491. /**
  48492. * This special type of texture is intended for compute shaders.
  48493. * It can be used to compute the data of a texture with a compute shader.
  48494. *
  48495. * Note: This type of texture can only be used with `WebGPURenderer`
  48496. * and a WebGPU backend.
  48497. *
  48498. * @augments Texture
  48499. */
  48500. class StorageTexture extends Texture {
  48501. /**
  48502. * Constructs a new storage texture.
  48503. *
  48504. * @param {Number} [width=1] - The storage texture's width.
  48505. * @param {Number} [height=1] - The storage texture's height.
  48506. */
  48507. constructor( width = 1, height = 1 ) {
  48508. super();
  48509. /**
  48510. * The image object which just represents the texture's dimension.
  48511. *
  48512. * @type {{width: Number, height: Number}}
  48513. */
  48514. this.image = { width, height };
  48515. /**
  48516. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  48517. *
  48518. * @type {Number}
  48519. */
  48520. this.magFilter = LinearFilter;
  48521. /**
  48522. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  48523. *
  48524. * @type {Number}
  48525. */
  48526. this.minFilter = LinearFilter;
  48527. /**
  48528. * This flag can be used for type testing.
  48529. *
  48530. * @type {Boolean}
  48531. * @readonly
  48532. * @default true
  48533. */
  48534. this.isStorageTexture = true;
  48535. }
  48536. }
  48537. /**
  48538. * This special type of buffer attribute is intended for compute shaders.
  48539. * It can be used to encode draw parameters for indirect draw calls.
  48540. *
  48541. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  48542. * and a WebGPU backend.
  48543. *
  48544. * @augments StorageBufferAttribute
  48545. */
  48546. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  48547. /**
  48548. * Constructs a new storage buffer attribute.
  48549. *
  48550. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  48551. * The subsequent parameter is then obsolete.
  48552. * @param {Number} itemSize - The item size.
  48553. */
  48554. constructor( count, itemSize ) {
  48555. super( count, itemSize, Uint32Array );
  48556. /**
  48557. * This flag can be used for type testing.
  48558. *
  48559. * @type {Boolean}
  48560. * @readonly
  48561. * @default true
  48562. */
  48563. this.isIndirectStorageBufferAttribute = true;
  48564. }
  48565. }
  48566. /**
  48567. * A loader for loading node objects in the three.js JSON Object/Scene format.
  48568. *
  48569. * @augments Loader
  48570. */
  48571. class NodeLoader extends Loader {
  48572. /**
  48573. * Constructs a new node loader.
  48574. *
  48575. * @param {LoadingManager?} manager - A reference to a loading manager.
  48576. */
  48577. constructor( manager ) {
  48578. super( manager );
  48579. /**
  48580. * Represents a dictionary of textures.
  48581. *
  48582. * @type {Object<String,Texture>}
  48583. */
  48584. this.textures = {};
  48585. /**
  48586. * Represents a dictionary of node types.
  48587. *
  48588. * @type {Object<String,Node.constructor>}
  48589. */
  48590. this.nodes = {};
  48591. }
  48592. /**
  48593. * Loads the node definitions from the given URL.
  48594. *
  48595. * @param {String} url - The path/URL of the file to be loaded.
  48596. * @param {Function} onLoad - Will be called when load completes.
  48597. * @param {Function} onProgress - Will be called while load progresses.
  48598. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  48599. */
  48600. load( url, onLoad, onProgress, onError ) {
  48601. const loader = new FileLoader( this.manager );
  48602. loader.setPath( this.path );
  48603. loader.setRequestHeader( this.requestHeader );
  48604. loader.setWithCredentials( this.withCredentials );
  48605. loader.load( url, ( text ) => {
  48606. try {
  48607. onLoad( this.parse( JSON.parse( text ) ) );
  48608. } catch ( e ) {
  48609. if ( onError ) {
  48610. onError( e );
  48611. } else {
  48612. console.error( e );
  48613. }
  48614. this.manager.itemError( url );
  48615. }
  48616. }, onProgress, onError );
  48617. }
  48618. /**
  48619. * Parse the node dependencies for the loaded node.
  48620. *
  48621. * @param {Object} json - The JSON definition
  48622. * @return {Object<String,Node>} A dictionary with node dependencies.
  48623. */
  48624. parseNodes( json ) {
  48625. const nodes = {};
  48626. if ( json !== undefined ) {
  48627. for ( const nodeJSON of json ) {
  48628. const { uuid, type } = nodeJSON;
  48629. nodes[ uuid ] = this.createNodeFromType( type );
  48630. nodes[ uuid ].uuid = uuid;
  48631. }
  48632. const meta = { nodes, textures: this.textures };
  48633. for ( const nodeJSON of json ) {
  48634. nodeJSON.meta = meta;
  48635. const node = nodes[ nodeJSON.uuid ];
  48636. node.deserialize( nodeJSON );
  48637. delete nodeJSON.meta;
  48638. }
  48639. }
  48640. return nodes;
  48641. }
  48642. /**
  48643. * Parses the node from the given JSON.
  48644. *
  48645. * @param {Object} json - The JSON definition
  48646. * @return {Node} The parsed node.
  48647. */
  48648. parse( json ) {
  48649. const node = this.createNodeFromType( json.type );
  48650. node.uuid = json.uuid;
  48651. const nodes = this.parseNodes( json.nodes );
  48652. const meta = { nodes, textures: this.textures };
  48653. json.meta = meta;
  48654. node.deserialize( json );
  48655. delete json.meta;
  48656. return node;
  48657. }
  48658. /**
  48659. * Defines the dictionary of textures.
  48660. *
  48661. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  48662. * @return {NodeLoader} A reference to this loader.
  48663. */
  48664. setTextures( value ) {
  48665. this.textures = value;
  48666. return this;
  48667. }
  48668. /**
  48669. * Defines the dictionary of node types.
  48670. *
  48671. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48672. * @return {NodeLoader} A reference to this loader.
  48673. */
  48674. setNodes( value ) {
  48675. this.nodes = value;
  48676. return this;
  48677. }
  48678. /**
  48679. * Creates a node object from the given type.
  48680. *
  48681. * @param {String} type - The node type.
  48682. * @return {Node} The created node instance.
  48683. */
  48684. createNodeFromType( type ) {
  48685. if ( this.nodes[ type ] === undefined ) {
  48686. console.error( 'THREE.NodeLoader: Node type not found:', type );
  48687. return float();
  48688. }
  48689. return nodeObject( new this.nodes[ type ]() );
  48690. }
  48691. }
  48692. /**
  48693. * A special type of material loader for loading node materials.
  48694. *
  48695. * @augments MaterialLoader
  48696. */
  48697. class NodeMaterialLoader extends MaterialLoader {
  48698. /**
  48699. * Constructs a new node material loader.
  48700. *
  48701. * @param {LoadingManager?} manager - A reference to a loading manager.
  48702. */
  48703. constructor( manager ) {
  48704. super( manager );
  48705. /**
  48706. * Represents a dictionary of node types.
  48707. *
  48708. * @type {Object<String,Node.constructor>}
  48709. */
  48710. this.nodes = {};
  48711. /**
  48712. * Represents a dictionary of node material types.
  48713. *
  48714. * @type {Object<String,NodeMaterial.constructor>}
  48715. */
  48716. this.nodeMaterials = {};
  48717. }
  48718. /**
  48719. * Parses the node material from the given JSON.
  48720. *
  48721. * @param {Object} json - The JSON definition
  48722. * @return {NodeMaterial}. The parsed material.
  48723. */
  48724. parse( json ) {
  48725. const material = super.parse( json );
  48726. const nodes = this.nodes;
  48727. const inputNodes = json.inputNodes;
  48728. for ( const property in inputNodes ) {
  48729. const uuid = inputNodes[ property ];
  48730. material[ property ] = nodes[ uuid ];
  48731. }
  48732. return material;
  48733. }
  48734. /**
  48735. * Defines the dictionary of node types.
  48736. *
  48737. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48738. * @return {NodeLoader} A reference to this loader.
  48739. */
  48740. setNodes( value ) {
  48741. this.nodes = value;
  48742. return this;
  48743. }
  48744. /**
  48745. * Defines the dictionary of node material types.
  48746. *
  48747. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48748. * @return {NodeLoader} A reference to this loader.
  48749. */
  48750. setNodeMaterials( value ) {
  48751. this.nodeMaterials = value;
  48752. return this;
  48753. }
  48754. /**
  48755. * Creates a node material from the given type.
  48756. *
  48757. * @param {String} type - The node material type.
  48758. * @return {Node} The created node material instance.
  48759. */
  48760. createMaterialFromType( type ) {
  48761. const materialClass = this.nodeMaterials[ type ];
  48762. if ( materialClass !== undefined ) {
  48763. return new materialClass();
  48764. }
  48765. return super.createMaterialFromType( type );
  48766. }
  48767. }
  48768. /**
  48769. * A special type of object loader for loading 3D objects using
  48770. * node materials.
  48771. *
  48772. * @augments ObjectLoader
  48773. */
  48774. class NodeObjectLoader extends ObjectLoader {
  48775. /**
  48776. * Constructs a new node object loader.
  48777. *
  48778. * @param {LoadingManager?} manager - A reference to a loading manager.
  48779. */
  48780. constructor( manager ) {
  48781. super( manager );
  48782. /**
  48783. * Represents a dictionary of node types.
  48784. *
  48785. * @type {Object<String,Node.constructor>}
  48786. */
  48787. this.nodes = {};
  48788. /**
  48789. * Represents a dictionary of node material types.
  48790. *
  48791. * @type {Object<String,NodeMaterial.constructor>}
  48792. */
  48793. this.nodeMaterials = {};
  48794. /**
  48795. * A reference to hold the `nodes` JSON property.
  48796. *
  48797. * @private
  48798. * @type {Object?}
  48799. */
  48800. this._nodesJSON = null;
  48801. }
  48802. /**
  48803. * Defines the dictionary of node types.
  48804. *
  48805. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48806. * @return {NodeLoader} A reference to this loader.
  48807. */
  48808. setNodes( value ) {
  48809. this.nodes = value;
  48810. return this;
  48811. }
  48812. /**
  48813. * Defines the dictionary of node material types.
  48814. *
  48815. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48816. * @return {NodeLoader} A reference to this loader.
  48817. */
  48818. setNodeMaterials( value ) {
  48819. this.nodeMaterials = value;
  48820. return this;
  48821. }
  48822. /**
  48823. * Parses the node objects from the given JSON.
  48824. *
  48825. * @param {Object} json - The JSON definition
  48826. * @param {Function} onLoad - The onLoad callback function.
  48827. * @return {Object3D}. The parsed 3D object.
  48828. */
  48829. parse( json, onLoad ) {
  48830. this._nodesJSON = json.nodes;
  48831. const data = super.parse( json, onLoad );
  48832. this._nodesJSON = null; // dispose
  48833. return data;
  48834. }
  48835. /**
  48836. * Parses the node objects from the given JSON and textures.
  48837. *
  48838. * @param {Object} json - The JSON definition
  48839. * @param {Object<String,Texture>} textures - The texture library.
  48840. * @return {Object<String,Node>}. The parsed nodes.
  48841. */
  48842. parseNodes( json, textures ) {
  48843. if ( json !== undefined ) {
  48844. const loader = new NodeLoader();
  48845. loader.setNodes( this.nodes );
  48846. loader.setTextures( textures );
  48847. return loader.parseNodes( json );
  48848. }
  48849. return {};
  48850. }
  48851. /**
  48852. * Parses the node objects from the given JSON and textures.
  48853. *
  48854. * @param {Object} json - The JSON definition
  48855. * @param {Object<String,Texture>} textures - The texture library.
  48856. * @return {Object<String,NodeMaterial>}. The parsed materials.
  48857. */
  48858. parseMaterials( json, textures ) {
  48859. const materials = {};
  48860. if ( json !== undefined ) {
  48861. const nodes = this.parseNodes( this._nodesJSON, textures );
  48862. const loader = new NodeMaterialLoader();
  48863. loader.setTextures( textures );
  48864. loader.setNodes( nodes );
  48865. loader.setNodeMaterials( this.nodeMaterials );
  48866. for ( let i = 0, l = json.length; i < l; i ++ ) {
  48867. const data = json[ i ];
  48868. materials[ data.uuid ] = loader.parse( data );
  48869. }
  48870. }
  48871. return materials;
  48872. }
  48873. }
  48874. /**
  48875. * In earlier three.js versions, clipping was defined globally
  48876. * on the renderer or on material level. This special version of
  48877. * `THREE.Group` allows to encode the clipping state into the scene
  48878. * graph. Meaning if you create an instance of this group, all
  48879. * descendant 3D objects will be affected by the respective clipping
  48880. * planes.
  48881. *
  48882. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  48883. *
  48884. * @augments Group
  48885. */
  48886. class ClippingGroup extends Group {
  48887. /**
  48888. * Constructs a new clipping group.
  48889. */
  48890. constructor() {
  48891. super();
  48892. /**
  48893. * This flag can be used for type testing.
  48894. *
  48895. * @type {Boolean}
  48896. * @readonly
  48897. * @default true
  48898. */
  48899. this.isClippingGroup = true;
  48900. /**
  48901. * An array with clipping planes.
  48902. *
  48903. * @type {Array<Plane>}
  48904. */
  48905. this.clippingPlanes = [];
  48906. /**
  48907. * Whether clipping should be enabled or not.
  48908. *
  48909. * @type {Boolean}
  48910. * @default true
  48911. */
  48912. this.enabled = true;
  48913. /**
  48914. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  48915. *
  48916. * @type {Boolean}
  48917. * @default false
  48918. */
  48919. this.clipIntersection = false;
  48920. /**
  48921. * Whether shadows should be clipped or not.
  48922. *
  48923. * @type {Boolean}
  48924. * @default false
  48925. */
  48926. this.clipShadows = false;
  48927. }
  48928. }
  48929. 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, 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, 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号