three.webgpu.nodes.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801
  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, NearestFilter, Sphere, BackSide, Euler, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, SRGBColorSpace, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, BufferGeometry, BufferAttribute, RenderTarget, CubeUVReflectionMapping, OrthographicCamera, PerspectiveCamera, HalfFloatType, RGBAFormat, LinearSRGBColorSpace, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, arrayNeedsUint32, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, WebXRController, RAD2DEG, Quaternion, PCFShadowMap, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, warnOnce, createCanvasElement, SubtractEquation, ReverseSubtractEquation, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, 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, 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, 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, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<string>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. id: geometry.id,
  133. attributes: this.getAttributesData( geometry.attributes ),
  134. indexVersion: geometry.index ? geometry.index.version : null,
  135. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  136. },
  137. worldMatrix: object.matrixWorld.clone()
  138. };
  139. if ( object.center ) {
  140. data.center = object.center.clone();
  141. }
  142. if ( object.morphTargetInfluences ) {
  143. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  144. }
  145. if ( renderObject.bundle !== null ) {
  146. data.version = renderObject.bundle.version;
  147. }
  148. if ( data.material.transmission > 0 ) {
  149. const { width, height } = renderObject.context;
  150. data.bufferWidth = width;
  151. data.bufferHeight = height;
  152. }
  153. this.renderObjects.set( renderObject, data );
  154. }
  155. return data;
  156. }
  157. /**
  158. * Returns an attribute data structure holding the attributes versions for
  159. * monitoring.
  160. *
  161. * @param {Object} attributes - The geometry attributes.
  162. * @return {Object} An object for monitoring the versions of attributes.
  163. */
  164. getAttributesData( attributes ) {
  165. const attributesData = {};
  166. for ( const name in attributes ) {
  167. const attribute = attributes[ name ];
  168. attributesData[ name ] = {
  169. version: attribute.version
  170. };
  171. }
  172. return attributesData;
  173. }
  174. /**
  175. * Returns `true` if the node builder's material uses
  176. * node properties.
  177. *
  178. * @param {NodeBuilder} builder - The current node builder.
  179. * @return {boolean} Whether the node builder's material uses node properties or not.
  180. */
  181. containsNode( builder ) {
  182. const material = builder.material;
  183. for ( const property in material ) {
  184. if ( material[ property ] && material[ property ].isNode )
  185. return true;
  186. }
  187. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  188. return true;
  189. return false;
  190. }
  191. /**
  192. * Returns a material data structure holding the material property values for
  193. * monitoring.
  194. *
  195. * @param {Material} material - The material.
  196. * @return {Object} An object for monitoring material properties.
  197. */
  198. getMaterialData( material ) {
  199. const data = {};
  200. for ( const property of this.refreshUniforms ) {
  201. const value = material[ property ];
  202. if ( value === null || value === undefined ) continue;
  203. if ( typeof value === 'object' && value.clone !== undefined ) {
  204. if ( value.isTexture === true ) {
  205. data[ property ] = { id: value.id, version: value.version };
  206. } else {
  207. data[ property ] = value.clone();
  208. }
  209. } else {
  210. data[ property ] = value;
  211. }
  212. }
  213. return data;
  214. }
  215. /**
  216. * Returns `true` if the given render object has not changed its state.
  217. *
  218. * @param {RenderObject} renderObject - The render object.
  219. * @return {boolean} Whether the given render object has changed its state or not.
  220. */
  221. equals( renderObject ) {
  222. const { object, material, geometry } = renderObject;
  223. const renderObjectData = this.getRenderObjectData( renderObject );
  224. // world matrix
  225. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  226. renderObjectData.worldMatrix.copy( object.matrixWorld );
  227. return false;
  228. }
  229. // material
  230. const materialData = renderObjectData.material;
  231. for ( const property in materialData ) {
  232. const value = materialData[ property ];
  233. const mtlValue = material[ property ];
  234. if ( value.equals !== undefined ) {
  235. if ( value.equals( mtlValue ) === false ) {
  236. value.copy( mtlValue );
  237. return false;
  238. }
  239. } else if ( mtlValue.isTexture === true ) {
  240. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  241. value.id = mtlValue.id;
  242. value.version = mtlValue.version;
  243. return false;
  244. }
  245. } else if ( value !== mtlValue ) {
  246. materialData[ property ] = mtlValue;
  247. return false;
  248. }
  249. }
  250. if ( materialData.transmission > 0 ) {
  251. const { width, height } = renderObject.context;
  252. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  253. renderObjectData.bufferWidth = width;
  254. renderObjectData.bufferHeight = height;
  255. return false;
  256. }
  257. }
  258. // geometry
  259. const storedGeometryData = renderObjectData.geometry;
  260. const attributes = geometry.attributes;
  261. const storedAttributes = storedGeometryData.attributes;
  262. const storedAttributeNames = Object.keys( storedAttributes );
  263. const currentAttributeNames = Object.keys( attributes );
  264. if ( storedGeometryData.id !== geometry.id ) {
  265. storedGeometryData.id = geometry.id;
  266. return false;
  267. }
  268. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  269. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  270. return false;
  271. }
  272. // compare each attribute
  273. for ( const name of storedAttributeNames ) {
  274. const storedAttributeData = storedAttributes[ name ];
  275. const attribute = attributes[ name ];
  276. if ( attribute === undefined ) {
  277. // attribute was removed
  278. delete storedAttributes[ name ];
  279. return false;
  280. }
  281. if ( storedAttributeData.version !== attribute.version ) {
  282. storedAttributeData.version = attribute.version;
  283. return false;
  284. }
  285. }
  286. // check index
  287. const index = geometry.index;
  288. const storedIndexVersion = storedGeometryData.indexVersion;
  289. const currentIndexVersion = index ? index.version : null;
  290. if ( storedIndexVersion !== currentIndexVersion ) {
  291. storedGeometryData.indexVersion = currentIndexVersion;
  292. return false;
  293. }
  294. // check drawRange
  295. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  296. storedGeometryData.drawRange.start = geometry.drawRange.start;
  297. storedGeometryData.drawRange.count = geometry.drawRange.count;
  298. return false;
  299. }
  300. // morph targets
  301. if ( renderObjectData.morphTargetInfluences ) {
  302. let morphChanged = false;
  303. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  304. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  305. morphChanged = true;
  306. }
  307. }
  308. if ( morphChanged ) return true;
  309. }
  310. // center
  311. if ( renderObjectData.center ) {
  312. if ( renderObjectData.center.equals( object.center ) === false ) {
  313. renderObjectData.center.copy( object.center );
  314. return true;
  315. }
  316. }
  317. // bundle
  318. if ( renderObject.bundle !== null ) {
  319. renderObjectData.version = renderObject.bundle.version;
  320. }
  321. return true;
  322. }
  323. /**
  324. * Checks if the given render object requires a refresh.
  325. *
  326. * @param {RenderObject} renderObject - The render object.
  327. * @param {NodeFrame} nodeFrame - The current node frame.
  328. * @return {boolean} Whether the given render object requires a refresh or not.
  329. */
  330. needsRefresh( renderObject, nodeFrame ) {
  331. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  332. return true;
  333. const { renderId } = nodeFrame;
  334. if ( this.renderId !== renderId ) {
  335. this.renderId = renderId;
  336. return true;
  337. }
  338. const isStatic = renderObject.object.static === true;
  339. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  340. if ( isStatic || isBundle )
  341. return false;
  342. const notEqual = this.equals( renderObject ) !== true;
  343. return notEqual;
  344. }
  345. }
  346. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  347. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  348. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  349. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  350. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  351. function cyrb53( value, seed = 0 ) {
  352. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  353. if ( value instanceof Array ) {
  354. for ( let i = 0, val; i < value.length; i ++ ) {
  355. val = value[ i ];
  356. h1 = Math.imul( h1 ^ val, 2654435761 );
  357. h2 = Math.imul( h2 ^ val, 1597334677 );
  358. }
  359. } else {
  360. for ( let i = 0, ch; i < value.length; i ++ ) {
  361. ch = value.charCodeAt( i );
  362. h1 = Math.imul( h1 ^ ch, 2654435761 );
  363. h2 = Math.imul( h2 ^ ch, 1597334677 );
  364. }
  365. }
  366. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  367. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  368. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  369. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  370. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  371. }
  372. /**
  373. * Computes a hash for the given string.
  374. *
  375. * @method
  376. * @param {string} str - The string to be hashed.
  377. * @return {number} The hash.
  378. */
  379. const hashString = ( str ) => cyrb53( str );
  380. /**
  381. * Computes a hash for the given array.
  382. *
  383. * @method
  384. * @param {Array<number>} array - The array to be hashed.
  385. * @return {number} The hash.
  386. */
  387. const hashArray = ( array ) => cyrb53( array );
  388. /**
  389. * Computes a hash for the given list of parameters.
  390. *
  391. * @method
  392. * @param {...number} params - A list of parameters.
  393. * @return {number} The hash.
  394. */
  395. const hash$1 = ( ...params ) => cyrb53( params );
  396. /**
  397. * Computes a cache key for the given node.
  398. *
  399. * @method
  400. * @param {Object|Node} object - The object to be hashed.
  401. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  402. * @return {number} The hash.
  403. */
  404. function getCacheKey$1( object, force = false ) {
  405. const values = [];
  406. if ( object.isNode === true ) {
  407. values.push( object.id );
  408. object = object.getSelf();
  409. }
  410. for ( const { property, childNode } of getNodeChildren( object ) ) {
  411. values.push( cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  412. }
  413. return cyrb53( values );
  414. }
  415. /**
  416. * This generator function can be used to iterate over the node children
  417. * of the given object.
  418. *
  419. * @generator
  420. * @param {Object} node - The object to be hashed.
  421. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  422. * @yields {Object} A result node holding the property, index (if available) and the child node.
  423. */
  424. function* getNodeChildren( node, toJSON = false ) {
  425. for ( const property in node ) {
  426. // Ignore private properties.
  427. if ( property.startsWith( '_' ) === true ) continue;
  428. const object = node[ property ];
  429. if ( Array.isArray( object ) === true ) {
  430. for ( let i = 0; i < object.length; i ++ ) {
  431. const child = object[ i ];
  432. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  433. yield { property, index: i, childNode: child };
  434. }
  435. }
  436. } else if ( object && object.isNode === true ) {
  437. yield { property, childNode: object };
  438. } else if ( typeof object === 'object' ) {
  439. for ( const subProperty in object ) {
  440. const child = object[ subProperty ];
  441. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  442. yield { property, index: subProperty, childNode: child };
  443. }
  444. }
  445. }
  446. }
  447. }
  448. const typeFromLength = /*@__PURE__*/ new Map( [
  449. [ 1, 'float' ],
  450. [ 2, 'vec2' ],
  451. [ 3, 'vec3' ],
  452. [ 4, 'vec4' ],
  453. [ 9, 'mat3' ],
  454. [ 16, 'mat4' ]
  455. ] );
  456. const dataFromObject = /*@__PURE__*/ new WeakMap();
  457. /**
  458. * Returns the data type for the given the length.
  459. *
  460. * @method
  461. * @param {number} length - The length.
  462. * @return {string} The data type.
  463. */
  464. function getTypeFromLength( length ) {
  465. return typeFromLength.get( length );
  466. }
  467. /**
  468. * Returns the typed array for the given data type.
  469. *
  470. * @method
  471. * @param {string} type - The data type.
  472. * @return {TypedArray} The typed array.
  473. */
  474. function getTypedArrayFromType( type ) {
  475. // Handle component type for vectors and matrices
  476. if ( /[iu]?vec\d/.test( type ) ) {
  477. // Handle int vectors
  478. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  479. // Handle uint vectors
  480. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  481. // Default to float vectors
  482. return Float32Array;
  483. }
  484. // Handle matrices (always float)
  485. if ( /mat\d/.test( type ) ) return Float32Array;
  486. // Basic types
  487. if ( /float/.test( type ) ) return Float32Array;
  488. if ( /uint/.test( type ) ) return Uint32Array;
  489. if ( /int/.test( type ) ) return Int32Array;
  490. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  491. }
  492. /**
  493. * Returns the length for the given data type.
  494. *
  495. * @method
  496. * @param {string} type - The data type.
  497. * @return {number} The length.
  498. */
  499. function getLengthFromType( type ) {
  500. if ( /float|int|uint/.test( type ) ) return 1;
  501. if ( /vec2/.test( type ) ) return 2;
  502. if ( /vec3/.test( type ) ) return 3;
  503. if ( /vec4/.test( type ) ) return 4;
  504. if ( /mat2/.test( type ) ) return 4;
  505. if ( /mat3/.test( type ) ) return 9;
  506. if ( /mat4/.test( type ) ) return 16;
  507. console.error( 'THREE.TSL: Unsupported type:', type );
  508. }
  509. /**
  510. * Returns the data type for the given value.
  511. *
  512. * @method
  513. * @param {any} value - The value.
  514. * @return {?string} The data type.
  515. */
  516. function getValueType( value ) {
  517. if ( value === undefined || value === null ) return null;
  518. const typeOf = typeof value;
  519. if ( value.isNode === true ) {
  520. return 'node';
  521. } else if ( typeOf === 'number' ) {
  522. return 'float';
  523. } else if ( typeOf === 'boolean' ) {
  524. return 'bool';
  525. } else if ( typeOf === 'string' ) {
  526. return 'string';
  527. } else if ( typeOf === 'function' ) {
  528. return 'shader';
  529. } else if ( value.isVector2 === true ) {
  530. return 'vec2';
  531. } else if ( value.isVector3 === true ) {
  532. return 'vec3';
  533. } else if ( value.isVector4 === true ) {
  534. return 'vec4';
  535. } else if ( value.isMatrix2 === true ) {
  536. return 'mat2';
  537. } else if ( value.isMatrix3 === true ) {
  538. return 'mat3';
  539. } else if ( value.isMatrix4 === true ) {
  540. return 'mat4';
  541. } else if ( value.isColor === true ) {
  542. return 'color';
  543. } else if ( value instanceof ArrayBuffer ) {
  544. return 'ArrayBuffer';
  545. }
  546. return null;
  547. }
  548. /**
  549. * Returns the value/object for the given data type and parameters.
  550. *
  551. * @method
  552. * @param {string} type - The given type.
  553. * @param {...any} params - A parameter list.
  554. * @return {any} The value/object.
  555. */
  556. function getValueFromType( type, ...params ) {
  557. const last4 = type ? type.slice( - 4 ) : undefined;
  558. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  559. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  560. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  561. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  562. }
  563. if ( type === 'color' ) {
  564. return new Color( ...params );
  565. } else if ( last4 === 'vec2' ) {
  566. return new Vector2( ...params );
  567. } else if ( last4 === 'vec3' ) {
  568. return new Vector3( ...params );
  569. } else if ( last4 === 'vec4' ) {
  570. return new Vector4( ...params );
  571. } else if ( last4 === 'mat2' ) {
  572. return new Matrix2( ...params );
  573. } else if ( last4 === 'mat3' ) {
  574. return new Matrix3( ...params );
  575. } else if ( last4 === 'mat4' ) {
  576. return new Matrix4( ...params );
  577. } else if ( type === 'bool' ) {
  578. return params[ 0 ] || false;
  579. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  580. return params[ 0 ] || 0;
  581. } else if ( type === 'string' ) {
  582. return params[ 0 ] || '';
  583. } else if ( type === 'ArrayBuffer' ) {
  584. return base64ToArrayBuffer( params[ 0 ] );
  585. }
  586. return null;
  587. }
  588. /**
  589. * Gets the object data that can be shared between different rendering steps.
  590. *
  591. * @param {Object} object - The object to get the data for.
  592. * @return {Object} The object data.
  593. */
  594. function getDataFromObject( object ) {
  595. let data = dataFromObject.get( object );
  596. if ( data === undefined ) {
  597. data = {};
  598. dataFromObject.set( object, data );
  599. }
  600. return data;
  601. }
  602. /**
  603. * Converts the given array buffer to a Base64 string.
  604. *
  605. * @method
  606. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  607. * @return {string} The Base64 string.
  608. */
  609. function arrayBufferToBase64( arrayBuffer ) {
  610. let chars = '';
  611. const array = new Uint8Array( arrayBuffer );
  612. for ( let i = 0; i < array.length; i ++ ) {
  613. chars += String.fromCharCode( array[ i ] );
  614. }
  615. return btoa( chars );
  616. }
  617. /**
  618. * Converts the given Base64 string to an array buffer.
  619. *
  620. * @method
  621. * @param {string} base64 - The Base64 string.
  622. * @return {ArrayBuffer} The array buffer.
  623. */
  624. function base64ToArrayBuffer( base64 ) {
  625. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  626. }
  627. var NodeUtils = /*#__PURE__*/Object.freeze({
  628. __proto__: null,
  629. arrayBufferToBase64: arrayBufferToBase64,
  630. base64ToArrayBuffer: base64ToArrayBuffer,
  631. getCacheKey: getCacheKey$1,
  632. getDataFromObject: getDataFromObject,
  633. getLengthFromType: getLengthFromType,
  634. getNodeChildren: getNodeChildren,
  635. getTypeFromLength: getTypeFromLength,
  636. getTypedArrayFromType: getTypedArrayFromType,
  637. getValueFromType: getValueFromType,
  638. getValueType: getValueType,
  639. hash: hash$1,
  640. hashArray: hashArray,
  641. hashString: hashString
  642. });
  643. /**
  644. * Possible shader stages.
  645. *
  646. * @property {string} VERTEX The vertex shader stage.
  647. * @property {string} FRAGMENT The fragment shader stage.
  648. */
  649. const NodeShaderStage = {
  650. VERTEX: 'vertex',
  651. FRAGMENT: 'fragment'
  652. };
  653. /**
  654. * Update types of a node.
  655. *
  656. * @property {string} NONE The update method is not executed.
  657. * @property {string} FRAME The update method is executed per frame.
  658. * @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.
  659. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  660. */
  661. const NodeUpdateType = {
  662. NONE: 'none',
  663. FRAME: 'frame',
  664. RENDER: 'render',
  665. OBJECT: 'object'
  666. };
  667. /**
  668. * Data types of a node.
  669. *
  670. * @property {string} BOOLEAN Boolean type.
  671. * @property {string} INTEGER Integer type.
  672. * @property {string} FLOAT Float type.
  673. * @property {string} VECTOR2 Two-dimensional vector type.
  674. * @property {string} VECTOR3 Three-dimensional vector type.
  675. * @property {string} VECTOR4 Four-dimensional vector type.
  676. * @property {string} MATRIX2 2x2 matrix type.
  677. * @property {string} MATRIX3 3x3 matrix type.
  678. * @property {string} MATRIX4 4x4 matrix type.
  679. */
  680. const NodeType = {
  681. BOOLEAN: 'bool',
  682. INTEGER: 'int',
  683. FLOAT: 'float',
  684. VECTOR2: 'vec2',
  685. VECTOR3: 'vec3',
  686. VECTOR4: 'vec4',
  687. MATRIX2: 'mat2',
  688. MATRIX3: 'mat3',
  689. MATRIX4: 'mat4'
  690. };
  691. /**
  692. * Access types of a node. These are relevant for compute and storage usage.
  693. *
  694. * @property {string} READ_ONLY Read-only access
  695. * @property {string} WRITE_ONLY Write-only access.
  696. * @property {string} READ_WRITE Read and write access.
  697. */
  698. const NodeAccess = {
  699. READ_ONLY: 'readOnly',
  700. WRITE_ONLY: 'writeOnly',
  701. READ_WRITE: 'readWrite',
  702. };
  703. const defaultShaderStages = [ 'fragment', 'vertex' ];
  704. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  705. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  706. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  707. let _nodeId = 0;
  708. /**
  709. * Base class for all nodes.
  710. *
  711. * @augments EventDispatcher
  712. */
  713. class Node extends EventDispatcher {
  714. static get type() {
  715. return 'Node';
  716. }
  717. /**
  718. * Constructs a new node.
  719. *
  720. * @param {?string} nodeType - The node type.
  721. */
  722. constructor( nodeType = null ) {
  723. super();
  724. /**
  725. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  726. *
  727. * @type {?string}
  728. * @default null
  729. */
  730. this.nodeType = nodeType;
  731. /**
  732. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  733. *
  734. * @type {string}
  735. * @default 'none'
  736. */
  737. this.updateType = NodeUpdateType.NONE;
  738. /**
  739. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  740. *
  741. * @type {string}
  742. * @default 'none'
  743. */
  744. this.updateBeforeType = NodeUpdateType.NONE;
  745. /**
  746. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  747. *
  748. * @type {string}
  749. * @default 'none'
  750. */
  751. this.updateAfterType = NodeUpdateType.NONE;
  752. /**
  753. * The UUID of the node.
  754. *
  755. * @type {string}
  756. * @readonly
  757. */
  758. this.uuid = MathUtils.generateUUID();
  759. /**
  760. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  761. *
  762. * @type {number}
  763. * @readonly
  764. * @default 0
  765. */
  766. this.version = 0;
  767. /**
  768. * Whether this node is global or not. This property is relevant for the internal
  769. * node caching system. All nodes which should be declared just once should
  770. * set this flag to `true` (a typical example is {@link AttributeNode}).
  771. *
  772. * @type {boolean}
  773. * @default false
  774. */
  775. this.global = false;
  776. /**
  777. * This flag can be used for type testing.
  778. *
  779. * @type {boolean}
  780. * @readonly
  781. * @default true
  782. */
  783. this.isNode = true;
  784. // private
  785. /**
  786. * The cache key of this node.
  787. *
  788. * @private
  789. * @type {?number}
  790. * @default null
  791. */
  792. this._cacheKey = null;
  793. /**
  794. * The cache key 's version.
  795. *
  796. * @private
  797. * @type {number}
  798. * @default 0
  799. */
  800. this._cacheKeyVersion = 0;
  801. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  802. }
  803. /**
  804. * Set this property to `true` when the node should be regenerated.
  805. *
  806. * @type {boolean}
  807. * @default false
  808. * @param {boolean} value
  809. */
  810. set needsUpdate( value ) {
  811. if ( value === true ) {
  812. this.version ++;
  813. }
  814. }
  815. /**
  816. * The type of the class. The value is usually the constructor name.
  817. *
  818. * @type {string}
  819. * @readonly
  820. */
  821. get type() {
  822. return this.constructor.type;
  823. }
  824. /**
  825. * Convenient method for defining {@link Node#update}.
  826. *
  827. * @param {Function} callback - The update method.
  828. * @param {string} updateType - The update type.
  829. * @return {Node} A reference to this node.
  830. */
  831. onUpdate( callback, updateType ) {
  832. this.updateType = updateType;
  833. this.update = callback.bind( this.getSelf() );
  834. return this;
  835. }
  836. /**
  837. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  838. * this method automatically sets the update type to `FRAME`.
  839. *
  840. * @param {Function} callback - The update method.
  841. * @return {Node} A reference to this node.
  842. */
  843. onFrameUpdate( callback ) {
  844. return this.onUpdate( callback, NodeUpdateType.FRAME );
  845. }
  846. /**
  847. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  848. * this method automatically sets the update type to `RENDER`.
  849. *
  850. * @param {Function} callback - The update method.
  851. * @return {Node} A reference to this node.
  852. */
  853. onRenderUpdate( callback ) {
  854. return this.onUpdate( callback, NodeUpdateType.RENDER );
  855. }
  856. /**
  857. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  858. * this method automatically sets the update type to `OBJECT`.
  859. *
  860. * @param {Function} callback - The update method.
  861. * @return {Node} A reference to this node.
  862. */
  863. onObjectUpdate( callback ) {
  864. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  865. }
  866. /**
  867. * Convenient method for defining {@link Node#updateReference}.
  868. *
  869. * @param {Function} callback - The update method.
  870. * @return {Node} A reference to this node.
  871. */
  872. onReference( callback ) {
  873. this.updateReference = callback.bind( this.getSelf() );
  874. return this;
  875. }
  876. /**
  877. * The `this` reference might point to a Proxy so this method can be used
  878. * to get the reference to the actual node instance.
  879. *
  880. * @return {Node} A reference to the node.
  881. */
  882. getSelf() {
  883. // Returns non-node object.
  884. return this.self || this;
  885. }
  886. /**
  887. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  888. * to such objects based on a given state (e.g. the current node frame or builder).
  889. *
  890. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  891. * @return {any} The updated reference.
  892. */
  893. updateReference( /*state*/ ) {
  894. return this;
  895. }
  896. /**
  897. * By default this method returns the value of the {@link Node#global} flag. This method
  898. * can be overwritten in derived classes if an analytical way is required to determine the
  899. * global status.
  900. *
  901. * @param {NodeBuilder} builder - The current node builder.
  902. * @return {boolean} Whether this node is global or not.
  903. */
  904. isGlobal( /*builder*/ ) {
  905. return this.global;
  906. }
  907. /**
  908. * Generator function that can be used to iterate over the child nodes.
  909. *
  910. * @generator
  911. * @yields {Node} A child node.
  912. */
  913. * getChildren() {
  914. for ( const { childNode } of getNodeChildren( this ) ) {
  915. yield childNode;
  916. }
  917. }
  918. /**
  919. * Calling this method dispatches the `dispose` event. This event can be used
  920. * to register event listeners for clean up tasks.
  921. */
  922. dispose() {
  923. this.dispatchEvent( { type: 'dispose' } );
  924. }
  925. /**
  926. * Callback for {@link Node#traverse}.
  927. *
  928. * @callback traverseCallback
  929. * @param {Node} node - The current node.
  930. */
  931. /**
  932. * Can be used to traverse through the node's hierarchy.
  933. *
  934. * @param {traverseCallback} callback - A callback that is executed per node.
  935. */
  936. traverse( callback ) {
  937. callback( this );
  938. for ( const childNode of this.getChildren() ) {
  939. childNode.traverse( callback );
  940. }
  941. }
  942. /**
  943. * Returns the cache key for this node.
  944. *
  945. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  946. * @return {number} The cache key of the node.
  947. */
  948. getCacheKey( force = false ) {
  949. force = force || this.version !== this._cacheKeyVersion;
  950. if ( force === true || this._cacheKey === null ) {
  951. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  952. this._cacheKeyVersion = this.version;
  953. }
  954. return this._cacheKey;
  955. }
  956. /**
  957. * Generate a custom cache key for this node.
  958. *
  959. * @return {number} The cache key of the node.
  960. */
  961. customCacheKey() {
  962. return 0;
  963. }
  964. /**
  965. * Returns the references to this node which is by default `this`.
  966. *
  967. * @return {Node} A reference to this node.
  968. */
  969. getScope() {
  970. return this;
  971. }
  972. /**
  973. * Returns the hash of the node which is used to identify the node. By default it's
  974. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  975. * depending on their implementation.
  976. *
  977. * @param {NodeBuilder} builder - The current node builder.
  978. * @return {string} The hash.
  979. */
  980. getHash( /*builder*/ ) {
  981. return this.uuid;
  982. }
  983. /**
  984. * Returns the update type of {@link Node#update}.
  985. *
  986. * @return {NodeUpdateType} The update type.
  987. */
  988. getUpdateType() {
  989. return this.updateType;
  990. }
  991. /**
  992. * Returns the update type of {@link Node#updateBefore}.
  993. *
  994. * @return {NodeUpdateType} The update type.
  995. */
  996. getUpdateBeforeType() {
  997. return this.updateBeforeType;
  998. }
  999. /**
  1000. * Returns the update type of {@link Node#updateAfter}.
  1001. *
  1002. * @return {NodeUpdateType} The update type.
  1003. */
  1004. getUpdateAfterType() {
  1005. return this.updateAfterType;
  1006. }
  1007. /**
  1008. * Certain types are composed of multiple elements. For example a `vec3`
  1009. * is composed of three `float` values. This method returns the type of
  1010. * these elements.
  1011. *
  1012. * @param {NodeBuilder} builder - The current node builder.
  1013. * @return {string} The type of the node.
  1014. */
  1015. getElementType( builder ) {
  1016. const type = this.getNodeType( builder );
  1017. const elementType = builder.getElementType( type );
  1018. return elementType;
  1019. }
  1020. /**
  1021. * Returns the node member type for the given name.
  1022. *
  1023. * @param {NodeBuilder} builder - The current node builder.
  1024. * @param {string} name - The name of the member.
  1025. * @return {string} The type of the node.
  1026. */
  1027. getMemberType( /*builder, name*/ ) {
  1028. return 'void';
  1029. }
  1030. /**
  1031. * Returns the node's type.
  1032. *
  1033. * @param {NodeBuilder} builder - The current node builder.
  1034. * @return {string} The type of the node.
  1035. */
  1036. getNodeType( builder ) {
  1037. const nodeProperties = builder.getNodeProperties( this );
  1038. if ( nodeProperties.outputNode ) {
  1039. return nodeProperties.outputNode.getNodeType( builder );
  1040. }
  1041. return this.nodeType;
  1042. }
  1043. /**
  1044. * This method is used during the build process of a node and ensures
  1045. * equal nodes are not built multiple times but just once. For example if
  1046. * `attribute( 'uv' )` is used multiple times by the user, the build
  1047. * process makes sure to process just the first node.
  1048. *
  1049. * @param {NodeBuilder} builder - The current node builder.
  1050. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1051. */
  1052. getShared( builder ) {
  1053. const hash = this.getHash( builder );
  1054. const nodeFromHash = builder.getNodeFromHash( hash );
  1055. return nodeFromHash || this;
  1056. }
  1057. /**
  1058. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1059. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1060. * The output node must be returned in the `return` statement.
  1061. *
  1062. * @param {NodeBuilder} builder - The current node builder.
  1063. * @return {?Node} The output node.
  1064. */
  1065. setup( builder ) {
  1066. const nodeProperties = builder.getNodeProperties( this );
  1067. let index = 0;
  1068. for ( const childNode of this.getChildren() ) {
  1069. nodeProperties[ 'node' + index ++ ] = childNode;
  1070. }
  1071. // return a outputNode if exists or null
  1072. return nodeProperties.outputNode || null;
  1073. }
  1074. /**
  1075. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1076. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1077. *
  1078. * @param {NodeBuilder} builder - The current node builder.
  1079. */
  1080. analyze( builder ) {
  1081. const usageCount = builder.increaseUsage( this );
  1082. if ( usageCount === 1 ) {
  1083. // node flow children
  1084. const nodeProperties = builder.getNodeProperties( this );
  1085. for ( const childNode of Object.values( nodeProperties ) ) {
  1086. if ( childNode && childNode.isNode === true ) {
  1087. childNode.build( builder );
  1088. }
  1089. }
  1090. }
  1091. }
  1092. /**
  1093. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1094. * This state builds the output node and returns the resulting shader string.
  1095. *
  1096. * @param {NodeBuilder} builder - The current node builder.
  1097. * @param {?string} output - Can be used to define the output type.
  1098. * @return {?string} The generated shader string.
  1099. */
  1100. generate( builder, output ) {
  1101. const { outputNode } = builder.getNodeProperties( this );
  1102. if ( outputNode && outputNode.isNode === true ) {
  1103. return outputNode.build( builder, output );
  1104. }
  1105. }
  1106. /**
  1107. * The method can be implemented to update the node's internal state before it is used to render an object.
  1108. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1109. *
  1110. * @abstract
  1111. * @param {NodeFrame} frame - A reference to the current node frame.
  1112. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1113. */
  1114. updateBefore( /*frame*/ ) {
  1115. console.warn( 'Abstract function.' );
  1116. }
  1117. /**
  1118. * The method can be implemented to update the node's internal state after it was used to render an object.
  1119. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1120. *
  1121. * @abstract
  1122. * @param {NodeFrame} frame - A reference to the current node frame.
  1123. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1124. */
  1125. updateAfter( /*frame*/ ) {
  1126. console.warn( 'Abstract function.' );
  1127. }
  1128. /**
  1129. * The method can be implemented to update the node's internal state when it is used to render an object.
  1130. * The {@link Node#updateType} property defines how often the update is executed.
  1131. *
  1132. * @abstract
  1133. * @param {NodeFrame} frame - A reference to the current node frame.
  1134. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1135. */
  1136. update( /*frame*/ ) {
  1137. console.warn( 'Abstract function.' );
  1138. }
  1139. /**
  1140. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1141. * on the current build stage (setup, analyze or generate).
  1142. *
  1143. * @param {NodeBuilder} builder - The current node builder.
  1144. * @param {?string} output - Can be used to define the output type.
  1145. * @return {?string} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1146. */
  1147. build( builder, output = null ) {
  1148. const refNode = this.getShared( builder );
  1149. if ( this !== refNode ) {
  1150. return refNode.build( builder, output );
  1151. }
  1152. builder.addNode( this );
  1153. builder.addChain( this );
  1154. /* Build stages expected results:
  1155. - "setup" -> Node
  1156. - "analyze" -> null
  1157. - "generate" -> String
  1158. */
  1159. let result = null;
  1160. const buildStage = builder.getBuildStage();
  1161. if ( buildStage === 'setup' ) {
  1162. this.updateReference( builder );
  1163. const properties = builder.getNodeProperties( this );
  1164. if ( properties.initialized !== true ) {
  1165. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1166. properties.initialized = true;
  1167. const outputNode = this.setup( builder ); // return a node or null
  1168. const isNodeOutput = outputNode && outputNode.isNode === true;
  1169. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1170. // !! no outputNode !!
  1171. //outputNode = builder.stack;
  1172. }*/
  1173. for ( const childNode of Object.values( properties ) ) {
  1174. if ( childNode && childNode.isNode === true ) {
  1175. childNode.build( builder );
  1176. }
  1177. }
  1178. if ( isNodeOutput ) {
  1179. outputNode.build( builder );
  1180. }
  1181. properties.outputNode = outputNode;
  1182. }
  1183. } else if ( buildStage === 'analyze' ) {
  1184. this.analyze( builder );
  1185. } else if ( buildStage === 'generate' ) {
  1186. const isGenerateOnce = this.generate.length === 1;
  1187. if ( isGenerateOnce ) {
  1188. const type = this.getNodeType( builder );
  1189. const nodeData = builder.getDataFromNode( this );
  1190. result = nodeData.snippet;
  1191. if ( result === undefined ) {
  1192. result = this.generate( builder ) || '';
  1193. nodeData.snippet = result;
  1194. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1195. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1196. }
  1197. result = builder.format( result, type, output );
  1198. } else {
  1199. result = this.generate( builder, output ) || '';
  1200. }
  1201. }
  1202. builder.removeChain( this );
  1203. builder.addSequentialNode( this );
  1204. return result;
  1205. }
  1206. /**
  1207. * Returns the child nodes as a JSON object.
  1208. *
  1209. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1210. */
  1211. getSerializeChildren() {
  1212. return getNodeChildren( this );
  1213. }
  1214. /**
  1215. * Serializes the node to JSON.
  1216. *
  1217. * @param {Object} json - The output JSON object.
  1218. */
  1219. serialize( json ) {
  1220. const nodeChildren = this.getSerializeChildren();
  1221. const inputNodes = {};
  1222. for ( const { property, index, childNode } of nodeChildren ) {
  1223. if ( index !== undefined ) {
  1224. if ( inputNodes[ property ] === undefined ) {
  1225. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1226. }
  1227. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1228. } else {
  1229. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1230. }
  1231. }
  1232. if ( Object.keys( inputNodes ).length > 0 ) {
  1233. json.inputNodes = inputNodes;
  1234. }
  1235. }
  1236. /**
  1237. * Deserializes the node from the given JSON.
  1238. *
  1239. * @param {Object} json - The JSON object.
  1240. */
  1241. deserialize( json ) {
  1242. if ( json.inputNodes !== undefined ) {
  1243. const nodes = json.meta.nodes;
  1244. for ( const property in json.inputNodes ) {
  1245. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1246. const inputArray = [];
  1247. for ( const uuid of json.inputNodes[ property ] ) {
  1248. inputArray.push( nodes[ uuid ] );
  1249. }
  1250. this[ property ] = inputArray;
  1251. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1252. const inputObject = {};
  1253. for ( const subProperty in json.inputNodes[ property ] ) {
  1254. const uuid = json.inputNodes[ property ][ subProperty ];
  1255. inputObject[ subProperty ] = nodes[ uuid ];
  1256. }
  1257. this[ property ] = inputObject;
  1258. } else {
  1259. const uuid = json.inputNodes[ property ];
  1260. this[ property ] = nodes[ uuid ];
  1261. }
  1262. }
  1263. }
  1264. }
  1265. /**
  1266. * Serializes the node into the three.js JSON Object/Scene format.
  1267. *
  1268. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1269. * @return {Object} The serialized node.
  1270. */
  1271. toJSON( meta ) {
  1272. const { uuid, type } = this;
  1273. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1274. if ( isRoot ) {
  1275. meta = {
  1276. textures: {},
  1277. images: {},
  1278. nodes: {}
  1279. };
  1280. }
  1281. // serialize
  1282. let data = meta.nodes[ uuid ];
  1283. if ( data === undefined ) {
  1284. data = {
  1285. uuid,
  1286. type,
  1287. meta,
  1288. metadata: {
  1289. version: 4.6,
  1290. type: 'Node',
  1291. generator: 'Node.toJSON'
  1292. }
  1293. };
  1294. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1295. this.serialize( data );
  1296. delete data.meta;
  1297. }
  1298. // TODO: Copied from Object3D.toJSON
  1299. function extractFromCache( cache ) {
  1300. const values = [];
  1301. for ( const key in cache ) {
  1302. const data = cache[ key ];
  1303. delete data.metadata;
  1304. values.push( data );
  1305. }
  1306. return values;
  1307. }
  1308. if ( isRoot ) {
  1309. const textures = extractFromCache( meta.textures );
  1310. const images = extractFromCache( meta.images );
  1311. const nodes = extractFromCache( meta.nodes );
  1312. if ( textures.length > 0 ) data.textures = textures;
  1313. if ( images.length > 0 ) data.images = images;
  1314. if ( nodes.length > 0 ) data.nodes = nodes;
  1315. }
  1316. return data;
  1317. }
  1318. }
  1319. /**
  1320. * Base class for representing element access on an array-like
  1321. * node data structures.
  1322. *
  1323. * @augments Node
  1324. */
  1325. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1326. static get type() {
  1327. return 'ArrayElementNode';
  1328. }
  1329. /**
  1330. * Constructs an array element node.
  1331. *
  1332. * @param {Node} node - The array-like node.
  1333. * @param {Node} indexNode - The index node that defines the element access.
  1334. */
  1335. constructor( node, indexNode ) {
  1336. super();
  1337. /**
  1338. * The array-like node.
  1339. *
  1340. * @type {Node}
  1341. */
  1342. this.node = node;
  1343. /**
  1344. * The index node that defines the element access.
  1345. *
  1346. * @type {Node}
  1347. */
  1348. this.indexNode = indexNode;
  1349. /**
  1350. * This flag can be used for type testing.
  1351. *
  1352. * @type {boolean}
  1353. * @readonly
  1354. * @default true
  1355. */
  1356. this.isArrayElementNode = true;
  1357. }
  1358. /**
  1359. * This method is overwritten since the node type is inferred from the array-like node.
  1360. *
  1361. * @param {NodeBuilder} builder - The current node builder.
  1362. * @return {string} The node type.
  1363. */
  1364. getNodeType( builder ) {
  1365. return this.node.getElementType( builder );
  1366. }
  1367. generate( builder ) {
  1368. const indexType = this.indexNode.getNodeType( builder );
  1369. const nodeSnippet = this.node.build( builder );
  1370. const indexSnippet = this.indexNode.build( builder, indexType === 'int' ? indexType : 'uint' );
  1371. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1372. }
  1373. }
  1374. /**
  1375. * This module is part of the TSL core and usually not used in app level code.
  1376. * It represents a convert operation during the shader generation process
  1377. * meaning it converts the data type of a node to a target data type.
  1378. *
  1379. * @augments Node
  1380. */
  1381. class ConvertNode extends Node {
  1382. static get type() {
  1383. return 'ConvertNode';
  1384. }
  1385. /**
  1386. * Constructs a new convert node.
  1387. *
  1388. * @param {Node} node - The node which type should be converted.
  1389. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1390. */
  1391. constructor( node, convertTo ) {
  1392. super();
  1393. /**
  1394. * The node which type should be converted.
  1395. *
  1396. * @type {Node}
  1397. */
  1398. this.node = node;
  1399. /**
  1400. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1401. *
  1402. * @type {string}
  1403. */
  1404. this.convertTo = convertTo;
  1405. }
  1406. /**
  1407. * This method is overwritten since the implementation tries to infer the best
  1408. * matching type from the {@link ConvertNode#convertTo} property.
  1409. *
  1410. * @param {NodeBuilder} builder - The current node builder.
  1411. * @return {string} The node type.
  1412. */
  1413. getNodeType( builder ) {
  1414. const requestType = this.node.getNodeType( builder );
  1415. let convertTo = null;
  1416. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1417. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1418. convertTo = overloadingType;
  1419. }
  1420. }
  1421. return convertTo;
  1422. }
  1423. serialize( data ) {
  1424. super.serialize( data );
  1425. data.convertTo = this.convertTo;
  1426. }
  1427. deserialize( data ) {
  1428. super.deserialize( data );
  1429. this.convertTo = data.convertTo;
  1430. }
  1431. generate( builder, output ) {
  1432. const node = this.node;
  1433. const type = this.getNodeType( builder );
  1434. const snippet = node.build( builder, type );
  1435. return builder.format( snippet, type, output );
  1436. }
  1437. }
  1438. /**
  1439. * This module uses cache management to create temporary variables
  1440. * if the node is used more than once to prevent duplicate calculations.
  1441. *
  1442. * The class acts as a base class for many other nodes types.
  1443. *
  1444. * @augments Node
  1445. */
  1446. class TempNode extends Node {
  1447. static get type() {
  1448. return 'TempNode';
  1449. }
  1450. /**
  1451. * Constructs a temp node.
  1452. *
  1453. * @param {?string} nodeType - The node type.
  1454. */
  1455. constructor( nodeType = null ) {
  1456. super( nodeType );
  1457. /**
  1458. * This flag can be used for type testing.
  1459. *
  1460. * @type {boolean}
  1461. * @readonly
  1462. * @default true
  1463. */
  1464. this.isTempNode = true;
  1465. }
  1466. /**
  1467. * Whether this node is used more than once in context of other nodes.
  1468. *
  1469. * @param {NodeBuilder} builder - The node builder.
  1470. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1471. */
  1472. hasDependencies( builder ) {
  1473. return builder.getDataFromNode( this ).usageCount > 1;
  1474. }
  1475. build( builder, output ) {
  1476. const buildStage = builder.getBuildStage();
  1477. if ( buildStage === 'generate' ) {
  1478. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1479. const nodeData = builder.getDataFromNode( this );
  1480. if ( nodeData.propertyName !== undefined ) {
  1481. return builder.format( nodeData.propertyName, type, output );
  1482. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1483. const snippet = super.build( builder, type );
  1484. const nodeVar = builder.getVarFromNode( this, null, type );
  1485. const propertyName = builder.getPropertyName( nodeVar );
  1486. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1487. nodeData.snippet = snippet;
  1488. nodeData.propertyName = propertyName;
  1489. return builder.format( nodeData.propertyName, type, output );
  1490. }
  1491. }
  1492. return super.build( builder, output );
  1493. }
  1494. }
  1495. /**
  1496. * This module is part of the TSL core and usually not used in app level code.
  1497. * It represents a join operation during the shader generation process.
  1498. * For example in can compose/join two single floats into a `vec2` type.
  1499. *
  1500. * @augments TempNode
  1501. */
  1502. class JoinNode extends TempNode {
  1503. static get type() {
  1504. return 'JoinNode';
  1505. }
  1506. /**
  1507. * Constructs a new join node.
  1508. *
  1509. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1510. * @param {?string} [nodeType=null] - The node type.
  1511. */
  1512. constructor( nodes = [], nodeType = null ) {
  1513. super( nodeType );
  1514. /**
  1515. * An array of nodes that should be joined.
  1516. *
  1517. * @type {Array<Node>}
  1518. */
  1519. this.nodes = nodes;
  1520. }
  1521. /**
  1522. * This method is overwritten since the node type must be inferred from the
  1523. * joined data length if not explicitly defined.
  1524. *
  1525. * @param {NodeBuilder} builder - The current node builder.
  1526. * @return {string} The node type.
  1527. */
  1528. getNodeType( builder ) {
  1529. if ( this.nodeType !== null ) {
  1530. return builder.getVectorType( this.nodeType );
  1531. }
  1532. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1533. }
  1534. generate( builder, output ) {
  1535. const type = this.getNodeType( builder );
  1536. const nodes = this.nodes;
  1537. const primitiveType = builder.getComponentType( type );
  1538. const snippetValues = [];
  1539. for ( const input of nodes ) {
  1540. let inputSnippet = input.build( builder );
  1541. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1542. if ( inputPrimitiveType !== primitiveType ) {
  1543. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1544. }
  1545. snippetValues.push( inputSnippet );
  1546. }
  1547. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1548. return builder.format( snippet, type, output );
  1549. }
  1550. }
  1551. const _stringVectorComponents = vectorComponents.join( '' );
  1552. /**
  1553. * This module is part of the TSL core and usually not used in app level code.
  1554. * `SplitNode` represents a property access operation which means it is
  1555. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1556. * For example:
  1557. * ```js
  1558. * const redValue = color.r;
  1559. * ```
  1560. *
  1561. * @augments Node
  1562. */
  1563. class SplitNode extends Node {
  1564. static get type() {
  1565. return 'SplitNode';
  1566. }
  1567. /**
  1568. * Constructs a new split node.
  1569. *
  1570. * @param {Node} node - The node that should be accessed.
  1571. * @param {string} [components='x'] - The components that should be accessed.
  1572. */
  1573. constructor( node, components = 'x' ) {
  1574. super();
  1575. /**
  1576. * The node that should be accessed.
  1577. *
  1578. * @type {Node}
  1579. */
  1580. this.node = node;
  1581. /**
  1582. * The components that should be accessed.
  1583. *
  1584. * @type {string}
  1585. */
  1586. this.components = components;
  1587. /**
  1588. * This flag can be used for type testing.
  1589. *
  1590. * @type {boolean}
  1591. * @readonly
  1592. * @default true
  1593. */
  1594. this.isSplitNode = true;
  1595. }
  1596. /**
  1597. * Returns the vector length which is computed based on the requested components.
  1598. *
  1599. * @return {number} The vector length.
  1600. */
  1601. getVectorLength() {
  1602. let vectorLength = this.components.length;
  1603. for ( const c of this.components ) {
  1604. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1605. }
  1606. return vectorLength;
  1607. }
  1608. /**
  1609. * Returns the component type of the node's type.
  1610. *
  1611. * @param {NodeBuilder} builder - The current node builder.
  1612. * @return {string} The component type.
  1613. */
  1614. getComponentType( builder ) {
  1615. return builder.getComponentType( this.node.getNodeType( builder ) );
  1616. }
  1617. /**
  1618. * This method is overwritten since the node type is inferred from requested components.
  1619. *
  1620. * @param {NodeBuilder} builder - The current node builder.
  1621. * @return {string} The node type.
  1622. */
  1623. getNodeType( builder ) {
  1624. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1625. }
  1626. generate( builder, output ) {
  1627. const node = this.node;
  1628. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1629. let snippet = null;
  1630. if ( nodeTypeLength > 1 ) {
  1631. let type = null;
  1632. const componentsLength = this.getVectorLength();
  1633. if ( componentsLength >= nodeTypeLength ) {
  1634. // needed expand the input node
  1635. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1636. }
  1637. const nodeSnippet = node.build( builder, type );
  1638. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1639. // unnecessary swizzle
  1640. snippet = builder.format( nodeSnippet, type, output );
  1641. } else {
  1642. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1643. }
  1644. } else {
  1645. // ignore .components if .node returns float/integer
  1646. snippet = node.build( builder, output );
  1647. }
  1648. return snippet;
  1649. }
  1650. serialize( data ) {
  1651. super.serialize( data );
  1652. data.components = this.components;
  1653. }
  1654. deserialize( data ) {
  1655. super.deserialize( data );
  1656. this.components = data.components;
  1657. }
  1658. }
  1659. /**
  1660. * This module is part of the TSL core and usually not used in app level code.
  1661. * `SetNode` represents a set operation which means it is used to implement any
  1662. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1663. * For example:
  1664. * ```js
  1665. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1666. * ```
  1667. *
  1668. * @augments TempNode
  1669. */
  1670. class SetNode extends TempNode {
  1671. static get type() {
  1672. return 'SetNode';
  1673. }
  1674. /**
  1675. * Constructs a new set node.
  1676. *
  1677. * @param {Node} sourceNode - The node that should be updated.
  1678. * @param {string} components - The components that should be updated.
  1679. * @param {Node} targetNode - The value node.
  1680. */
  1681. constructor( sourceNode, components, targetNode ) {
  1682. super();
  1683. /**
  1684. * The node that should be updated.
  1685. *
  1686. * @type {Node}
  1687. */
  1688. this.sourceNode = sourceNode;
  1689. /**
  1690. * The components that should be updated.
  1691. *
  1692. * @type {string}
  1693. */
  1694. this.components = components;
  1695. /**
  1696. * The value node.
  1697. *
  1698. * @type {Node}
  1699. */
  1700. this.targetNode = targetNode;
  1701. }
  1702. /**
  1703. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1704. *
  1705. * @param {NodeBuilder} builder - The current node builder.
  1706. * @return {string} The node type.
  1707. */
  1708. getNodeType( builder ) {
  1709. return this.sourceNode.getNodeType( builder );
  1710. }
  1711. generate( builder ) {
  1712. const { sourceNode, components, targetNode } = this;
  1713. const sourceType = this.getNodeType( builder );
  1714. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1715. const targetType = builder.getTypeFromLength( components.length, componentType );
  1716. const targetSnippet = targetNode.build( builder, targetType );
  1717. const sourceSnippet = sourceNode.build( builder, sourceType );
  1718. const length = builder.getTypeLength( sourceType );
  1719. const snippetValues = [];
  1720. for ( let i = 0; i < length; i ++ ) {
  1721. const component = vectorComponents[ i ];
  1722. if ( component === components[ 0 ] ) {
  1723. snippetValues.push( targetSnippet );
  1724. i += components.length - 1;
  1725. } else {
  1726. snippetValues.push( sourceSnippet + '.' + component );
  1727. }
  1728. }
  1729. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1730. }
  1731. }
  1732. /**
  1733. * This module is part of the TSL core and usually not used in app level code.
  1734. * It represents a flip operation during the shader generation process
  1735. * meaning it flips normalized values with the following formula:
  1736. * ```
  1737. * x = 1 - x;
  1738. * ```
  1739. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1740. * `flipSTPQ()` method invocations on node objects. For example:
  1741. * ```js
  1742. * uvNode = uvNode.flipY();
  1743. * ```
  1744. *
  1745. * @augments TempNode
  1746. */
  1747. class FlipNode extends TempNode {
  1748. static get type() {
  1749. return 'FlipNode';
  1750. }
  1751. /**
  1752. * Constructs a new flip node.
  1753. *
  1754. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1755. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1756. */
  1757. constructor( sourceNode, components ) {
  1758. super();
  1759. /**
  1760. * The node which component(s) should be flipped.
  1761. *
  1762. * @type {Node}
  1763. */
  1764. this.sourceNode = sourceNode;
  1765. /**
  1766. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1767. *
  1768. * @type {string}
  1769. */
  1770. this.components = components;
  1771. }
  1772. /**
  1773. * This method is overwritten since the node type is inferred from the source node.
  1774. *
  1775. * @param {NodeBuilder} builder - The current node builder.
  1776. * @return {string} The node type.
  1777. */
  1778. getNodeType( builder ) {
  1779. return this.sourceNode.getNodeType( builder );
  1780. }
  1781. generate( builder ) {
  1782. const { components, sourceNode } = this;
  1783. const sourceType = this.getNodeType( builder );
  1784. const sourceSnippet = sourceNode.build( builder );
  1785. const sourceCache = builder.getVarFromNode( this );
  1786. const sourceProperty = builder.getPropertyName( sourceCache );
  1787. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1788. const length = builder.getTypeLength( sourceType );
  1789. const snippetValues = [];
  1790. let componentIndex = 0;
  1791. for ( let i = 0; i < length; i ++ ) {
  1792. const component = vectorComponents[ i ];
  1793. if ( component === components[ componentIndex ] ) {
  1794. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1795. componentIndex ++;
  1796. } else {
  1797. snippetValues.push( sourceProperty + '.' + component );
  1798. }
  1799. }
  1800. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1801. }
  1802. }
  1803. /**
  1804. * Base class for representing data input nodes.
  1805. *
  1806. * @augments Node
  1807. */
  1808. class InputNode extends Node {
  1809. static get type() {
  1810. return 'InputNode';
  1811. }
  1812. /**
  1813. * Constructs a new input node.
  1814. *
  1815. * @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).
  1816. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1817. */
  1818. constructor( value, nodeType = null ) {
  1819. super( nodeType );
  1820. /**
  1821. * This flag can be used for type testing.
  1822. *
  1823. * @type {boolean}
  1824. * @readonly
  1825. * @default true
  1826. */
  1827. this.isInputNode = true;
  1828. /**
  1829. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1830. *
  1831. * @type {any}
  1832. */
  1833. this.value = value;
  1834. /**
  1835. * The precision of the value in the shader.
  1836. *
  1837. * @type {?('low'|'medium'|'high')}
  1838. * @default null
  1839. */
  1840. this.precision = null;
  1841. }
  1842. getNodeType( /*builder*/ ) {
  1843. if ( this.nodeType === null ) {
  1844. return getValueType( this.value );
  1845. }
  1846. return this.nodeType;
  1847. }
  1848. /**
  1849. * Returns the input type of the node which is by default the node type. Derived modules
  1850. * might overwrite this method and use a fixed type or compute one analytically.
  1851. *
  1852. * A typical example for different input and node types are textures. The input type of a
  1853. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1854. *
  1855. * @param {NodeBuilder} builder - The current node builder.
  1856. * @return {string} The input type.
  1857. */
  1858. getInputType( builder ) {
  1859. return this.getNodeType( builder );
  1860. }
  1861. /**
  1862. * Sets the precision to the given value. The method can be
  1863. * overwritten in derived classes if the final precision must be computed
  1864. * analytically.
  1865. *
  1866. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1867. * @return {InputNode} A reference to this node.
  1868. */
  1869. setPrecision( precision ) {
  1870. this.precision = precision;
  1871. return this;
  1872. }
  1873. serialize( data ) {
  1874. super.serialize( data );
  1875. data.value = this.value;
  1876. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1877. data.valueType = getValueType( this.value );
  1878. data.nodeType = this.nodeType;
  1879. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1880. data.precision = this.precision;
  1881. }
  1882. deserialize( data ) {
  1883. super.deserialize( data );
  1884. this.nodeType = data.nodeType;
  1885. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1886. this.precision = data.precision || null;
  1887. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1888. }
  1889. generate( /*builder, output*/ ) {
  1890. console.warn( 'Abstract function.' );
  1891. }
  1892. }
  1893. const _regNum = /float|u?int/;
  1894. /**
  1895. * Class for representing a constant value in the shader.
  1896. *
  1897. * @augments InputNode
  1898. */
  1899. class ConstNode extends InputNode {
  1900. static get type() {
  1901. return 'ConstNode';
  1902. }
  1903. /**
  1904. * Constructs a new input node.
  1905. *
  1906. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1907. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1908. */
  1909. constructor( value, nodeType = null ) {
  1910. super( value, nodeType );
  1911. /**
  1912. * This flag can be used for type testing.
  1913. *
  1914. * @type {boolean}
  1915. * @readonly
  1916. * @default true
  1917. */
  1918. this.isConstNode = true;
  1919. }
  1920. /**
  1921. * Generates the shader string of the value with the current node builder.
  1922. *
  1923. * @param {NodeBuilder} builder - The current node builder.
  1924. * @return {string} The generated value as a shader string.
  1925. */
  1926. generateConst( builder ) {
  1927. return builder.generateConst( this.getNodeType( builder ), this.value );
  1928. }
  1929. generate( builder, output ) {
  1930. const type = this.getNodeType( builder );
  1931. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  1932. return builder.generateConst( output, this.value );
  1933. }
  1934. return builder.format( this.generateConst( builder ), type, output );
  1935. }
  1936. }
  1937. /**
  1938. * Base class for representing member access on an object-like
  1939. * node data structures.
  1940. *
  1941. * @augments Node
  1942. */
  1943. class MemberNode extends Node {
  1944. static get type() {
  1945. return 'MemberNode';
  1946. }
  1947. /**
  1948. * Constructs an array element node.
  1949. *
  1950. * @param {Node} node - The array-like node.
  1951. * @param {string} property - The property name.
  1952. */
  1953. constructor( node, property ) {
  1954. super();
  1955. /**
  1956. * The array-like node.
  1957. *
  1958. * @type {Node}
  1959. */
  1960. this.node = node;
  1961. /**
  1962. * The property name.
  1963. *
  1964. * @type {Node}
  1965. */
  1966. this.property = property;
  1967. /**
  1968. * This flag can be used for type testing.
  1969. *
  1970. * @type {boolean}
  1971. * @readonly
  1972. * @default true
  1973. */
  1974. this.isMemberNode = true;
  1975. }
  1976. getNodeType( builder ) {
  1977. return this.node.getMemberType( builder, this.property );
  1978. }
  1979. generate( builder ) {
  1980. const propertyName = this.node.build( builder );
  1981. return propertyName + '.' + this.property;
  1982. }
  1983. }
  1984. let currentStack = null;
  1985. const NodeElements = new Map();
  1986. function addMethodChaining( name, nodeElement ) {
  1987. if ( NodeElements.has( name ) ) {
  1988. console.warn( `Redefinition of method chaining ${ name }` );
  1989. return;
  1990. }
  1991. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1992. NodeElements.set( name, nodeElement );
  1993. }
  1994. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1995. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1996. const shaderNodeHandler = {
  1997. setup( NodeClosure, params ) {
  1998. const inputs = params.shift();
  1999. return NodeClosure( nodeObjects( inputs ), ...params );
  2000. },
  2001. get( node, prop, nodeObj ) {
  2002. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2003. if ( node.isStackNode !== true && prop === 'assign' ) {
  2004. return ( ...params ) => {
  2005. currentStack.assign( nodeObj, ...params );
  2006. return nodeObj;
  2007. };
  2008. } else if ( NodeElements.has( prop ) ) {
  2009. const nodeElement = NodeElements.get( prop );
  2010. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2011. } else if ( prop === 'self' ) {
  2012. return node;
  2013. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2014. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2015. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2016. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2017. // accessing properties ( swizzle )
  2018. prop = parseSwizzle( prop );
  2019. return nodeObject( new SplitNode( nodeObj, prop ) );
  2020. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2021. // set properties ( swizzle ) and sort to xyzw sequence
  2022. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2023. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  2024. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2025. // set properties ( swizzle ) and sort to xyzw sequence
  2026. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2027. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2028. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2029. // accessing property
  2030. if ( prop === 'width' ) prop = 'x';
  2031. else if ( prop === 'height' ) prop = 'y';
  2032. else if ( prop === 'depth' ) prop = 'z';
  2033. return nodeObject( new SplitNode( node, prop ) );
  2034. } else if ( /^\d+$/.test( prop ) === true ) {
  2035. // accessing array
  2036. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2037. } else if ( /^get$/.test( prop ) === true ) {
  2038. // accessing properties
  2039. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2040. }
  2041. }
  2042. return Reflect.get( node, prop, nodeObj );
  2043. },
  2044. set( node, prop, value, nodeObj ) {
  2045. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2046. // setting properties
  2047. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2048. nodeObj[ prop ].assign( value );
  2049. return true;
  2050. }
  2051. }
  2052. return Reflect.set( node, prop, value, nodeObj );
  2053. }
  2054. };
  2055. const nodeObjectsCacheMap = new WeakMap();
  2056. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2057. const ShaderNodeObject = function ( obj, altType = null ) {
  2058. const type = getValueType( obj );
  2059. if ( type === 'node' ) {
  2060. let nodeObject = nodeObjectsCacheMap.get( obj );
  2061. if ( nodeObject === undefined ) {
  2062. nodeObject = new Proxy( obj, shaderNodeHandler );
  2063. nodeObjectsCacheMap.set( obj, nodeObject );
  2064. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2065. }
  2066. return nodeObject;
  2067. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2068. return nodeObject( getConstNode( obj, altType ) );
  2069. } else if ( type === 'shader' ) {
  2070. return Fn( obj );
  2071. }
  2072. return obj;
  2073. };
  2074. const ShaderNodeObjects = function ( objects, altType = null ) {
  2075. for ( const name in objects ) {
  2076. objects[ name ] = nodeObject( objects[ name ], altType );
  2077. }
  2078. return objects;
  2079. };
  2080. const ShaderNodeArray = function ( array, altType = null ) {
  2081. const len = array.length;
  2082. for ( let i = 0; i < len; i ++ ) {
  2083. array[ i ] = nodeObject( array[ i ], altType );
  2084. }
  2085. return array;
  2086. };
  2087. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2088. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2089. if ( scope === null ) {
  2090. return ( ...params ) => {
  2091. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2092. };
  2093. } else if ( factor !== null ) {
  2094. factor = nodeObject( factor );
  2095. return ( ...params ) => {
  2096. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2097. };
  2098. } else {
  2099. return ( ...params ) => {
  2100. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2101. };
  2102. }
  2103. };
  2104. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2105. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2106. };
  2107. class ShaderCallNodeInternal extends Node {
  2108. constructor( shaderNode, inputNodes ) {
  2109. super();
  2110. this.shaderNode = shaderNode;
  2111. this.inputNodes = inputNodes;
  2112. }
  2113. getNodeType( builder ) {
  2114. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2115. }
  2116. getMemberType( builder, name ) {
  2117. return this.getOutputNode( builder ).getMemberType( builder, name );
  2118. }
  2119. call( builder ) {
  2120. const { shaderNode, inputNodes } = this;
  2121. const properties = builder.getNodeProperties( shaderNode );
  2122. if ( properties.onceOutput ) return properties.onceOutput;
  2123. //
  2124. let result = null;
  2125. if ( shaderNode.layout ) {
  2126. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2127. if ( functionNodesCacheMap === undefined ) {
  2128. functionNodesCacheMap = new WeakMap();
  2129. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2130. }
  2131. let functionNode = functionNodesCacheMap.get( shaderNode );
  2132. if ( functionNode === undefined ) {
  2133. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2134. functionNodesCacheMap.set( shaderNode, functionNode );
  2135. }
  2136. builder.addInclude( functionNode );
  2137. result = nodeObject( functionNode.call( inputNodes ) );
  2138. } else {
  2139. const jsFunc = shaderNode.jsFunc;
  2140. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2141. result = nodeObject( outputNode );
  2142. }
  2143. if ( shaderNode.once ) {
  2144. properties.onceOutput = result;
  2145. }
  2146. return result;
  2147. }
  2148. getOutputNode( builder ) {
  2149. const properties = builder.getNodeProperties( this );
  2150. if ( properties.outputNode === null ) {
  2151. properties.outputNode = this.setupOutput( builder );
  2152. }
  2153. return properties.outputNode;
  2154. }
  2155. setup( builder ) {
  2156. return this.getOutputNode( builder );
  2157. }
  2158. setupOutput( builder ) {
  2159. builder.addStack();
  2160. builder.stack.outputNode = this.call( builder );
  2161. return builder.removeStack();
  2162. }
  2163. generate( builder, output ) {
  2164. const outputNode = this.getOutputNode( builder );
  2165. return outputNode.build( builder, output );
  2166. }
  2167. }
  2168. class ShaderNodeInternal extends Node {
  2169. constructor( jsFunc, nodeType ) {
  2170. super( nodeType );
  2171. this.jsFunc = jsFunc;
  2172. this.layout = null;
  2173. this.global = true;
  2174. this.once = false;
  2175. }
  2176. setLayout( layout ) {
  2177. this.layout = layout;
  2178. return this;
  2179. }
  2180. call( inputs = null ) {
  2181. nodeObjects( inputs );
  2182. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2183. }
  2184. setup() {
  2185. return this.call();
  2186. }
  2187. }
  2188. const bools = [ false, true ];
  2189. const uints = [ 0, 1, 2, 3 ];
  2190. const ints = [ - 1, - 2 ];
  2191. 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 ];
  2192. const boolsCacheMap = new Map();
  2193. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2194. const uintsCacheMap = new Map();
  2195. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2196. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2197. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2198. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2199. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2200. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2201. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2202. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2203. const getConstNode = ( value, type ) => {
  2204. if ( constNodesCacheMap.has( value ) ) {
  2205. return constNodesCacheMap.get( value );
  2206. } else if ( value.isNode === true ) {
  2207. return value;
  2208. } else {
  2209. return new ConstNode( value, type );
  2210. }
  2211. };
  2212. const safeGetNodeType = ( node ) => {
  2213. try {
  2214. return node.getNodeType();
  2215. } catch ( _ ) {
  2216. return undefined;
  2217. }
  2218. };
  2219. const ConvertType = function ( type, cacheMap = null ) {
  2220. return ( ...params ) => {
  2221. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2222. params = [ getValueFromType( type, ...params ) ];
  2223. }
  2224. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2225. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2226. }
  2227. if ( params.length === 1 ) {
  2228. const node = getConstNode( params[ 0 ], type );
  2229. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2230. return nodeObject( new ConvertNode( node, type ) );
  2231. }
  2232. const nodes = params.map( param => getConstNode( param ) );
  2233. return nodeObject( new JoinNode( nodes, type ) );
  2234. };
  2235. };
  2236. // exports
  2237. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2238. // utils
  2239. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2240. // shader node base
  2241. function ShaderNode( jsFunc, nodeType ) {
  2242. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2243. }
  2244. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2245. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2246. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2247. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2248. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2249. const Fn = ( jsFunc, nodeType ) => {
  2250. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2251. const fn = ( ...params ) => {
  2252. let inputs;
  2253. nodeObjects( params );
  2254. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2255. inputs = [ ...params ];
  2256. } else {
  2257. inputs = params[ 0 ];
  2258. }
  2259. return shaderNode.call( inputs );
  2260. };
  2261. fn.shaderNode = shaderNode;
  2262. fn.setLayout = ( layout ) => {
  2263. shaderNode.setLayout( layout );
  2264. return fn;
  2265. };
  2266. fn.once = () => {
  2267. shaderNode.once = true;
  2268. return fn;
  2269. };
  2270. return fn;
  2271. };
  2272. /**
  2273. * @tsl
  2274. * @function
  2275. * @deprecated since r168. Use {@link Fn} instead.
  2276. *
  2277. * @param {...any} params
  2278. * @returns {Function}
  2279. */
  2280. const tslFn = ( ...params ) => { // @deprecated, r168
  2281. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2282. return Fn( ...params );
  2283. };
  2284. //
  2285. addMethodChaining( 'toGlobal', ( node ) => {
  2286. node.global = true;
  2287. return node;
  2288. } );
  2289. //
  2290. const setCurrentStack = ( stack ) => {
  2291. currentStack = stack;
  2292. };
  2293. const getCurrentStack = () => currentStack;
  2294. const If = ( ...params ) => currentStack.If( ...params );
  2295. function append( node ) {
  2296. if ( currentStack ) currentStack.add( node );
  2297. return node;
  2298. }
  2299. addMethodChaining( 'append', append );
  2300. // types
  2301. const color = new ConvertType( 'color' );
  2302. const float = new ConvertType( 'float', cacheMaps.float );
  2303. const int = new ConvertType( 'int', cacheMaps.ints );
  2304. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2305. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2306. const vec2 = new ConvertType( 'vec2' );
  2307. const ivec2 = new ConvertType( 'ivec2' );
  2308. const uvec2 = new ConvertType( 'uvec2' );
  2309. const bvec2 = new ConvertType( 'bvec2' );
  2310. const vec3 = new ConvertType( 'vec3' );
  2311. const ivec3 = new ConvertType( 'ivec3' );
  2312. const uvec3 = new ConvertType( 'uvec3' );
  2313. const bvec3 = new ConvertType( 'bvec3' );
  2314. const vec4 = new ConvertType( 'vec4' );
  2315. const ivec4 = new ConvertType( 'ivec4' );
  2316. const uvec4 = new ConvertType( 'uvec4' );
  2317. const bvec4 = new ConvertType( 'bvec4' );
  2318. const mat2 = new ConvertType( 'mat2' );
  2319. const mat3 = new ConvertType( 'mat3' );
  2320. const mat4 = new ConvertType( 'mat4' );
  2321. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2322. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2323. addMethodChaining( 'toColor', color );
  2324. addMethodChaining( 'toFloat', float );
  2325. addMethodChaining( 'toInt', int );
  2326. addMethodChaining( 'toUint', uint );
  2327. addMethodChaining( 'toBool', bool );
  2328. addMethodChaining( 'toVec2', vec2 );
  2329. addMethodChaining( 'toIVec2', ivec2 );
  2330. addMethodChaining( 'toUVec2', uvec2 );
  2331. addMethodChaining( 'toBVec2', bvec2 );
  2332. addMethodChaining( 'toVec3', vec3 );
  2333. addMethodChaining( 'toIVec3', ivec3 );
  2334. addMethodChaining( 'toUVec3', uvec3 );
  2335. addMethodChaining( 'toBVec3', bvec3 );
  2336. addMethodChaining( 'toVec4', vec4 );
  2337. addMethodChaining( 'toIVec4', ivec4 );
  2338. addMethodChaining( 'toUVec4', uvec4 );
  2339. addMethodChaining( 'toBVec4', bvec4 );
  2340. addMethodChaining( 'toMat2', mat2 );
  2341. addMethodChaining( 'toMat3', mat3 );
  2342. addMethodChaining( 'toMat4', mat4 );
  2343. // basic nodes
  2344. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2345. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2346. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2347. addMethodChaining( 'element', element );
  2348. addMethodChaining( 'convert', convert );
  2349. /**
  2350. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  2351. * ```js
  2352. * const colors = array( [
  2353. * vec3( 1, 0, 0 ),
  2354. * vec3( 0, 1, 0 ),
  2355. * vec3( 0, 0, 1 )
  2356. * ] );
  2357. *
  2358. * const redColor = tintColors.element( 0 );
  2359. *
  2360. * @augments TempNode
  2361. */
  2362. class ArrayNode extends TempNode {
  2363. static get type() {
  2364. return 'ArrayNode';
  2365. }
  2366. /**
  2367. * Constructs a new array node.
  2368. *
  2369. * @param {?string} nodeType - The data type of the elements.
  2370. * @param {number} count - Size of the array.
  2371. * @param {?Array<Node>} [values=null] - Array default values.
  2372. */
  2373. constructor( nodeType, count, values = null ) {
  2374. super( nodeType );
  2375. /**
  2376. * Array size.
  2377. *
  2378. * @type {number}
  2379. */
  2380. this.count = count;
  2381. /**
  2382. * Array default values.
  2383. *
  2384. * @type {?Array<Node>}
  2385. */
  2386. this.values = values;
  2387. /**
  2388. * This flag can be used for type testing.
  2389. *
  2390. * @type {boolean}
  2391. * @readonly
  2392. * @default true
  2393. */
  2394. this.isArrayNode = true;
  2395. }
  2396. /**
  2397. * Returns the node's type.
  2398. *
  2399. * @param {NodeBuilder} builder - The current node builder.
  2400. * @return {string} The type of the node.
  2401. */
  2402. getNodeType( builder ) {
  2403. if ( this.nodeType === null ) {
  2404. this.nodeType = this.values[ 0 ].getNodeType( builder );
  2405. }
  2406. return this.nodeType;
  2407. }
  2408. /**
  2409. * Returns the node's type.
  2410. *
  2411. * @param {NodeBuilder} builder - The current node builder.
  2412. * @return {string} The type of the node.
  2413. */
  2414. getElementType( builder ) {
  2415. return this.getNodeType( builder );
  2416. }
  2417. /**
  2418. * This method builds the output node and returns the resulting array as a shader string.
  2419. *
  2420. * @param {NodeBuilder} builder - The current node builder.
  2421. * @return {string} The generated shader string.
  2422. */
  2423. generate( builder ) {
  2424. const type = this.getNodeType( builder );
  2425. return builder.generateArray( type, this.count, this.values );
  2426. }
  2427. }
  2428. /**
  2429. * TSL function for creating an array node.
  2430. *
  2431. * @tsl
  2432. * @function
  2433. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  2434. * or an array containing the default values (e.g., [ vec3() ]).
  2435. * @param {?number} [count] - Size of the array.
  2436. * @returns {ArrayNode}
  2437. */
  2438. const array = ( ...params ) => {
  2439. let node;
  2440. if ( params.length === 1 ) {
  2441. const values = params[ 0 ];
  2442. node = new ArrayNode( null, values.length, values );
  2443. } else {
  2444. const nodeType = params[ 0 ];
  2445. const count = params[ 1 ];
  2446. node = new ArrayNode( nodeType, count );
  2447. }
  2448. return nodeObject( node );
  2449. };
  2450. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  2451. /**
  2452. * This node can be used to group single instances of {@link UniformNode}
  2453. * and manage them as a uniform buffer.
  2454. *
  2455. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2456. * will be used when defining the {@link UniformNode#groupNode} property.
  2457. *
  2458. * - `objectGroup`: Uniform buffer per object.
  2459. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2460. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2461. *
  2462. * @augments Node
  2463. */
  2464. class UniformGroupNode extends Node {
  2465. static get type() {
  2466. return 'UniformGroupNode';
  2467. }
  2468. /**
  2469. * Constructs a new uniform group node.
  2470. *
  2471. * @param {string} name - The name of the uniform group node.
  2472. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2473. * @param {number} [order=1] - Influences the internal sorting.
  2474. */
  2475. constructor( name, shared = false, order = 1 ) {
  2476. super( 'string' );
  2477. /**
  2478. * The name of the uniform group node.
  2479. *
  2480. * @type {string}
  2481. */
  2482. this.name = name;
  2483. /**
  2484. * Whether this uniform group node is shared or not.
  2485. *
  2486. * @type {boolean}
  2487. * @default false
  2488. */
  2489. this.shared = shared;
  2490. /**
  2491. * Influences the internal sorting.
  2492. * TODO: Add details when this property should be changed.
  2493. *
  2494. * @type {number}
  2495. * @default 1
  2496. */
  2497. this.order = order;
  2498. /**
  2499. * This flag can be used for type testing.
  2500. *
  2501. * @type {boolean}
  2502. * @readonly
  2503. * @default true
  2504. */
  2505. this.isUniformGroup = true;
  2506. }
  2507. serialize( data ) {
  2508. super.serialize( data );
  2509. data.name = this.name;
  2510. data.version = this.version;
  2511. data.shared = this.shared;
  2512. }
  2513. deserialize( data ) {
  2514. super.deserialize( data );
  2515. this.name = data.name;
  2516. this.version = data.version;
  2517. this.shared = data.shared;
  2518. }
  2519. }
  2520. /**
  2521. * TSL function for creating a uniform group node with the given name.
  2522. *
  2523. * @tsl
  2524. * @function
  2525. * @param {string} name - The name of the uniform group node.
  2526. * @returns {UniformGroupNode}
  2527. */
  2528. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2529. /**
  2530. * TSL function for creating a shared uniform group node with the given name and order.
  2531. *
  2532. * @tsl
  2533. * @function
  2534. * @param {string} name - The name of the uniform group node.
  2535. * @param {number} [order=0] - Influences the internal sorting.
  2536. * @returns {UniformGroupNode}
  2537. */
  2538. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2539. /**
  2540. * TSL object that represents a shared uniform group node which is updated once per frame.
  2541. *
  2542. * @tsl
  2543. * @type {UniformGroupNode}
  2544. */
  2545. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2546. /**
  2547. * TSL object that represents a shared uniform group node which is updated once per render.
  2548. *
  2549. * @tsl
  2550. * @type {UniformGroupNode}
  2551. */
  2552. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2553. /**
  2554. * TSL object that represents a uniform group node which is updated once per object.
  2555. *
  2556. * @tsl
  2557. * @type {UniformGroupNode}
  2558. */
  2559. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2560. /**
  2561. * Class for representing a uniform.
  2562. *
  2563. * @augments InputNode
  2564. */
  2565. class UniformNode extends InputNode {
  2566. static get type() {
  2567. return 'UniformNode';
  2568. }
  2569. /**
  2570. * Constructs a new uniform node.
  2571. *
  2572. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2573. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2574. */
  2575. constructor( value, nodeType = null ) {
  2576. super( value, nodeType );
  2577. /**
  2578. * This flag can be used for type testing.
  2579. *
  2580. * @type {boolean}
  2581. * @readonly
  2582. * @default true
  2583. */
  2584. this.isUniformNode = true;
  2585. /**
  2586. * The name or label of the uniform.
  2587. *
  2588. * @type {string}
  2589. * @default ''
  2590. */
  2591. this.name = '';
  2592. /**
  2593. * The uniform group of this uniform. By default, uniforms are
  2594. * managed per object but they might belong to a shared group
  2595. * which is updated per frame or render call.
  2596. *
  2597. * @type {UniformGroupNode}
  2598. */
  2599. this.groupNode = objectGroup;
  2600. }
  2601. /**
  2602. * Sets the {@link UniformNode#name} property.
  2603. *
  2604. * @param {string} name - The name of the uniform.
  2605. * @return {UniformNode} A reference to this node.
  2606. */
  2607. label( name ) {
  2608. this.name = name;
  2609. return this;
  2610. }
  2611. /**
  2612. * Sets the {@link UniformNode#groupNode} property.
  2613. *
  2614. * @param {UniformGroupNode} group - The uniform group.
  2615. * @return {UniformNode} A reference to this node.
  2616. */
  2617. setGroup( group ) {
  2618. this.groupNode = group;
  2619. return this;
  2620. }
  2621. /**
  2622. * Returns the {@link UniformNode#groupNode}.
  2623. *
  2624. * @return {UniformGroupNode} The uniform group.
  2625. */
  2626. getGroup() {
  2627. return this.groupNode;
  2628. }
  2629. /**
  2630. * By default, this method returns the result of {@link Node#getHash} but derived
  2631. * classes might overwrite this method with a different implementation.
  2632. *
  2633. * @param {NodeBuilder} builder - The current node builder.
  2634. * @return {string} The uniform hash.
  2635. */
  2636. getUniformHash( builder ) {
  2637. return this.getHash( builder );
  2638. }
  2639. onUpdate( callback, updateType ) {
  2640. const self = this.getSelf();
  2641. callback = callback.bind( self );
  2642. return super.onUpdate( ( frame ) => {
  2643. const value = callback( frame, self );
  2644. if ( value !== undefined ) {
  2645. this.value = value;
  2646. }
  2647. }, updateType );
  2648. }
  2649. generate( builder, output ) {
  2650. const type = this.getNodeType( builder );
  2651. const hash = this.getUniformHash( builder );
  2652. let sharedNode = builder.getNodeFromHash( hash );
  2653. if ( sharedNode === undefined ) {
  2654. builder.setHashNode( this, hash );
  2655. sharedNode = this;
  2656. }
  2657. const sharedNodeType = sharedNode.getInputType( builder );
  2658. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2659. const propertyName = builder.getPropertyName( nodeUniform );
  2660. if ( builder.context.label !== undefined ) delete builder.context.label;
  2661. return builder.format( propertyName, type, output );
  2662. }
  2663. }
  2664. /**
  2665. * TSL function for creating a uniform node.
  2666. *
  2667. * @tsl
  2668. * @function
  2669. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2670. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2671. * @returns {UniformNode}
  2672. */
  2673. const uniform = ( arg1, arg2 ) => {
  2674. const nodeType = getConstNodeType( arg2 || arg1 );
  2675. // @TODO: get ConstNode from .traverse() in the future
  2676. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2677. return nodeObject( new UniformNode( value, nodeType ) );
  2678. };
  2679. /**
  2680. * This class represents a shader property. It can be used
  2681. * to explicitly define a property and assign a value to it.
  2682. *
  2683. * ```js
  2684. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2685. *```
  2686. * `PropertyNode` is used by the engine to predefined common material properties
  2687. * for TSL code.
  2688. *
  2689. * @augments Node
  2690. */
  2691. class PropertyNode extends Node {
  2692. static get type() {
  2693. return 'PropertyNode';
  2694. }
  2695. /**
  2696. * Constructs a new property node.
  2697. *
  2698. * @param {string} nodeType - The type of the node.
  2699. * @param {?string} [name=null] - The name of the property in the shader.
  2700. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2701. */
  2702. constructor( nodeType, name = null, varying = false ) {
  2703. super( nodeType );
  2704. /**
  2705. * The name of the property in the shader. If no name is defined,
  2706. * the node system auto-generates one.
  2707. *
  2708. * @type {?string}
  2709. * @default null
  2710. */
  2711. this.name = name;
  2712. /**
  2713. * Whether this property is a varying or not.
  2714. *
  2715. * @type {boolean}
  2716. * @default false
  2717. */
  2718. this.varying = varying;
  2719. /**
  2720. * This flag can be used for type testing.
  2721. *
  2722. * @type {boolean}
  2723. * @readonly
  2724. * @default true
  2725. */
  2726. this.isPropertyNode = true;
  2727. }
  2728. getHash( builder ) {
  2729. return this.name || super.getHash( builder );
  2730. }
  2731. /**
  2732. * The method is overwritten so it always returns `true`.
  2733. *
  2734. * @param {NodeBuilder} builder - The current node builder.
  2735. * @return {boolean} Whether this node is global or not.
  2736. */
  2737. isGlobal( /*builder*/ ) {
  2738. return true;
  2739. }
  2740. generate( builder ) {
  2741. let nodeVar;
  2742. if ( this.varying === true ) {
  2743. nodeVar = builder.getVaryingFromNode( this, this.name );
  2744. nodeVar.needsInterpolation = true;
  2745. } else {
  2746. nodeVar = builder.getVarFromNode( this, this.name );
  2747. }
  2748. return builder.getPropertyName( nodeVar );
  2749. }
  2750. }
  2751. /**
  2752. * TSL function for creating a property node.
  2753. *
  2754. * @tsl
  2755. * @function
  2756. * @param {string} type - The type of the node.
  2757. * @param {?string} [name=null] - The name of the property in the shader.
  2758. * @returns {PropertyNode}
  2759. */
  2760. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2761. /**
  2762. * TSL function for creating a varying property node.
  2763. *
  2764. * @tsl
  2765. * @function
  2766. * @param {string} type - The type of the node.
  2767. * @param {?string} [name=null] - The name of the varying in the shader.
  2768. * @returns {PropertyNode}
  2769. */
  2770. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2771. /**
  2772. * TSL object that represents the shader variable `DiffuseColor`.
  2773. *
  2774. * @tsl
  2775. * @type {PropertyNode<vec4>}
  2776. */
  2777. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2778. /**
  2779. * TSL object that represents the shader variable `EmissiveColor`.
  2780. *
  2781. * @tsl
  2782. * @type {PropertyNode<vec3>}
  2783. */
  2784. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2785. /**
  2786. * TSL object that represents the shader variable `Roughness`.
  2787. *
  2788. * @tsl
  2789. * @type {PropertyNode<float>}
  2790. */
  2791. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2792. /**
  2793. * TSL object that represents the shader variable `Metalness`.
  2794. *
  2795. * @tsl
  2796. * @type {PropertyNode<float>}
  2797. */
  2798. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2799. /**
  2800. * TSL object that represents the shader variable `Clearcoat`.
  2801. *
  2802. * @tsl
  2803. * @type {PropertyNode<float>}
  2804. */
  2805. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2806. /**
  2807. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2808. *
  2809. * @tsl
  2810. * @type {PropertyNode<float>}
  2811. */
  2812. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2813. /**
  2814. * TSL object that represents the shader variable `Sheen`.
  2815. *
  2816. * @tsl
  2817. * @type {PropertyNode<vec3>}
  2818. */
  2819. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2820. /**
  2821. * TSL object that represents the shader variable `SheenRoughness`.
  2822. *
  2823. * @tsl
  2824. * @type {PropertyNode<float>}
  2825. */
  2826. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2827. /**
  2828. * TSL object that represents the shader variable `Iridescence`.
  2829. *
  2830. * @tsl
  2831. * @type {PropertyNode<float>}
  2832. */
  2833. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2834. /**
  2835. * TSL object that represents the shader variable `IridescenceIOR`.
  2836. *
  2837. * @tsl
  2838. * @type {PropertyNode<float>}
  2839. */
  2840. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2841. /**
  2842. * TSL object that represents the shader variable `IridescenceThickness`.
  2843. *
  2844. * @tsl
  2845. * @type {PropertyNode<float>}
  2846. */
  2847. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2848. /**
  2849. * TSL object that represents the shader variable `AlphaT`.
  2850. *
  2851. * @tsl
  2852. * @type {PropertyNode<float>}
  2853. */
  2854. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2855. /**
  2856. * TSL object that represents the shader variable `Anisotropy`.
  2857. *
  2858. * @tsl
  2859. * @type {PropertyNode<float>}
  2860. */
  2861. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2862. /**
  2863. * TSL object that represents the shader variable `AnisotropyT`.
  2864. *
  2865. * @tsl
  2866. * @type {PropertyNode<vec3>}
  2867. */
  2868. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2869. /**
  2870. * TSL object that represents the shader variable `AnisotropyB`.
  2871. *
  2872. * @tsl
  2873. * @type {PropertyNode<vec3>}
  2874. */
  2875. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2876. /**
  2877. * TSL object that represents the shader variable `SpecularColor`.
  2878. *
  2879. * @tsl
  2880. * @type {PropertyNode<color>}
  2881. */
  2882. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2883. /**
  2884. * TSL object that represents the shader variable `SpecularF90`.
  2885. *
  2886. * @tsl
  2887. * @type {PropertyNode<float>}
  2888. */
  2889. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2890. /**
  2891. * TSL object that represents the shader variable `Shininess`.
  2892. *
  2893. * @tsl
  2894. * @type {PropertyNode<float>}
  2895. */
  2896. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2897. /**
  2898. * TSL object that represents the shader variable `Output`.
  2899. *
  2900. * @tsl
  2901. * @type {PropertyNode<vec4>}
  2902. */
  2903. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2904. /**
  2905. * TSL object that represents the shader variable `dashSize`.
  2906. *
  2907. * @tsl
  2908. * @type {PropertyNode<float>}
  2909. */
  2910. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2911. /**
  2912. * TSL object that represents the shader variable `gapSize`.
  2913. *
  2914. * @tsl
  2915. * @type {PropertyNode<float>}
  2916. */
  2917. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2918. /**
  2919. * TSL object that represents the shader variable `pointWidth`.
  2920. *
  2921. * @tsl
  2922. * @type {PropertyNode<float>}
  2923. */
  2924. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2925. /**
  2926. * TSL object that represents the shader variable `IOR`.
  2927. *
  2928. * @tsl
  2929. * @type {PropertyNode<float>}
  2930. */
  2931. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2932. /**
  2933. * TSL object that represents the shader variable `Transmission`.
  2934. *
  2935. * @tsl
  2936. * @type {PropertyNode<float>}
  2937. */
  2938. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2939. /**
  2940. * TSL object that represents the shader variable `Thickness`.
  2941. *
  2942. * @tsl
  2943. * @type {PropertyNode<float>}
  2944. */
  2945. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2946. /**
  2947. * TSL object that represents the shader variable `AttenuationDistance`.
  2948. *
  2949. * @tsl
  2950. * @type {PropertyNode<float>}
  2951. */
  2952. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2953. /**
  2954. * TSL object that represents the shader variable `AttenuationColor`.
  2955. *
  2956. * @tsl
  2957. * @type {PropertyNode<color>}
  2958. */
  2959. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2960. /**
  2961. * TSL object that represents the shader variable `Dispersion`.
  2962. *
  2963. * @tsl
  2964. * @type {PropertyNode<float>}
  2965. */
  2966. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2967. /**
  2968. * These node represents an assign operation. Meaning a node is assigned
  2969. * to another node.
  2970. *
  2971. * @augments TempNode
  2972. */
  2973. class AssignNode extends TempNode {
  2974. static get type() {
  2975. return 'AssignNode';
  2976. }
  2977. /**
  2978. * Constructs a new assign node.
  2979. *
  2980. * @param {Node} targetNode - The target node.
  2981. * @param {Node} sourceNode - The source type.
  2982. */
  2983. constructor( targetNode, sourceNode ) {
  2984. super();
  2985. /**
  2986. * The target node.
  2987. *
  2988. * @type {Node}
  2989. */
  2990. this.targetNode = targetNode;
  2991. /**
  2992. * The source node.
  2993. *
  2994. * @type {Node}
  2995. */
  2996. this.sourceNode = sourceNode;
  2997. }
  2998. /**
  2999. * Whether this node is used more than once in context of other nodes. This method
  3000. * is overwritten since it always returns `false` (assigns are unique).
  3001. *
  3002. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3003. */
  3004. hasDependencies() {
  3005. return false;
  3006. }
  3007. getNodeType( builder, output ) {
  3008. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3009. }
  3010. /**
  3011. * Whether a split is required when assigning source to target. This can happen when the component length of
  3012. * target and source data type does not match.
  3013. *
  3014. * @param {NodeBuilder} builder - The current node builder.
  3015. * @return {boolean} Whether a split is required when assigning source to target.
  3016. */
  3017. needsSplitAssign( builder ) {
  3018. const { targetNode } = this;
  3019. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3020. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3021. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3022. return assignDifferentVector;
  3023. }
  3024. return false;
  3025. }
  3026. generate( builder, output ) {
  3027. const { targetNode, sourceNode } = this;
  3028. const needsSplitAssign = this.needsSplitAssign( builder );
  3029. const targetType = targetNode.getNodeType( builder );
  3030. const target = targetNode.context( { assign: true } ).build( builder );
  3031. const source = sourceNode.build( builder, targetType );
  3032. const sourceType = sourceNode.getNodeType( builder );
  3033. const nodeData = builder.getDataFromNode( this );
  3034. //
  3035. let snippet;
  3036. if ( nodeData.initialized === true ) {
  3037. if ( output !== 'void' ) {
  3038. snippet = target;
  3039. }
  3040. } else if ( needsSplitAssign ) {
  3041. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3042. const sourceProperty = builder.getPropertyName( sourceVar );
  3043. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3044. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  3045. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  3046. const component = targetNode.components[ i ];
  3047. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3048. }
  3049. if ( output !== 'void' ) {
  3050. snippet = target;
  3051. }
  3052. } else {
  3053. snippet = `${ target } = ${ source }`;
  3054. if ( output === 'void' || sourceType === 'void' ) {
  3055. builder.addLineFlowCode( snippet, this );
  3056. if ( output !== 'void' ) {
  3057. snippet = target;
  3058. }
  3059. }
  3060. }
  3061. nodeData.initialized = true;
  3062. return builder.format( snippet, targetType, output );
  3063. }
  3064. }
  3065. /**
  3066. * TSL function for creating an assign node.
  3067. *
  3068. * @tsl
  3069. * @function
  3070. * @param {Node} targetNode - The target node.
  3071. * @param {Node} sourceNode - The source type.
  3072. * @returns {AssignNode}
  3073. */
  3074. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  3075. addMethodChaining( 'assign', assign );
  3076. /**
  3077. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3078. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3079. * this logic.
  3080. *
  3081. * @augments TempNode
  3082. */
  3083. class FunctionCallNode extends TempNode {
  3084. static get type() {
  3085. return 'FunctionCallNode';
  3086. }
  3087. /**
  3088. * Constructs a new function call node.
  3089. *
  3090. * @param {?FunctionNode} functionNode - The function node.
  3091. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3092. */
  3093. constructor( functionNode = null, parameters = {} ) {
  3094. super();
  3095. /**
  3096. * The function node.
  3097. *
  3098. * @type {?FunctionNode}
  3099. * @default null
  3100. */
  3101. this.functionNode = functionNode;
  3102. /**
  3103. * The parameters of the function call.
  3104. *
  3105. * @type {Object<string, Node>}
  3106. * @default {}
  3107. */
  3108. this.parameters = parameters;
  3109. }
  3110. /**
  3111. * Sets the parameters of the function call node.
  3112. *
  3113. * @param {Object<string, Node>} parameters - The parameters to set.
  3114. * @return {FunctionCallNode} A reference to this node.
  3115. */
  3116. setParameters( parameters ) {
  3117. this.parameters = parameters;
  3118. return this;
  3119. }
  3120. /**
  3121. * Returns the parameters of the function call node.
  3122. *
  3123. * @return {Object<string, Node>} The parameters of this node.
  3124. */
  3125. getParameters() {
  3126. return this.parameters;
  3127. }
  3128. getNodeType( builder ) {
  3129. return this.functionNode.getNodeType( builder );
  3130. }
  3131. generate( builder ) {
  3132. const params = [];
  3133. const functionNode = this.functionNode;
  3134. const inputs = functionNode.getInputs( builder );
  3135. const parameters = this.parameters;
  3136. const generateInput = ( node, inputNode ) => {
  3137. const type = inputNode.type;
  3138. const pointer = type === 'pointer';
  3139. let output;
  3140. if ( pointer ) output = '&' + node.build( builder );
  3141. else output = node.build( builder, type );
  3142. return output;
  3143. };
  3144. if ( Array.isArray( parameters ) ) {
  3145. for ( let i = 0; i < parameters.length; i ++ ) {
  3146. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3147. }
  3148. } else {
  3149. for ( const inputNode of inputs ) {
  3150. const node = parameters[ inputNode.name ];
  3151. if ( node !== undefined ) {
  3152. params.push( generateInput( node, inputNode ) );
  3153. } else {
  3154. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  3155. }
  3156. }
  3157. }
  3158. const functionName = functionNode.build( builder, 'property' );
  3159. return `${functionName}( ${params.join( ', ' )} )`;
  3160. }
  3161. }
  3162. const call = ( func, ...params ) => {
  3163. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3164. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3165. };
  3166. addMethodChaining( 'call', call );
  3167. /**
  3168. * This node represents basic mathematical and logical operations like addition,
  3169. * subtraction or comparisons (e.g. `equal()`).
  3170. *
  3171. * @augments TempNode
  3172. */
  3173. class OperatorNode extends TempNode {
  3174. static get type() {
  3175. return 'OperatorNode';
  3176. }
  3177. /**
  3178. * Constructs a new operator node.
  3179. *
  3180. * @param {string} op - The operator.
  3181. * @param {Node} aNode - The first input.
  3182. * @param {Node} bNode - The second input.
  3183. * @param {...Node} params - Additional input parameters.
  3184. */
  3185. constructor( op, aNode, bNode, ...params ) {
  3186. super();
  3187. if ( params.length > 0 ) {
  3188. let finalOp = new OperatorNode( op, aNode, bNode );
  3189. for ( let i = 0; i < params.length - 1; i ++ ) {
  3190. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3191. }
  3192. aNode = finalOp;
  3193. bNode = params[ params.length - 1 ];
  3194. }
  3195. /**
  3196. * The operator.
  3197. *
  3198. * @type {string}
  3199. */
  3200. this.op = op;
  3201. /**
  3202. * The first input.
  3203. *
  3204. * @type {Node}
  3205. */
  3206. this.aNode = aNode;
  3207. /**
  3208. * The second input.
  3209. *
  3210. * @type {Node}
  3211. */
  3212. this.bNode = bNode;
  3213. /**
  3214. * This flag can be used for type testing.
  3215. *
  3216. * @type {boolean}
  3217. * @readonly
  3218. * @default true
  3219. */
  3220. this.isOperatorNode = true;
  3221. }
  3222. /**
  3223. * This method is overwritten since the node type is inferred from the operator
  3224. * and the input node types.
  3225. *
  3226. * @param {NodeBuilder} builder - The current node builder.
  3227. * @param {string} output - The current output string.
  3228. * @return {string} The node type.
  3229. */
  3230. getNodeType( builder, output ) {
  3231. const op = this.op;
  3232. const aNode = this.aNode;
  3233. const bNode = this.bNode;
  3234. const typeA = aNode.getNodeType( builder );
  3235. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3236. if ( typeA === 'void' || typeB === 'void' ) {
  3237. return 'void';
  3238. } else if ( op === '%' ) {
  3239. return typeA;
  3240. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3241. return builder.getIntegerType( typeA );
  3242. } else if ( op === '!' || op === '==' || op === '!=' || op === '&&' || op === '||' || op === '^^' ) {
  3243. return 'bool';
  3244. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3245. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3246. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3247. } else {
  3248. // Handle matrix operations
  3249. if ( builder.isMatrix( typeA ) ) {
  3250. if ( typeB === 'float' ) {
  3251. return typeA; // matrix * scalar = matrix
  3252. } else if ( builder.isVector( typeB ) ) {
  3253. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3254. } else if ( builder.isMatrix( typeB ) ) {
  3255. return typeA; // matrix * matrix
  3256. }
  3257. } else if ( builder.isMatrix( typeB ) ) {
  3258. if ( typeA === 'float' ) {
  3259. return typeB; // scalar * matrix = matrix
  3260. } else if ( builder.isVector( typeA ) ) {
  3261. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3262. }
  3263. }
  3264. // Handle non-matrix cases
  3265. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3266. // anytype x anytype: use the greater length vector
  3267. return typeB;
  3268. }
  3269. return typeA;
  3270. }
  3271. }
  3272. generate( builder, output ) {
  3273. const op = this.op;
  3274. const aNode = this.aNode;
  3275. const bNode = this.bNode;
  3276. const type = this.getNodeType( builder, output );
  3277. let typeA = null;
  3278. let typeB = null;
  3279. if ( type !== 'void' ) {
  3280. typeA = aNode.getNodeType( builder );
  3281. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3282. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3283. if ( builder.isVector( typeA ) ) {
  3284. typeB = typeA;
  3285. } else if ( typeA !== typeB ) {
  3286. typeA = typeB = 'float';
  3287. }
  3288. } else if ( op === '>>' || op === '<<' ) {
  3289. typeA = type;
  3290. typeB = builder.changeComponentType( typeB, 'uint' );
  3291. } else if ( builder.isMatrix( typeA ) ) {
  3292. if ( typeB === 'float' ) {
  3293. // Keep matrix type for typeA, but ensure typeB stays float
  3294. typeB = 'float';
  3295. } else if ( builder.isVector( typeB ) ) {
  3296. // matrix x vector
  3297. typeB = builder.getVectorFromMatrix( typeA );
  3298. } else if ( builder.isMatrix( typeB ) ) ; else {
  3299. typeA = typeB = type;
  3300. }
  3301. } else if ( builder.isMatrix( typeB ) ) {
  3302. if ( typeA === 'float' ) {
  3303. // Keep matrix type for typeB, but ensure typeA stays float
  3304. typeA = 'float';
  3305. } else if ( builder.isVector( typeA ) ) {
  3306. // vector x matrix
  3307. typeA = builder.getVectorFromMatrix( typeB );
  3308. } else {
  3309. typeA = typeB = type;
  3310. }
  3311. } else {
  3312. // anytype x anytype
  3313. typeA = typeB = type;
  3314. }
  3315. } else {
  3316. typeA = typeB = type;
  3317. }
  3318. const a = aNode.build( builder, typeA );
  3319. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3320. const outputLength = builder.getTypeLength( output );
  3321. const fnOpSnippet = builder.getFunctionOperator( op );
  3322. if ( output !== 'void' ) {
  3323. if ( op === '<' && outputLength > 1 ) {
  3324. if ( builder.useComparisonMethod ) {
  3325. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3326. } else {
  3327. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3328. }
  3329. } else if ( op === '<=' && outputLength > 1 ) {
  3330. if ( builder.useComparisonMethod ) {
  3331. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3332. } else {
  3333. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3334. }
  3335. } else if ( op === '>' && outputLength > 1 ) {
  3336. if ( builder.useComparisonMethod ) {
  3337. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3338. } else {
  3339. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3340. }
  3341. } else if ( op === '>=' && outputLength > 1 ) {
  3342. if ( builder.useComparisonMethod ) {
  3343. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3344. } else {
  3345. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3346. }
  3347. } else if ( op === '!' || op === '~' ) {
  3348. return builder.format( `(${op}${a})`, typeA, output );
  3349. } else if ( fnOpSnippet ) {
  3350. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3351. } else {
  3352. // Handle matrix operations
  3353. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3354. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3355. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3356. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3357. } else {
  3358. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3359. }
  3360. }
  3361. } else if ( typeA !== 'void' ) {
  3362. if ( fnOpSnippet ) {
  3363. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3364. } else {
  3365. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3366. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3367. } else {
  3368. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3369. }
  3370. }
  3371. }
  3372. }
  3373. serialize( data ) {
  3374. super.serialize( data );
  3375. data.op = this.op;
  3376. }
  3377. deserialize( data ) {
  3378. super.deserialize( data );
  3379. this.op = data.op;
  3380. }
  3381. }
  3382. /**
  3383. * Returns the addition of two or more value.
  3384. *
  3385. * @tsl
  3386. * @function
  3387. * @param {Node} aNode - The first input.
  3388. * @param {Node} bNode - The second input.
  3389. * @param {...Node} params - Additional input parameters.
  3390. * @returns {OperatorNode}
  3391. */
  3392. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3393. /**
  3394. * Returns the subtraction of two or more value.
  3395. *
  3396. * @tsl
  3397. * @function
  3398. * @param {Node} aNode - The first input.
  3399. * @param {Node} bNode - The second input.
  3400. * @param {...Node} params - Additional input parameters.
  3401. * @returns {OperatorNode}
  3402. */
  3403. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3404. /**
  3405. * Returns the multiplication of two or more value.
  3406. *
  3407. * @tsl
  3408. * @function
  3409. * @param {Node} aNode - The first input.
  3410. * @param {Node} bNode - The second input.
  3411. * @param {...Node} params - Additional input parameters.
  3412. * @returns {OperatorNode}
  3413. */
  3414. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3415. /**
  3416. * Returns the division of two or more value.
  3417. *
  3418. * @tsl
  3419. * @function
  3420. * @param {Node} aNode - The first input.
  3421. * @param {Node} bNode - The second input.
  3422. * @param {...Node} params - Additional input parameters.
  3423. * @returns {OperatorNode}
  3424. */
  3425. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3426. /**
  3427. * Computes the remainder of dividing the first node by the second, for integer values.
  3428. *
  3429. * @tsl
  3430. * @function
  3431. * @param {Node} aNode - The first input.
  3432. * @param {Node} bNode - The second input.
  3433. * @returns {OperatorNode}
  3434. */
  3435. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3436. /**
  3437. * Checks if two nodes are equal.
  3438. *
  3439. * @tsl
  3440. * @function
  3441. * @param {Node} aNode - The first input.
  3442. * @param {Node} bNode - The second input.
  3443. * @returns {OperatorNode}
  3444. */
  3445. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3446. /**
  3447. * Checks if two nodes are not equal.
  3448. *
  3449. * @tsl
  3450. * @function
  3451. * @param {Node} aNode - The first input.
  3452. * @param {Node} bNode - The second input.
  3453. * @returns {OperatorNode}
  3454. */
  3455. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3456. /**
  3457. * Checks if the first node is less than the second.
  3458. *
  3459. * @tsl
  3460. * @function
  3461. * @param {Node} aNode - The first input.
  3462. * @param {Node} bNode - The second input.
  3463. * @returns {OperatorNode}
  3464. */
  3465. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3466. /**
  3467. * Checks if the first node is greater than the second.
  3468. *
  3469. * @tsl
  3470. * @function
  3471. * @param {Node} aNode - The first input.
  3472. * @param {Node} bNode - The second input.
  3473. * @returns {OperatorNode}
  3474. */
  3475. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3476. /**
  3477. * Checks if the first node is less than or equal to the second.
  3478. *
  3479. * @tsl
  3480. * @function
  3481. * @param {Node} aNode - The first input.
  3482. * @param {Node} bNode - The second input.
  3483. * @returns {OperatorNode}
  3484. */
  3485. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3486. /**
  3487. * Checks if the first node is greater than or equal to the second.
  3488. *
  3489. * @tsl
  3490. * @function
  3491. * @param {Node} aNode - The first input.
  3492. * @param {Node} bNode - The second input.
  3493. * @returns {OperatorNode}
  3494. */
  3495. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3496. /**
  3497. * Performs logical AND on two nodes.
  3498. *
  3499. * @tsl
  3500. * @function
  3501. * @param {Node} aNode - The first input.
  3502. * @param {Node} bNode - The second input.
  3503. * @returns {OperatorNode}
  3504. */
  3505. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3506. /**
  3507. * Performs logical OR on two nodes.
  3508. *
  3509. * @tsl
  3510. * @function
  3511. * @param {Node} aNode - The first input.
  3512. * @param {Node} bNode - The second input.
  3513. * @returns {OperatorNode}
  3514. */
  3515. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3516. /**
  3517. * Performs logical NOT on a node.
  3518. *
  3519. * @tsl
  3520. * @function
  3521. * @param {Node} aNode - The first input.
  3522. * @param {Node} bNode - The second input.
  3523. * @returns {OperatorNode}
  3524. */
  3525. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3526. /**
  3527. * Performs logical XOR on two nodes.
  3528. *
  3529. * @tsl
  3530. * @function
  3531. * @param {Node} aNode - The first input.
  3532. * @param {Node} bNode - The second input.
  3533. * @returns {OperatorNode}
  3534. */
  3535. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3536. /**
  3537. * Performs bitwise AND on two nodes.
  3538. *
  3539. * @tsl
  3540. * @function
  3541. * @param {Node} aNode - The first input.
  3542. * @param {Node} bNode - The second input.
  3543. * @returns {OperatorNode}
  3544. */
  3545. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3546. /**
  3547. * Performs bitwise NOT on a node.
  3548. *
  3549. * @tsl
  3550. * @function
  3551. * @param {Node} aNode - The first input.
  3552. * @param {Node} bNode - The second input.
  3553. * @returns {OperatorNode}
  3554. */
  3555. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3556. /**
  3557. * Performs bitwise OR on two nodes.
  3558. *
  3559. * @tsl
  3560. * @function
  3561. * @param {Node} aNode - The first input.
  3562. * @param {Node} bNode - The second input.
  3563. * @returns {OperatorNode}
  3564. */
  3565. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3566. /**
  3567. * Performs bitwise XOR on two nodes.
  3568. *
  3569. * @tsl
  3570. * @function
  3571. * @param {Node} aNode - The first input.
  3572. * @param {Node} bNode - The second input.
  3573. * @returns {OperatorNode}
  3574. */
  3575. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3576. /**
  3577. * Shifts a node to the left.
  3578. *
  3579. * @tsl
  3580. * @function
  3581. * @param {Node} aNode - The node to shift.
  3582. * @param {Node} bNode - The value to shift.
  3583. * @returns {OperatorNode}
  3584. */
  3585. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3586. /**
  3587. * Shifts a node to the right.
  3588. *
  3589. * @tsl
  3590. * @function
  3591. * @param {Node} aNode - The node to shift.
  3592. * @param {Node} bNode - The value to shift.
  3593. * @returns {OperatorNode}
  3594. */
  3595. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3596. addMethodChaining( 'add', add );
  3597. addMethodChaining( 'sub', sub );
  3598. addMethodChaining( 'mul', mul );
  3599. addMethodChaining( 'div', div );
  3600. addMethodChaining( 'modInt', modInt );
  3601. addMethodChaining( 'equal', equal );
  3602. addMethodChaining( 'notEqual', notEqual );
  3603. addMethodChaining( 'lessThan', lessThan );
  3604. addMethodChaining( 'greaterThan', greaterThan );
  3605. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3606. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3607. addMethodChaining( 'and', and );
  3608. addMethodChaining( 'or', or );
  3609. addMethodChaining( 'not', not );
  3610. addMethodChaining( 'xor', xor );
  3611. addMethodChaining( 'bitAnd', bitAnd );
  3612. addMethodChaining( 'bitNot', bitNot );
  3613. addMethodChaining( 'bitOr', bitOr );
  3614. addMethodChaining( 'bitXor', bitXor );
  3615. addMethodChaining( 'shiftLeft', shiftLeft );
  3616. addMethodChaining( 'shiftRight', shiftRight );
  3617. /**
  3618. * @tsl
  3619. * @function
  3620. * @deprecated since r168. Use {@link modInt} instead.
  3621. *
  3622. * @param {...any} params
  3623. * @returns {Function}
  3624. */
  3625. const remainder = ( ...params ) => { // @deprecated, r168
  3626. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3627. return modInt( ...params );
  3628. };
  3629. addMethodChaining( 'remainder', remainder );
  3630. /**
  3631. * This node represents a variety of mathematical methods available in shaders.
  3632. * They are divided into three categories:
  3633. *
  3634. * - Methods with one input like `sin`, `cos` or `normalize`.
  3635. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3636. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3637. *
  3638. * @augments TempNode
  3639. */
  3640. class MathNode extends TempNode {
  3641. static get type() {
  3642. return 'MathNode';
  3643. }
  3644. /**
  3645. * Constructs a new math node.
  3646. *
  3647. * @param {string} method - The method name.
  3648. * @param {Node} aNode - The first input.
  3649. * @param {?Node} [bNode=null] - The second input.
  3650. * @param {?Node} [cNode=null] - The third input.
  3651. */
  3652. constructor( method, aNode, bNode = null, cNode = null ) {
  3653. super();
  3654. /**
  3655. * The method name.
  3656. *
  3657. * @type {string}
  3658. */
  3659. this.method = method;
  3660. /**
  3661. * The first input.
  3662. *
  3663. * @type {Node}
  3664. */
  3665. this.aNode = aNode;
  3666. /**
  3667. * The second input.
  3668. *
  3669. * @type {?Node}
  3670. * @default null
  3671. */
  3672. this.bNode = bNode;
  3673. /**
  3674. * The third input.
  3675. *
  3676. * @type {?Node}
  3677. * @default null
  3678. */
  3679. this.cNode = cNode;
  3680. /**
  3681. * This flag can be used for type testing.
  3682. *
  3683. * @type {boolean}
  3684. * @readonly
  3685. * @default true
  3686. */
  3687. this.isMathNode = true;
  3688. }
  3689. /**
  3690. * The input type is inferred from the node types of the input nodes.
  3691. *
  3692. * @param {NodeBuilder} builder - The current node builder.
  3693. * @return {string} The input type.
  3694. */
  3695. getInputType( builder ) {
  3696. const aType = this.aNode.getNodeType( builder );
  3697. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3698. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3699. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3700. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3701. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3702. if ( aLen > bLen && aLen > cLen ) {
  3703. return aType;
  3704. } else if ( bLen > cLen ) {
  3705. return bType;
  3706. } else if ( cLen > aLen ) {
  3707. return cType;
  3708. }
  3709. return aType;
  3710. }
  3711. /**
  3712. * The selected method as well as the input type determine the node type of this node.
  3713. *
  3714. * @param {NodeBuilder} builder - The current node builder.
  3715. * @return {string} The node type.
  3716. */
  3717. getNodeType( builder ) {
  3718. const method = this.method;
  3719. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3720. return 'float';
  3721. } else if ( method === MathNode.CROSS ) {
  3722. return 'vec3';
  3723. } else if ( method === MathNode.ALL ) {
  3724. return 'bool';
  3725. } else if ( method === MathNode.EQUALS ) {
  3726. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3727. } else if ( method === MathNode.MOD ) {
  3728. return this.aNode.getNodeType( builder );
  3729. } else {
  3730. return this.getInputType( builder );
  3731. }
  3732. }
  3733. generate( builder, output ) {
  3734. let method = this.method;
  3735. const type = this.getNodeType( builder );
  3736. const inputType = this.getInputType( builder );
  3737. const a = this.aNode;
  3738. const b = this.bNode;
  3739. const c = this.cNode;
  3740. const coordinateSystem = builder.renderer.coordinateSystem;
  3741. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3742. // dir can be either a direction vector or a normal vector
  3743. // upper-left 3x3 of matrix is assumed to be orthogonal
  3744. let tA = a;
  3745. let tB = b;
  3746. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3747. tB = vec4( vec3( tB ), 0.0 );
  3748. } else {
  3749. tA = vec4( vec3( tA ), 0.0 );
  3750. }
  3751. const mulNode = mul( tA, tB ).xyz;
  3752. return normalize( mulNode ).build( builder, output );
  3753. } else if ( method === MathNode.NEGATE ) {
  3754. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3755. } else if ( method === MathNode.ONE_MINUS ) {
  3756. return sub( 1.0, a ).build( builder, output );
  3757. } else if ( method === MathNode.RECIPROCAL ) {
  3758. return div( 1.0, a ).build( builder, output );
  3759. } else if ( method === MathNode.DIFFERENCE ) {
  3760. return abs( sub( a, b ) ).build( builder, output );
  3761. } else {
  3762. const params = [];
  3763. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3764. params.push(
  3765. a.build( builder, type ),
  3766. b.build( builder, type )
  3767. );
  3768. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3769. params.push(
  3770. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3771. b.build( builder, inputType )
  3772. );
  3773. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3774. params.push(
  3775. a.build( builder, inputType ),
  3776. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3777. );
  3778. } else if ( method === MathNode.REFRACT ) {
  3779. params.push(
  3780. a.build( builder, inputType ),
  3781. b.build( builder, inputType ),
  3782. c.build( builder, 'float' )
  3783. );
  3784. } else if ( method === MathNode.MIX ) {
  3785. params.push(
  3786. a.build( builder, inputType ),
  3787. b.build( builder, inputType ),
  3788. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3789. );
  3790. } else {
  3791. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3792. method = 'atan2';
  3793. }
  3794. params.push( a.build( builder, inputType ) );
  3795. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3796. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3797. }
  3798. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3799. }
  3800. }
  3801. serialize( data ) {
  3802. super.serialize( data );
  3803. data.method = this.method;
  3804. }
  3805. deserialize( data ) {
  3806. super.deserialize( data );
  3807. this.method = data.method;
  3808. }
  3809. }
  3810. // 1 input
  3811. MathNode.ALL = 'all';
  3812. MathNode.ANY = 'any';
  3813. MathNode.RADIANS = 'radians';
  3814. MathNode.DEGREES = 'degrees';
  3815. MathNode.EXP = 'exp';
  3816. MathNode.EXP2 = 'exp2';
  3817. MathNode.LOG = 'log';
  3818. MathNode.LOG2 = 'log2';
  3819. MathNode.SQRT = 'sqrt';
  3820. MathNode.INVERSE_SQRT = 'inversesqrt';
  3821. MathNode.FLOOR = 'floor';
  3822. MathNode.CEIL = 'ceil';
  3823. MathNode.NORMALIZE = 'normalize';
  3824. MathNode.FRACT = 'fract';
  3825. MathNode.SIN = 'sin';
  3826. MathNode.COS = 'cos';
  3827. MathNode.TAN = 'tan';
  3828. MathNode.ASIN = 'asin';
  3829. MathNode.ACOS = 'acos';
  3830. MathNode.ATAN = 'atan';
  3831. MathNode.ABS = 'abs';
  3832. MathNode.SIGN = 'sign';
  3833. MathNode.LENGTH = 'length';
  3834. MathNode.NEGATE = 'negate';
  3835. MathNode.ONE_MINUS = 'oneMinus';
  3836. MathNode.DFDX = 'dFdx';
  3837. MathNode.DFDY = 'dFdy';
  3838. MathNode.ROUND = 'round';
  3839. MathNode.RECIPROCAL = 'reciprocal';
  3840. MathNode.TRUNC = 'trunc';
  3841. MathNode.FWIDTH = 'fwidth';
  3842. MathNode.TRANSPOSE = 'transpose';
  3843. // 2 inputs
  3844. MathNode.BITCAST = 'bitcast';
  3845. MathNode.EQUALS = 'equals';
  3846. MathNode.MIN = 'min';
  3847. MathNode.MAX = 'max';
  3848. MathNode.MOD = 'mod';
  3849. MathNode.STEP = 'step';
  3850. MathNode.REFLECT = 'reflect';
  3851. MathNode.DISTANCE = 'distance';
  3852. MathNode.DIFFERENCE = 'difference';
  3853. MathNode.DOT = 'dot';
  3854. MathNode.CROSS = 'cross';
  3855. MathNode.POW = 'pow';
  3856. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3857. // 3 inputs
  3858. MathNode.MIX = 'mix';
  3859. MathNode.CLAMP = 'clamp';
  3860. MathNode.REFRACT = 'refract';
  3861. MathNode.SMOOTHSTEP = 'smoothstep';
  3862. MathNode.FACEFORWARD = 'faceforward';
  3863. // 1 inputs
  3864. /**
  3865. * A small value used to handle floating-point precision errors.
  3866. *
  3867. * @tsl
  3868. * @type {Node<float>}
  3869. */
  3870. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3871. /**
  3872. * Represents infinity.
  3873. *
  3874. * @tsl
  3875. * @type {Node<float>}
  3876. */
  3877. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3878. /**
  3879. * Represents PI.
  3880. *
  3881. * @tsl
  3882. * @type {Node<float>}
  3883. */
  3884. const PI = /*@__PURE__*/ float( Math.PI );
  3885. /**
  3886. * Represents PI * 2.
  3887. *
  3888. * @tsl
  3889. * @type {Node<float>}
  3890. */
  3891. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3892. /**
  3893. * Returns `true` if all components of `x` are `true`.
  3894. *
  3895. * @tsl
  3896. * @function
  3897. * @param {Node | number} x - The parameter.
  3898. * @returns {Node<bool>}
  3899. */
  3900. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3901. /**
  3902. * Returns `true` if any components of `x` are `true`.
  3903. *
  3904. * @tsl
  3905. * @function
  3906. * @param {Node | number} x - The parameter.
  3907. * @returns {Node<bool>}
  3908. */
  3909. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3910. /**
  3911. * Converts a quantity in degrees to radians.
  3912. *
  3913. * @tsl
  3914. * @function
  3915. * @param {Node | number} x - The input in degrees.
  3916. * @returns {Node}
  3917. */
  3918. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3919. /**
  3920. * Convert a quantity in radians to degrees.
  3921. *
  3922. * @tsl
  3923. * @function
  3924. * @param {Node | number} x - The input in radians.
  3925. * @returns {Node}
  3926. */
  3927. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3928. /**
  3929. * Returns the natural exponentiation of the parameter.
  3930. *
  3931. * @tsl
  3932. * @function
  3933. * @param {Node | number} x - The parameter.
  3934. * @returns {Node}
  3935. */
  3936. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3937. /**
  3938. * Returns 2 raised to the power of the parameter.
  3939. *
  3940. * @tsl
  3941. * @function
  3942. * @param {Node | number} x - The parameter.
  3943. * @returns {Node}
  3944. */
  3945. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3946. /**
  3947. * Returns the natural logarithm of the parameter.
  3948. *
  3949. * @tsl
  3950. * @function
  3951. * @param {Node | number} x - The parameter.
  3952. * @returns {Node}
  3953. */
  3954. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3955. /**
  3956. * Returns the base 2 logarithm of the parameter.
  3957. *
  3958. * @tsl
  3959. * @function
  3960. * @param {Node | number} x - The parameter.
  3961. * @returns {Node}
  3962. */
  3963. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3964. /**
  3965. * Returns the square root of the parameter.
  3966. *
  3967. * @tsl
  3968. * @function
  3969. * @param {Node | number} x - The parameter.
  3970. * @returns {Node}
  3971. */
  3972. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3973. /**
  3974. * Returns the inverse of the square root of the parameter.
  3975. *
  3976. * @tsl
  3977. * @function
  3978. * @param {Node | number} x - The parameter.
  3979. * @returns {Node}
  3980. */
  3981. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3982. /**
  3983. * Finds the nearest integer less than or equal to the parameter.
  3984. *
  3985. * @tsl
  3986. * @function
  3987. * @param {Node | number} x - The parameter.
  3988. * @returns {Node}
  3989. */
  3990. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3991. /**
  3992. * Finds the nearest integer that is greater than or equal to the parameter.
  3993. *
  3994. * @tsl
  3995. * @function
  3996. * @param {Node | number} x - The parameter.
  3997. * @returns {Node}
  3998. */
  3999. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  4000. /**
  4001. * Calculates the unit vector in the same direction as the original vector.
  4002. *
  4003. * @tsl
  4004. * @function
  4005. * @param {Node} x - The input vector.
  4006. * @returns {Node}
  4007. */
  4008. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  4009. /**
  4010. * Computes the fractional part of the parameter.
  4011. *
  4012. * @tsl
  4013. * @function
  4014. * @param {Node | number} x - The parameter.
  4015. * @returns {Node}
  4016. */
  4017. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  4018. /**
  4019. * Returns the sine of the parameter.
  4020. *
  4021. * @tsl
  4022. * @function
  4023. * @param {Node | number} x - The parameter.
  4024. * @returns {Node}
  4025. */
  4026. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  4027. /**
  4028. * Returns the cosine of the parameter.
  4029. *
  4030. * @tsl
  4031. * @function
  4032. * @param {Node | number} x - The parameter.
  4033. * @returns {Node}
  4034. */
  4035. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  4036. /**
  4037. * Returns the tangent of the parameter.
  4038. *
  4039. * @tsl
  4040. * @function
  4041. * @param {Node | number} x - The parameter.
  4042. * @returns {Node}
  4043. */
  4044. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  4045. /**
  4046. * Returns the arcsine of the parameter.
  4047. *
  4048. * @tsl
  4049. * @function
  4050. * @param {Node | number} x - The parameter.
  4051. * @returns {Node}
  4052. */
  4053. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  4054. /**
  4055. * Returns the arccosine of the parameter.
  4056. *
  4057. * @tsl
  4058. * @function
  4059. * @param {Node | number} x - The parameter.
  4060. * @returns {Node}
  4061. */
  4062. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  4063. /**
  4064. * Returns the arc-tangent of the parameter.
  4065. * If two parameters are provided, the result is `atan2(y/x)`.
  4066. *
  4067. * @tsl
  4068. * @function
  4069. * @param {Node | number} y - The y parameter.
  4070. * @param {?(Node | number)} x - The x parameter.
  4071. * @returns {Node}
  4072. */
  4073. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  4074. /**
  4075. * Returns the absolute value of the parameter.
  4076. *
  4077. * @tsl
  4078. * @function
  4079. * @param {Node | number} x - The parameter.
  4080. * @returns {Node}
  4081. */
  4082. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  4083. /**
  4084. * Extracts the sign of the parameter.
  4085. *
  4086. * @tsl
  4087. * @function
  4088. * @param {Node | number} x - The parameter.
  4089. * @returns {Node}
  4090. */
  4091. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  4092. /**
  4093. * Calculates the length of a vector.
  4094. *
  4095. * @tsl
  4096. * @function
  4097. * @param {Node} x - The parameter.
  4098. * @returns {Node<float>}
  4099. */
  4100. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  4101. /**
  4102. * Negates the value of the parameter (-x).
  4103. *
  4104. * @tsl
  4105. * @function
  4106. * @param {Node | number} x - The parameter.
  4107. * @returns {Node}
  4108. */
  4109. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  4110. /**
  4111. * Return `1` minus the parameter.
  4112. *
  4113. * @tsl
  4114. * @function
  4115. * @param {Node | number} x - The parameter.
  4116. * @returns {Node}
  4117. */
  4118. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  4119. /**
  4120. * Returns the partial derivative of the parameter with respect to x.
  4121. *
  4122. * @tsl
  4123. * @function
  4124. * @param {Node | number} x - The parameter.
  4125. * @returns {Node}
  4126. */
  4127. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  4128. /**
  4129. * Returns the partial derivative of the parameter with respect to y.
  4130. *
  4131. * @tsl
  4132. * @function
  4133. * @param {Node | number} x - The parameter.
  4134. * @returns {Node}
  4135. */
  4136. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  4137. /**
  4138. * Rounds the parameter to the nearest integer.
  4139. *
  4140. * @tsl
  4141. * @function
  4142. * @param {Node | number} x - The parameter.
  4143. * @returns {Node}
  4144. */
  4145. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  4146. /**
  4147. * Returns the reciprocal of the parameter `(1/x)`.
  4148. *
  4149. * @tsl
  4150. * @function
  4151. * @param {Node | number} x - The parameter.
  4152. * @returns {Node}
  4153. */
  4154. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  4155. /**
  4156. * Truncates the parameter, removing the fractional part.
  4157. *
  4158. * @tsl
  4159. * @function
  4160. * @param {Node | number} x - The parameter.
  4161. * @returns {Node}
  4162. */
  4163. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  4164. /**
  4165. * Returns the sum of the absolute derivatives in x and y.
  4166. *
  4167. * @tsl
  4168. * @function
  4169. * @param {Node | number} x - The parameter.
  4170. * @returns {Node}
  4171. */
  4172. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  4173. /**
  4174. * Returns the transpose of a matrix.
  4175. *
  4176. * @tsl
  4177. * @function
  4178. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4179. * @returns {Node}
  4180. */
  4181. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  4182. // 2 inputs
  4183. /**
  4184. * Reinterpret the bit representation of a value in one type as a value in another type.
  4185. *
  4186. * @tsl
  4187. * @function
  4188. * @param {Node | number} x - The parameter.
  4189. * @param {string} y - The new type.
  4190. * @returns {Node}
  4191. */
  4192. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  4193. /**
  4194. * Returns `true` if `x` equals `y`.
  4195. *
  4196. * @tsl
  4197. * @function
  4198. * @param {Node | number} x - The first parameter.
  4199. * @param {Node | number} y - The second parameter.
  4200. * @returns {Node<bool>}
  4201. */
  4202. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  4203. /**
  4204. * Returns the lesser of two values.
  4205. *
  4206. * @tsl
  4207. * @function
  4208. * @param {Node | number} x - The y parameter.
  4209. * @param {Node | number} y - The x parameter.
  4210. * @returns {Node}
  4211. */
  4212. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  4213. /**
  4214. * Returns the greater of two values.
  4215. *
  4216. * @tsl
  4217. * @function
  4218. * @param {Node | number} x - The y parameter.
  4219. * @param {Node | number} y - The x parameter.
  4220. * @returns {Node}
  4221. */
  4222. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  4223. /**
  4224. * Computes the remainder of dividing the first node by the second one.
  4225. *
  4226. * @tsl
  4227. * @function
  4228. * @param {Node | number} x - The y parameter.
  4229. * @param {Node | number} y - The x parameter.
  4230. * @returns {Node}
  4231. */
  4232. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  4233. /**
  4234. * Generate a step function by comparing two values.
  4235. *
  4236. * @tsl
  4237. * @function
  4238. * @param {Node | number} x - The y parameter.
  4239. * @param {Node | number} y - The x parameter.
  4240. * @returns {Node}
  4241. */
  4242. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  4243. /**
  4244. * Calculates the reflection direction for an incident vector.
  4245. *
  4246. * @tsl
  4247. * @function
  4248. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4249. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4250. * @returns {Node<vec2|vec3|vec4>}
  4251. */
  4252. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  4253. /**
  4254. * Calculates the distance between two points.
  4255. *
  4256. * @tsl
  4257. * @function
  4258. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4259. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4260. * @returns {Node<float>}
  4261. */
  4262. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  4263. /**
  4264. * Calculates the absolute difference between two values.
  4265. *
  4266. * @tsl
  4267. * @function
  4268. * @param {Node | number} x - The first parameter.
  4269. * @param {Node | number} y - The second parameter.
  4270. * @returns {Node}
  4271. */
  4272. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  4273. /**
  4274. * Calculates the dot product of two vectors.
  4275. *
  4276. * @tsl
  4277. * @function
  4278. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4279. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4280. * @returns {Node<float>}
  4281. */
  4282. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  4283. /**
  4284. * Calculates the cross product of two vectors.
  4285. *
  4286. * @tsl
  4287. * @function
  4288. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4289. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4290. * @returns {Node<vec2|vec3|vec4>}
  4291. */
  4292. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  4293. /**
  4294. * Return the value of the first parameter raised to the power of the second one.
  4295. *
  4296. * @tsl
  4297. * @function
  4298. * @param {Node | number} x - The first parameter.
  4299. * @param {Node | number} y - The second parameter.
  4300. * @returns {Node}
  4301. */
  4302. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  4303. /**
  4304. * Returns the square of the parameter.
  4305. *
  4306. * @tsl
  4307. * @function
  4308. * @param {Node | number} x - The first parameter.
  4309. * @returns {Node}
  4310. */
  4311. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4312. /**
  4313. * Returns the cube of the parameter.
  4314. *
  4315. * @tsl
  4316. * @function
  4317. * @param {Node | number} x - The first parameter.
  4318. * @returns {Node}
  4319. */
  4320. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4321. /**
  4322. * Returns the fourth power of the parameter.
  4323. *
  4324. * @tsl
  4325. * @function
  4326. * @param {Node | number} x - The first parameter.
  4327. * @returns {Node}
  4328. */
  4329. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4330. /**
  4331. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4332. *
  4333. * @tsl
  4334. * @function
  4335. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4336. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4337. * @returns {Node}
  4338. */
  4339. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4340. /**
  4341. * Returns the cube root of a number.
  4342. *
  4343. * @tsl
  4344. * @function
  4345. * @param {Node | number} a - The first parameter.
  4346. * @returns {Node}
  4347. */
  4348. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4349. /**
  4350. * Calculate the squared length of a vector.
  4351. *
  4352. * @tsl
  4353. * @function
  4354. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4355. * @returns {Node<float>}
  4356. */
  4357. const lengthSq = ( a ) => dot( a, a );
  4358. /**
  4359. * Linearly interpolates between two values.
  4360. *
  4361. * @tsl
  4362. * @function
  4363. * @param {Node | number} a - The first parameter.
  4364. * @param {Node | number} b - The second parameter.
  4365. * @param {Node | number} t - The interpolation value.
  4366. * @returns {Node}
  4367. */
  4368. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4369. /**
  4370. * Constrains a value to lie between two further values.
  4371. *
  4372. * @tsl
  4373. * @function
  4374. * @param {Node | number} value - The value to constrain.
  4375. * @param {Node | number} [low=0] - The lower bound.
  4376. * @param {Node | number} [high=1] - The upper bound.
  4377. * @returns {Node}
  4378. */
  4379. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4380. /**
  4381. * Constrains a value between `0` and `1`.
  4382. *
  4383. * @tsl
  4384. * @function
  4385. * @param {Node | number} value - The value to constrain.
  4386. * @returns {Node}
  4387. */
  4388. const saturate = ( value ) => clamp( value );
  4389. /**
  4390. * Calculates the refraction direction for an incident vector.
  4391. *
  4392. * @tsl
  4393. * @function
  4394. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4395. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4396. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4397. * @returns {Node<vec2|vec3|vec4>}
  4398. */
  4399. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4400. /**
  4401. * Performs a Hermite interpolation between two values.
  4402. *
  4403. * @tsl
  4404. * @function
  4405. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4406. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4407. * @param {Node | number} x - The source value for interpolation.
  4408. * @returns {Node}
  4409. */
  4410. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4411. /**
  4412. * Returns a vector pointing in the same direction as another.
  4413. *
  4414. * @tsl
  4415. * @function
  4416. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4417. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4418. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4419. * @returns {Node<vec2|vec3|vec4>}
  4420. */
  4421. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4422. /**
  4423. * Returns a random value for the given uv.
  4424. *
  4425. * @tsl
  4426. * @function
  4427. * @param {Node<vec2>} uv - The uv node.
  4428. * @returns {Node<float>}
  4429. */
  4430. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4431. const a = 12.9898, b = 78.233, c = 43758.5453;
  4432. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4433. return fract( sin( sn ).mul( c ) );
  4434. } );
  4435. /**
  4436. * Alias for `mix()` with a different parameter order.
  4437. *
  4438. * @tsl
  4439. * @function
  4440. * @param {Node | number} t - The interpolation value.
  4441. * @param {Node | number} e1 - The first parameter.
  4442. * @param {Node | number} e2 - The second parameter.
  4443. * @returns {Node}
  4444. */
  4445. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4446. /**
  4447. * Alias for `smoothstep()` with a different parameter order.
  4448. *
  4449. * @tsl
  4450. * @function
  4451. * @param {Node | number} x - The source value for interpolation.
  4452. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4453. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4454. * @returns {Node}
  4455. */
  4456. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4457. /**
  4458. * Returns the arc-tangent of the quotient of its parameters.
  4459. *
  4460. * @tsl
  4461. * @function
  4462. * @deprecated since r172. Use {@link atan} instead.
  4463. *
  4464. * @param {Node | number} y - The y parameter.
  4465. * @param {Node | number} x - The x parameter.
  4466. * @returns {Node}
  4467. */
  4468. const atan2 = ( y, x ) => { // @deprecated, r172
  4469. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4470. return atan( y, x );
  4471. };
  4472. // GLSL alias function
  4473. const faceforward = faceForward;
  4474. const inversesqrt = inverseSqrt;
  4475. // Method chaining
  4476. addMethodChaining( 'all', all );
  4477. addMethodChaining( 'any', any );
  4478. addMethodChaining( 'equals', equals );
  4479. addMethodChaining( 'radians', radians );
  4480. addMethodChaining( 'degrees', degrees );
  4481. addMethodChaining( 'exp', exp );
  4482. addMethodChaining( 'exp2', exp2 );
  4483. addMethodChaining( 'log', log );
  4484. addMethodChaining( 'log2', log2 );
  4485. addMethodChaining( 'sqrt', sqrt );
  4486. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4487. addMethodChaining( 'floor', floor );
  4488. addMethodChaining( 'ceil', ceil );
  4489. addMethodChaining( 'normalize', normalize );
  4490. addMethodChaining( 'fract', fract );
  4491. addMethodChaining( 'sin', sin );
  4492. addMethodChaining( 'cos', cos );
  4493. addMethodChaining( 'tan', tan );
  4494. addMethodChaining( 'asin', asin );
  4495. addMethodChaining( 'acos', acos );
  4496. addMethodChaining( 'atan', atan );
  4497. addMethodChaining( 'abs', abs );
  4498. addMethodChaining( 'sign', sign );
  4499. addMethodChaining( 'length', length );
  4500. addMethodChaining( 'lengthSq', lengthSq );
  4501. addMethodChaining( 'negate', negate );
  4502. addMethodChaining( 'oneMinus', oneMinus );
  4503. addMethodChaining( 'dFdx', dFdx );
  4504. addMethodChaining( 'dFdy', dFdy );
  4505. addMethodChaining( 'round', round );
  4506. addMethodChaining( 'reciprocal', reciprocal );
  4507. addMethodChaining( 'trunc', trunc );
  4508. addMethodChaining( 'fwidth', fwidth );
  4509. addMethodChaining( 'atan2', atan2 );
  4510. addMethodChaining( 'min', min$1 );
  4511. addMethodChaining( 'max', max$1 );
  4512. addMethodChaining( 'mod', mod );
  4513. addMethodChaining( 'step', step );
  4514. addMethodChaining( 'reflect', reflect );
  4515. addMethodChaining( 'distance', distance );
  4516. addMethodChaining( 'dot', dot );
  4517. addMethodChaining( 'cross', cross );
  4518. addMethodChaining( 'pow', pow );
  4519. addMethodChaining( 'pow2', pow2 );
  4520. addMethodChaining( 'pow3', pow3 );
  4521. addMethodChaining( 'pow4', pow4 );
  4522. addMethodChaining( 'transformDirection', transformDirection );
  4523. addMethodChaining( 'mix', mixElement );
  4524. addMethodChaining( 'clamp', clamp );
  4525. addMethodChaining( 'refract', refract );
  4526. addMethodChaining( 'smoothstep', smoothstepElement );
  4527. addMethodChaining( 'faceForward', faceForward );
  4528. addMethodChaining( 'difference', difference );
  4529. addMethodChaining( 'saturate', saturate );
  4530. addMethodChaining( 'cbrt', cbrt );
  4531. addMethodChaining( 'transpose', transpose );
  4532. addMethodChaining( 'rand', rand );
  4533. /**
  4534. * Represents a logical `if/else` statement. Can be used as an alternative
  4535. * to the `If()`/`Else()` syntax.
  4536. *
  4537. * The corresponding TSL `select()` looks like so:
  4538. * ```js
  4539. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4540. * ```
  4541. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4542. * determine the outcome of the entire statement.
  4543. *
  4544. * @augments Node
  4545. */
  4546. class ConditionalNode extends Node {
  4547. static get type() {
  4548. return 'ConditionalNode';
  4549. }
  4550. /**
  4551. * Constructs a new conditional node.
  4552. *
  4553. * @param {Node} condNode - The node that defines the condition.
  4554. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4555. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4556. */
  4557. constructor( condNode, ifNode, elseNode = null ) {
  4558. super();
  4559. /**
  4560. * The node that defines the condition.
  4561. *
  4562. * @type {Node}
  4563. */
  4564. this.condNode = condNode;
  4565. /**
  4566. * The node that is evaluate when the condition ends up `true`.
  4567. *
  4568. * @type {Node}
  4569. */
  4570. this.ifNode = ifNode;
  4571. /**
  4572. * The node that is evaluate when the condition ends up `false`.
  4573. *
  4574. * @type {?Node}
  4575. * @default null
  4576. */
  4577. this.elseNode = elseNode;
  4578. }
  4579. /**
  4580. * This method is overwritten since the node type is inferred from the if/else
  4581. * nodes.
  4582. *
  4583. * @param {NodeBuilder} builder - The current node builder.
  4584. * @return {string} The node type.
  4585. */
  4586. getNodeType( builder ) {
  4587. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4588. if ( ifNode === undefined ) {
  4589. // fallback setup
  4590. this.setup( builder );
  4591. return this.getNodeType( builder );
  4592. }
  4593. const ifType = ifNode.getNodeType( builder );
  4594. if ( elseNode !== null ) {
  4595. const elseType = elseNode.getNodeType( builder );
  4596. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4597. return elseType;
  4598. }
  4599. }
  4600. return ifType;
  4601. }
  4602. setup( builder ) {
  4603. const condNode = this.condNode.cache();
  4604. const ifNode = this.ifNode.cache();
  4605. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4606. //
  4607. const currentNodeBlock = builder.context.nodeBlock;
  4608. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4609. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4610. //
  4611. const properties = builder.getNodeProperties( this );
  4612. properties.condNode = condNode;
  4613. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4614. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4615. }
  4616. generate( builder, output ) {
  4617. const type = this.getNodeType( builder );
  4618. const nodeData = builder.getDataFromNode( this );
  4619. if ( nodeData.nodeProperty !== undefined ) {
  4620. return nodeData.nodeProperty;
  4621. }
  4622. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4623. const needsOutput = output !== 'void';
  4624. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4625. nodeData.nodeProperty = nodeProperty;
  4626. const nodeSnippet = condNode.build( builder, 'bool' );
  4627. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4628. let ifSnippet = ifNode.build( builder, type );
  4629. if ( ifSnippet ) {
  4630. if ( needsOutput ) {
  4631. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4632. } else {
  4633. ifSnippet = 'return ' + ifSnippet + ';';
  4634. }
  4635. }
  4636. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4637. if ( elseNode !== null ) {
  4638. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4639. let elseSnippet = elseNode.build( builder, type );
  4640. if ( elseSnippet ) {
  4641. if ( needsOutput ) {
  4642. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4643. } else {
  4644. elseSnippet = 'return ' + elseSnippet + ';';
  4645. }
  4646. }
  4647. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4648. } else {
  4649. builder.addFlowCode( '\n\n' );
  4650. }
  4651. return builder.format( nodeProperty, type, output );
  4652. }
  4653. }
  4654. /**
  4655. * TSL function for creating a conditional node.
  4656. *
  4657. * @tsl
  4658. * @function
  4659. * @param {Node} condNode - The node that defines the condition.
  4660. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4661. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4662. * @returns {ConditionalNode}
  4663. */
  4664. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4665. addMethodChaining( 'select', select );
  4666. // Deprecated
  4667. /**
  4668. * @tsl
  4669. * @function
  4670. * @deprecated since r168. Use {@link select} instead.
  4671. *
  4672. * @param {...any} params
  4673. * @returns {ConditionalNode}
  4674. */
  4675. const cond = ( ...params ) => { // @deprecated, r168
  4676. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4677. return select( ...params );
  4678. };
  4679. addMethodChaining( 'cond', cond );
  4680. /**
  4681. * This node can be used as a context management component for another node.
  4682. * {@link NodeBuilder} performs its node building process in a specific context and
  4683. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4684. *
  4685. * ```js
  4686. *node.context( { getUV: () => customCoord } );
  4687. *```
  4688. * @augments Node
  4689. */
  4690. class ContextNode extends Node {
  4691. static get type() {
  4692. return 'ContextNode';
  4693. }
  4694. /**
  4695. * Constructs a new context node.
  4696. *
  4697. * @param {Node} node - The node whose context should be modified.
  4698. * @param {Object} [value={}] - The modified context data.
  4699. */
  4700. constructor( node, value = {} ) {
  4701. super();
  4702. /**
  4703. * This flag can be used for type testing.
  4704. *
  4705. * @type {boolean}
  4706. * @readonly
  4707. * @default true
  4708. */
  4709. this.isContextNode = true;
  4710. /**
  4711. * The node whose context should be modified.
  4712. *
  4713. * @type {Node}
  4714. */
  4715. this.node = node;
  4716. /**
  4717. * The modified context data.
  4718. *
  4719. * @type {Object}
  4720. * @default {}
  4721. */
  4722. this.value = value;
  4723. }
  4724. /**
  4725. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  4726. *
  4727. * @return {Node} A reference to {@link ContextNode#node}.
  4728. */
  4729. getScope() {
  4730. return this.node.getScope();
  4731. }
  4732. /**
  4733. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  4734. *
  4735. * @param {NodeBuilder} builder - The current node builder.
  4736. * @return {string} The node type.
  4737. */
  4738. getNodeType( builder ) {
  4739. return this.node.getNodeType( builder );
  4740. }
  4741. analyze( builder ) {
  4742. this.node.build( builder );
  4743. }
  4744. setup( builder ) {
  4745. const previousContext = builder.getContext();
  4746. builder.setContext( { ...builder.context, ...this.value } );
  4747. const node = this.node.build( builder );
  4748. builder.setContext( previousContext );
  4749. return node;
  4750. }
  4751. generate( builder, output ) {
  4752. const previousContext = builder.getContext();
  4753. builder.setContext( { ...builder.context, ...this.value } );
  4754. const snippet = this.node.build( builder, output );
  4755. builder.setContext( previousContext );
  4756. return snippet;
  4757. }
  4758. }
  4759. /**
  4760. * TSL function for creating a context node.
  4761. *
  4762. * @tsl
  4763. * @function
  4764. * @param {Node} node - The node whose context should be modified.
  4765. * @param {Object} [value={}] - The modified context data.
  4766. * @returns {ContextNode}
  4767. */
  4768. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4769. /**
  4770. * TSL function for defining a label context value for a given node.
  4771. *
  4772. * @tsl
  4773. * @function
  4774. * @param {Node} node - The node whose context should be modified.
  4775. * @param {string} name - The name/label to set.
  4776. * @returns {ContextNode}
  4777. */
  4778. const label = ( node, name ) => context( node, { label: name } );
  4779. addMethodChaining( 'context', context );
  4780. addMethodChaining( 'label', label );
  4781. /**
  4782. * Class for representing shader variables as nodes. Variables are created from
  4783. * existing nodes like the following:
  4784. *
  4785. * ```js
  4786. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4787. * ```
  4788. *
  4789. * @augments Node
  4790. */
  4791. class VarNode extends Node {
  4792. static get type() {
  4793. return 'VarNode';
  4794. }
  4795. /**
  4796. * Constructs a new variable node.
  4797. *
  4798. * @param {Node} node - The node for which a variable should be created.
  4799. * @param {?string} [name=null] - The name of the variable in the shader.
  4800. * @param {boolean} [readOnly=false] - The read-only flag.
  4801. */
  4802. constructor( node, name = null, readOnly = false ) {
  4803. super();
  4804. /**
  4805. * The node for which a variable should be created.
  4806. *
  4807. * @type {Node}
  4808. */
  4809. this.node = node;
  4810. /**
  4811. * The name of the variable in the shader. If no name is defined,
  4812. * the node system auto-generates one.
  4813. *
  4814. * @type {?string}
  4815. * @default null
  4816. */
  4817. this.name = name;
  4818. /**
  4819. * `VarNode` sets this property to `true` by default.
  4820. *
  4821. * @type {boolean}
  4822. * @default true
  4823. */
  4824. this.global = true;
  4825. /**
  4826. * This flag can be used for type testing.
  4827. *
  4828. * @type {boolean}
  4829. * @readonly
  4830. * @default true
  4831. */
  4832. this.isVarNode = true;
  4833. /**
  4834. *
  4835. * The read-only flag.
  4836. *
  4837. * @type {boolean}
  4838. * @default false
  4839. */
  4840. this.readOnly = readOnly;
  4841. }
  4842. getHash( builder ) {
  4843. return this.name || super.getHash( builder );
  4844. }
  4845. getMemberType( builder, name ) {
  4846. return this.node.getMemberType( builder, name );
  4847. }
  4848. getElementType( builder ) {
  4849. return this.node.getElementType( builder );
  4850. }
  4851. getNodeType( builder ) {
  4852. return this.node.getNodeType( builder );
  4853. }
  4854. generate( builder ) {
  4855. const { node, name, readOnly } = this;
  4856. const { renderer } = builder;
  4857. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4858. let isDeterministic = false;
  4859. let shouldTreatAsReadOnly = false;
  4860. if ( readOnly ) {
  4861. isDeterministic = builder.isDeterministic( node );
  4862. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4863. }
  4864. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4865. const snippet = node.build( builder, vectorType );
  4866. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4867. const propertyName = builder.getPropertyName( nodeVar );
  4868. let declarationPrefix = propertyName;
  4869. if ( shouldTreatAsReadOnly ) {
  4870. if ( isWebGPUBackend ) {
  4871. declarationPrefix = isDeterministic
  4872. ? `const ${ propertyName }`
  4873. : `let ${ propertyName }`;
  4874. } else {
  4875. const count = builder.getArrayCount( node );
  4876. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  4877. }
  4878. }
  4879. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4880. return propertyName;
  4881. }
  4882. }
  4883. /**
  4884. * TSL function for creating a var node.
  4885. *
  4886. * @tsl
  4887. * @function
  4888. * @param {Node} node - The node for which a variable should be created.
  4889. * @param {?string} name - The name of the variable in the shader.
  4890. * @returns {VarNode}
  4891. */
  4892. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4893. /**
  4894. * TSL function for creating a var node.
  4895. *
  4896. * @tsl
  4897. * @function
  4898. * @param {Node} node - The node for which a variable should be created.
  4899. * @param {?string} name - The name of the variable in the shader.
  4900. * @returns {VarNode}
  4901. */
  4902. const Var = ( node, name = null ) => createVar( node, name ).append();
  4903. /**
  4904. * TSL function for creating a const node.
  4905. *
  4906. * @tsl
  4907. * @function
  4908. * @param {Node} node - The node for which a constant should be created.
  4909. * @param {?string} name - The name of the constant in the shader.
  4910. * @returns {VarNode}
  4911. */
  4912. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4913. // Method chaining
  4914. addMethodChaining( 'toVar', Var );
  4915. addMethodChaining( 'toConst', Const );
  4916. // Deprecated
  4917. /**
  4918. * @tsl
  4919. * @function
  4920. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4921. *
  4922. * @param {any} node
  4923. * @returns {VarNode}
  4924. */
  4925. const temp = ( node ) => { // @deprecated, r170
  4926. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4927. return createVar( node );
  4928. };
  4929. addMethodChaining( 'temp', temp );
  4930. /**
  4931. * Class for representing shader varyings as nodes. Varyings are create from
  4932. * existing nodes like the following:
  4933. *
  4934. * ```js
  4935. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4936. * ```
  4937. *
  4938. * @augments Node
  4939. */
  4940. class VaryingNode extends Node {
  4941. static get type() {
  4942. return 'VaryingNode';
  4943. }
  4944. /**
  4945. * Constructs a new varying node.
  4946. *
  4947. * @param {Node} node - The node for which a varying should be created.
  4948. * @param {?string} name - The name of the varying in the shader.
  4949. */
  4950. constructor( node, name = null ) {
  4951. super();
  4952. /**
  4953. * The node for which a varying should be created.
  4954. *
  4955. * @type {Node}
  4956. */
  4957. this.node = node;
  4958. /**
  4959. * The name of the varying in the shader. If no name is defined,
  4960. * the node system auto-generates one.
  4961. *
  4962. * @type {?string}
  4963. * @default null
  4964. */
  4965. this.name = name;
  4966. /**
  4967. * This flag can be used for type testing.
  4968. *
  4969. * @type {boolean}
  4970. * @readonly
  4971. * @default true
  4972. */
  4973. this.isVaryingNode = true;
  4974. }
  4975. /**
  4976. * The method is overwritten so it always returns `true`.
  4977. *
  4978. * @param {NodeBuilder} builder - The current node builder.
  4979. * @return {boolean} Whether this node is global or not.
  4980. */
  4981. isGlobal( /*builder*/ ) {
  4982. return true;
  4983. }
  4984. getHash( builder ) {
  4985. return this.name || super.getHash( builder );
  4986. }
  4987. getNodeType( builder ) {
  4988. // VaryingNode is auto type
  4989. return this.node.getNodeType( builder );
  4990. }
  4991. /**
  4992. * This method performs the setup of a varying node with the current node builder.
  4993. *
  4994. * @param {NodeBuilder} builder - The current node builder.
  4995. * @return {NodeVarying} The node varying from the node builder.
  4996. */
  4997. setupVarying( builder ) {
  4998. const properties = builder.getNodeProperties( this );
  4999. let varying = properties.varying;
  5000. if ( varying === undefined ) {
  5001. const name = this.name;
  5002. const type = this.getNodeType( builder );
  5003. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  5004. properties.node = this.node;
  5005. }
  5006. // this property can be used to check if the varying can be optimized for a variable
  5007. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5008. return varying;
  5009. }
  5010. setup( builder ) {
  5011. this.setupVarying( builder );
  5012. }
  5013. analyze( builder ) {
  5014. this.setupVarying( builder );
  5015. return this.node.analyze( builder );
  5016. }
  5017. generate( builder ) {
  5018. const properties = builder.getNodeProperties( this );
  5019. const varying = this.setupVarying( builder );
  5020. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  5021. if ( properties.propertyName === undefined || needsReassign ) {
  5022. const type = this.getNodeType( builder );
  5023. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5024. // force node run in vertex stage
  5025. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5026. properties.propertyName = propertyName;
  5027. if ( needsReassign ) {
  5028. // once reassign varying in fragment stage
  5029. properties.reassignPosition = false;
  5030. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  5031. properties.reassignPosition = true;
  5032. }
  5033. }
  5034. return builder.getPropertyName( varying );
  5035. }
  5036. }
  5037. /**
  5038. * TSL function for creating a varying node.
  5039. *
  5040. * @tsl
  5041. * @function
  5042. * @param {Node} node - The node for which a varying should be created.
  5043. * @param {?string} name - The name of the varying in the shader.
  5044. * @returns {VaryingNode}
  5045. */
  5046. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  5047. /**
  5048. * Computes a node in the vertex stage.
  5049. *
  5050. * @tsl
  5051. * @function
  5052. * @param {Node} node - The node which should be executed in the vertex stage.
  5053. * @returns {VaryingNode}
  5054. */
  5055. const vertexStage = ( node ) => varying( node );
  5056. addMethodChaining( 'toVarying', varying );
  5057. addMethodChaining( 'toVertexStage', vertexStage );
  5058. // Deprecated
  5059. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5060. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  5061. return varying( ...params );
  5062. } );
  5063. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5064. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  5065. return varying( ...params );
  5066. } );
  5067. /**
  5068. * Converts the given color value from sRGB to linear-sRGB color space.
  5069. *
  5070. * @tsl
  5071. * @function
  5072. * @param {Node<vec3>} color - The sRGB color.
  5073. * @return {Node<vec3>} The linear-sRGB color.
  5074. */
  5075. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5076. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5077. const b = color.mul( 0.0773993808 );
  5078. const factor = color.lessThanEqual( 0.04045 );
  5079. const rgbResult = mix( a, b, factor );
  5080. return rgbResult;
  5081. } ).setLayout( {
  5082. name: 'sRGBTransferEOTF',
  5083. type: 'vec3',
  5084. inputs: [
  5085. { name: 'color', type: 'vec3' }
  5086. ]
  5087. } );
  5088. /**
  5089. * Converts the given color value from linear-sRGB to sRGB color space.
  5090. *
  5091. * @tsl
  5092. * @function
  5093. * @param {Node<vec3>} color - The linear-sRGB color.
  5094. * @return {Node<vec3>} The sRGB color.
  5095. */
  5096. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5097. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5098. const b = color.mul( 12.92 );
  5099. const factor = color.lessThanEqual( 0.0031308 );
  5100. const rgbResult = mix( a, b, factor );
  5101. return rgbResult;
  5102. } ).setLayout( {
  5103. name: 'sRGBTransferOETF',
  5104. type: 'vec3',
  5105. inputs: [
  5106. { name: 'color', type: 'vec3' }
  5107. ]
  5108. } );
  5109. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5110. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5111. /**
  5112. * This node represents a color space conversion. Meaning it converts
  5113. * a color value from a source to a target color space.
  5114. *
  5115. * @augments TempNode
  5116. */
  5117. class ColorSpaceNode extends TempNode {
  5118. static get type() {
  5119. return 'ColorSpaceNode';
  5120. }
  5121. /**
  5122. * Constructs a new color space node.
  5123. *
  5124. * @param {Node} colorNode - Represents the color to convert.
  5125. * @param {string} source - The source color space.
  5126. * @param {string} target - The target color space.
  5127. */
  5128. constructor( colorNode, source, target ) {
  5129. super( 'vec4' );
  5130. /**
  5131. * Represents the color to convert.
  5132. *
  5133. * @type {Node}
  5134. */
  5135. this.colorNode = colorNode;
  5136. /**
  5137. * The source color space.
  5138. *
  5139. * @type {string}
  5140. */
  5141. this.source = source;
  5142. /**
  5143. * The target color space.
  5144. *
  5145. * @type {string}
  5146. */
  5147. this.target = target;
  5148. }
  5149. /**
  5150. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5151. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5152. * color management and renderer.
  5153. *
  5154. * @param {NodeBuilder} builder - The current node builder.
  5155. * @param {string} colorSpace - The color space to resolve.
  5156. * @return {string} The resolved color space.
  5157. */
  5158. resolveColorSpace( builder, colorSpace ) {
  5159. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5160. return ColorManagement.workingColorSpace;
  5161. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5162. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5163. }
  5164. return colorSpace;
  5165. }
  5166. setup( builder ) {
  5167. const { colorNode } = this;
  5168. const source = this.resolveColorSpace( builder, this.source );
  5169. const target = this.resolveColorSpace( builder, this.target );
  5170. let outputNode = colorNode;
  5171. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5172. return outputNode;
  5173. }
  5174. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5175. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5176. }
  5177. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5178. outputNode = vec4(
  5179. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5180. outputNode.a
  5181. );
  5182. }
  5183. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5184. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5185. }
  5186. return outputNode;
  5187. }
  5188. }
  5189. /**
  5190. * TSL function for converting a given color node to the current output color space.
  5191. *
  5192. * @tsl
  5193. * @function
  5194. * @param {Node} node - Represents the node to convert.
  5195. * @returns {ColorSpaceNode}
  5196. */
  5197. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  5198. /**
  5199. * TSL function for converting a given color node to the current working color space.
  5200. *
  5201. * @tsl
  5202. * @function
  5203. * @param {Node} node - Represents the node to convert.
  5204. * @returns {ColorSpaceNode}
  5205. */
  5206. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5207. /**
  5208. * TSL function for converting a given color node from the current working color space to the given color space.
  5209. *
  5210. * @tsl
  5211. * @function
  5212. * @param {Node} node - Represents the node to convert.
  5213. * @param {string} colorSpace - The target color space.
  5214. * @returns {ColorSpaceNode}
  5215. */
  5216. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5217. /**
  5218. * TSL function for converting a given color node from the given color space to the current working color space.
  5219. *
  5220. * @tsl
  5221. * @function
  5222. * @param {Node} node - Represents the node to convert.
  5223. * @param {string} colorSpace - The source color space.
  5224. * @returns {ColorSpaceNode}
  5225. */
  5226. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5227. /**
  5228. * TSL function for converting a given color node from one color space to another one.
  5229. *
  5230. * @tsl
  5231. * @function
  5232. * @param {Node} node - Represents the node to convert.
  5233. * @param {string} sourceColorSpace - The source color space.
  5234. * @param {string} targetColorSpace - The target color space.
  5235. * @returns {ColorSpaceNode}
  5236. */
  5237. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5238. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5239. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5240. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5241. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5242. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5243. /**
  5244. * This class is only relevant if the referenced property is array-like.
  5245. * In this case, `ReferenceElementNode` allows to refer to a specific
  5246. * element inside the data structure via an index.
  5247. *
  5248. * @augments ArrayElementNode
  5249. */
  5250. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5251. static get type() {
  5252. return 'ReferenceElementNode';
  5253. }
  5254. /**
  5255. * Constructs a new reference element node.
  5256. *
  5257. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5258. * @param {Node} indexNode - The index node that defines the element access.
  5259. */
  5260. constructor( referenceNode, indexNode ) {
  5261. super( referenceNode, indexNode );
  5262. /**
  5263. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5264. * property references to the current node.
  5265. *
  5266. * @type {?ReferenceBaseNode}
  5267. * @default null
  5268. */
  5269. this.referenceNode = referenceNode;
  5270. /**
  5271. * This flag can be used for type testing.
  5272. *
  5273. * @type {boolean}
  5274. * @readonly
  5275. * @default true
  5276. */
  5277. this.isReferenceElementNode = true;
  5278. }
  5279. /**
  5280. * This method is overwritten since the node type is inferred from
  5281. * the uniform type of the reference node.
  5282. *
  5283. * @return {string} The node type.
  5284. */
  5285. getNodeType() {
  5286. return this.referenceNode.uniformType;
  5287. }
  5288. generate( builder ) {
  5289. const snippet = super.generate( builder );
  5290. const arrayType = this.referenceNode.getNodeType();
  5291. const elementType = this.getNodeType();
  5292. return builder.format( snippet, arrayType, elementType );
  5293. }
  5294. };
  5295. /**
  5296. * Base class for nodes which establishes a reference to a property of another object.
  5297. * In this way, the value of the node is automatically linked to the value of
  5298. * referenced object. Reference nodes internally represent the linked value
  5299. * as a uniform.
  5300. *
  5301. * @augments Node
  5302. */
  5303. class ReferenceBaseNode extends Node {
  5304. static get type() {
  5305. return 'ReferenceBaseNode';
  5306. }
  5307. /**
  5308. * Constructs a new reference base node.
  5309. *
  5310. * @param {string} property - The name of the property the node refers to.
  5311. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5312. * @param {?Object} [object=null] - The object the property belongs to.
  5313. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5314. */
  5315. constructor( property, uniformType, object = null, count = null ) {
  5316. super();
  5317. /**
  5318. * The name of the property the node refers to.
  5319. *
  5320. * @type {string}
  5321. */
  5322. this.property = property;
  5323. /**
  5324. * The uniform type that should be used to represent the property value.
  5325. *
  5326. * @type {string}
  5327. */
  5328. this.uniformType = uniformType;
  5329. /**
  5330. * The object the property belongs to.
  5331. *
  5332. * @type {?Object}
  5333. * @default null
  5334. */
  5335. this.object = object;
  5336. /**
  5337. * When the linked property is an array, this parameter defines its length.
  5338. *
  5339. * @type {?number}
  5340. * @default null
  5341. */
  5342. this.count = count;
  5343. /**
  5344. * The property name might have dots so nested properties can be referred.
  5345. * The hierarchy of the names is stored inside this array.
  5346. *
  5347. * @type {Array<string>}
  5348. */
  5349. this.properties = property.split( '.' );
  5350. /**
  5351. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5352. * since the final reference might be updated from calling code.
  5353. *
  5354. * @type {?Object}
  5355. * @default null
  5356. */
  5357. this.reference = object;
  5358. /**
  5359. * The uniform node that holds the value of the reference node.
  5360. *
  5361. * @type {UniformNode}
  5362. * @default null
  5363. */
  5364. this.node = null;
  5365. /**
  5366. * The uniform group of the internal uniform.
  5367. *
  5368. * @type {UniformGroupNode}
  5369. * @default null
  5370. */
  5371. this.group = null;
  5372. /**
  5373. * Overwritten since reference nodes are updated per object.
  5374. *
  5375. * @type {string}
  5376. * @default 'object'
  5377. */
  5378. this.updateType = NodeUpdateType.OBJECT;
  5379. }
  5380. /**
  5381. * Sets the uniform group for this reference node.
  5382. *
  5383. * @param {UniformGroupNode} group - The uniform group to set.
  5384. * @return {ReferenceBaseNode} A reference to this node.
  5385. */
  5386. setGroup( group ) {
  5387. this.group = group;
  5388. return this;
  5389. }
  5390. /**
  5391. * When the referred property is array-like, this method can be used
  5392. * to access elements via an index node.
  5393. *
  5394. * @param {IndexNode} indexNode - indexNode.
  5395. * @return {ReferenceElementNode} A reference to an element.
  5396. */
  5397. element( indexNode ) {
  5398. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5399. }
  5400. /**
  5401. * Sets the node type which automatically defines the internal
  5402. * uniform type.
  5403. *
  5404. * @param {string} uniformType - The type to set.
  5405. */
  5406. setNodeType( uniformType ) {
  5407. const node = uniform( null, uniformType ).getSelf();
  5408. if ( this.group !== null ) {
  5409. node.setGroup( this.group );
  5410. }
  5411. this.node = node;
  5412. }
  5413. /**
  5414. * This method is overwritten since the node type is inferred from
  5415. * the type of the reference node.
  5416. *
  5417. * @param {NodeBuilder} builder - The current node builder.
  5418. * @return {string} The node type.
  5419. */
  5420. getNodeType( builder ) {
  5421. if ( this.node === null ) {
  5422. this.updateReference( builder );
  5423. this.updateValue();
  5424. }
  5425. return this.node.getNodeType( builder );
  5426. }
  5427. /**
  5428. * Returns the property value from the given referred object.
  5429. *
  5430. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5431. * @return {any} The value.
  5432. */
  5433. getValueFromReference( object = this.reference ) {
  5434. const { properties } = this;
  5435. let value = object[ properties[ 0 ] ];
  5436. for ( let i = 1; i < properties.length; i ++ ) {
  5437. value = value[ properties[ i ] ];
  5438. }
  5439. return value;
  5440. }
  5441. /**
  5442. * Allows to update the reference based on the given state. The state is only
  5443. * evaluated {@link ReferenceBaseNode#object} is not set.
  5444. *
  5445. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5446. * @return {Object} The updated reference.
  5447. */
  5448. updateReference( state ) {
  5449. this.reference = this.object !== null ? this.object : state.object;
  5450. return this.reference;
  5451. }
  5452. /**
  5453. * The output of the reference node is the internal uniform node.
  5454. *
  5455. * @return {UniformNode} The output node.
  5456. */
  5457. setup() {
  5458. this.updateValue();
  5459. return this.node;
  5460. }
  5461. /**
  5462. * Overwritten to to update the internal uniform value.
  5463. *
  5464. * @param {NodeFrame} frame - A reference to the current node frame.
  5465. */
  5466. update( /*frame*/ ) {
  5467. this.updateValue();
  5468. }
  5469. /**
  5470. * Retrieves the value from the referred object property and uses it
  5471. * to updated the internal uniform.
  5472. */
  5473. updateValue() {
  5474. if ( this.node === null ) this.setNodeType( this.uniformType );
  5475. const value = this.getValueFromReference();
  5476. if ( Array.isArray( value ) ) {
  5477. this.node.array = value;
  5478. } else {
  5479. this.node.value = value;
  5480. }
  5481. }
  5482. }
  5483. /**
  5484. * TSL function for creating a reference base node.
  5485. *
  5486. * @tsl
  5487. * @function
  5488. * @param {string} name - The name of the property the node refers to.
  5489. * @param {string} type - The uniform type that should be used to represent the property value.
  5490. * @param {Object} object - The object the property belongs to.
  5491. * @returns {ReferenceBaseNode}
  5492. */
  5493. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5494. /**
  5495. * This node is a special type of reference node which is intended
  5496. * for linking renderer properties with node values.
  5497. * ```js
  5498. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5499. * ```
  5500. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5501. * automatically be updated.
  5502. *
  5503. * @augments ReferenceBaseNode
  5504. */
  5505. class RendererReferenceNode extends ReferenceBaseNode {
  5506. static get type() {
  5507. return 'RendererReferenceNode';
  5508. }
  5509. /**
  5510. * Constructs a new renderer reference node.
  5511. *
  5512. * @param {string} property - The name of the property the node refers to.
  5513. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5514. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5515. * the node refers to the renderer of the current state.
  5516. */
  5517. constructor( property, inputType, renderer = null ) {
  5518. super( property, inputType, renderer );
  5519. /**
  5520. * The renderer the property belongs to. When no renderer is set,
  5521. * the node refers to the renderer of the current state.
  5522. *
  5523. * @type {?Renderer}
  5524. * @default null
  5525. */
  5526. this.renderer = renderer;
  5527. this.setGroup( renderGroup );
  5528. }
  5529. /**
  5530. * Updates the reference based on the given state. The state is only evaluated
  5531. * {@link RendererReferenceNode#renderer} is not set.
  5532. *
  5533. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5534. * @return {Object} The updated reference.
  5535. */
  5536. updateReference( state ) {
  5537. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5538. return this.reference;
  5539. }
  5540. }
  5541. /**
  5542. * TSL function for creating a renderer reference node.
  5543. *
  5544. * @tsl
  5545. * @function
  5546. * @param {string} name - The name of the property the node refers to.
  5547. * @param {string} type - The uniform type that should be used to represent the property value.
  5548. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5549. * the node refers to the renderer of the current state.
  5550. * @returns {RendererReferenceNode}
  5551. */
  5552. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5553. /**
  5554. * This node represents a tone mapping operation.
  5555. *
  5556. * @augments TempNode
  5557. */
  5558. class ToneMappingNode extends TempNode {
  5559. static get type() {
  5560. return 'ToneMappingNode';
  5561. }
  5562. /**
  5563. * Constructs a new tone mapping node.
  5564. *
  5565. * @param {number} toneMapping - The tone mapping type.
  5566. * @param {Node} exposureNode - The tone mapping exposure.
  5567. * @param {Node} [colorNode=null] - The color node to process.
  5568. */
  5569. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5570. super( 'vec3' );
  5571. /**
  5572. * The tone mapping type.
  5573. *
  5574. * @type {number}
  5575. */
  5576. this.toneMapping = toneMapping;
  5577. /**
  5578. * The tone mapping exposure.
  5579. *
  5580. * @type {Node}
  5581. * @default null
  5582. */
  5583. this.exposureNode = exposureNode;
  5584. /**
  5585. * Represents the color to process.
  5586. *
  5587. * @type {?Node}
  5588. * @default null
  5589. */
  5590. this.colorNode = colorNode;
  5591. }
  5592. /**
  5593. * Overwrites the default `customCacheKey()` implementation by including the tone
  5594. * mapping type into the cache key.
  5595. *
  5596. * @return {number} The hash.
  5597. */
  5598. customCacheKey() {
  5599. return hash$1( this.toneMapping );
  5600. }
  5601. setup( builder ) {
  5602. const colorNode = this.colorNode || builder.context.color;
  5603. const toneMapping = this.toneMapping;
  5604. if ( toneMapping === NoToneMapping ) return colorNode;
  5605. let outputNode = null;
  5606. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5607. if ( toneMappingFn !== null ) {
  5608. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5609. } else {
  5610. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5611. outputNode = colorNode;
  5612. }
  5613. return outputNode;
  5614. }
  5615. }
  5616. /**
  5617. * TSL function for creating a tone mapping node.
  5618. *
  5619. * @tsl
  5620. * @function
  5621. * @param {number} mapping - The tone mapping type.
  5622. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5623. * @param {Node<vec3> | Color} color - The color node to process.
  5624. * @returns {ToneMappingNode<vec3>}
  5625. */
  5626. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5627. /**
  5628. * TSL object that represents the global tone mapping exposure of the renderer.
  5629. *
  5630. * @tsl
  5631. * @type {RendererReferenceNode<vec3>}
  5632. */
  5633. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5634. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5635. /**
  5636. * In earlier `three.js` versions it was only possible to define attribute data
  5637. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5638. * on the node level.
  5639. * ```js
  5640. * const geometry = new THREE.PlaneGeometry();
  5641. * const positionAttribute = geometry.getAttribute( 'position' );
  5642. *
  5643. * const colors = [];
  5644. * for ( let i = 0; i < position.count; i ++ ) {
  5645. * colors.push( 1, 0, 0 );
  5646. * }
  5647. *
  5648. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5649. * ```
  5650. * This new approach is especially interesting when geometry data are generated via
  5651. * compute shaders. The below line converts a storage buffer into an attribute node.
  5652. * ```js
  5653. * material.positionNode = positionBuffer.toAttribute();
  5654. * ```
  5655. * @augments InputNode
  5656. */
  5657. class BufferAttributeNode extends InputNode {
  5658. static get type() {
  5659. return 'BufferAttributeNode';
  5660. }
  5661. /**
  5662. * Constructs a new buffer attribute node.
  5663. *
  5664. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5665. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5666. * @param {number} [bufferStride=0] - The buffer stride.
  5667. * @param {number} [bufferOffset=0] - The buffer offset.
  5668. */
  5669. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5670. super( value, bufferType );
  5671. /**
  5672. * This flag can be used for type testing.
  5673. *
  5674. * @type {boolean}
  5675. * @readonly
  5676. * @default true
  5677. */
  5678. this.isBufferNode = true;
  5679. /**
  5680. * The buffer type (e.g. `'vec3'`).
  5681. *
  5682. * @type {?string}
  5683. * @default null
  5684. */
  5685. this.bufferType = bufferType;
  5686. /**
  5687. * The buffer stride.
  5688. *
  5689. * @type {number}
  5690. * @default 0
  5691. */
  5692. this.bufferStride = bufferStride;
  5693. /**
  5694. * The buffer offset.
  5695. *
  5696. * @type {number}
  5697. * @default 0
  5698. */
  5699. this.bufferOffset = bufferOffset;
  5700. /**
  5701. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5702. * if you are planning to update the attribute data per frame.
  5703. *
  5704. * @type {number}
  5705. * @default StaticDrawUsage
  5706. */
  5707. this.usage = StaticDrawUsage;
  5708. /**
  5709. * Whether the attribute is instanced or not.
  5710. *
  5711. * @type {boolean}
  5712. * @default false
  5713. */
  5714. this.instanced = false;
  5715. /**
  5716. * A reference to the buffer attribute.
  5717. *
  5718. * @type {?BufferAttribute}
  5719. * @default null
  5720. */
  5721. this.attribute = null;
  5722. /**
  5723. * `BufferAttributeNode` sets this property to `true` by default.
  5724. *
  5725. * @type {boolean}
  5726. * @default true
  5727. */
  5728. this.global = true;
  5729. if ( value && value.isBufferAttribute === true ) {
  5730. this.attribute = value;
  5731. this.usage = value.usage;
  5732. this.instanced = value.isInstancedBufferAttribute;
  5733. }
  5734. }
  5735. /**
  5736. * This method is overwritten since the attribute data might be shared
  5737. * and thus the hash should be shared as well.
  5738. *
  5739. * @param {NodeBuilder} builder - The current node builder.
  5740. * @return {string} The hash.
  5741. */
  5742. getHash( builder ) {
  5743. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5744. let bufferData = builder.globalCache.getData( this.value );
  5745. if ( bufferData === undefined ) {
  5746. bufferData = {
  5747. node: this
  5748. };
  5749. builder.globalCache.setData( this.value, bufferData );
  5750. }
  5751. return bufferData.node.uuid;
  5752. }
  5753. return this.uuid;
  5754. }
  5755. /**
  5756. * This method is overwritten since the node type is inferred from
  5757. * the buffer attribute.
  5758. *
  5759. * @param {NodeBuilder} builder - The current node builder.
  5760. * @return {string} The node type.
  5761. */
  5762. getNodeType( builder ) {
  5763. if ( this.bufferType === null ) {
  5764. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5765. }
  5766. return this.bufferType;
  5767. }
  5768. /**
  5769. * Depending on which value was passed to the node, `setup()` behaves
  5770. * differently. If no instance of `BufferAttribute` was passed, the method
  5771. * creates an internal attribute and configures it respectively.
  5772. *
  5773. * @param {NodeBuilder} builder - The current node builder.
  5774. */
  5775. setup( builder ) {
  5776. if ( this.attribute !== null ) return;
  5777. const type = this.getNodeType( builder );
  5778. const array = this.value;
  5779. const itemSize = builder.getTypeLength( type );
  5780. const stride = this.bufferStride || itemSize;
  5781. const offset = this.bufferOffset;
  5782. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5783. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5784. buffer.setUsage( this.usage );
  5785. this.attribute = bufferAttribute;
  5786. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5787. }
  5788. /**
  5789. * Generates the code snippet of the buffer attribute node.
  5790. *
  5791. * @param {NodeBuilder} builder - The current node builder.
  5792. * @return {string} The generated code snippet.
  5793. */
  5794. generate( builder ) {
  5795. const nodeType = this.getNodeType( builder );
  5796. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5797. const propertyName = builder.getPropertyName( nodeAttribute );
  5798. let output = null;
  5799. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5800. this.name = propertyName;
  5801. output = propertyName;
  5802. } else {
  5803. const nodeVarying = varying( this );
  5804. output = nodeVarying.build( builder, nodeType );
  5805. }
  5806. return output;
  5807. }
  5808. /**
  5809. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5810. *
  5811. * @param {NodeBuilder} builder - The current node builder.
  5812. * @return {string} The input type.
  5813. */
  5814. getInputType( /*builder*/ ) {
  5815. return 'bufferAttribute';
  5816. }
  5817. /**
  5818. * Sets the `usage` property to the given value.
  5819. *
  5820. * @param {number} value - The usage to set.
  5821. * @return {BufferAttributeNode} A reference to this node.
  5822. */
  5823. setUsage( value ) {
  5824. this.usage = value;
  5825. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5826. this.attribute.usage = value;
  5827. }
  5828. return this;
  5829. }
  5830. /**
  5831. * Sets the `instanced` property to the given value.
  5832. *
  5833. * @param {boolean} value - The value to set.
  5834. * @return {BufferAttributeNode} A reference to this node.
  5835. */
  5836. setInstanced( value ) {
  5837. this.instanced = value;
  5838. return this;
  5839. }
  5840. }
  5841. /**
  5842. * TSL function for creating a buffer attribute node.
  5843. *
  5844. * @tsl
  5845. * @function
  5846. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5847. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5848. * @param {number} [stride=0] - The buffer stride.
  5849. * @param {number} [offset=0] - The buffer offset.
  5850. * @returns {BufferAttributeNode}
  5851. */
  5852. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5853. /**
  5854. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5855. * Use this function if attribute data are updated per frame.
  5856. *
  5857. * @tsl
  5858. * @function
  5859. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5860. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5861. * @param {number} [stride=0] - The buffer stride.
  5862. * @param {number} [offset=0] - The buffer offset.
  5863. * @returns {BufferAttributeNode}
  5864. */
  5865. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5866. /**
  5867. * TSL function for creating a buffer attribute node but with enabled instancing
  5868. *
  5869. * @tsl
  5870. * @function
  5871. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5872. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5873. * @param {number} [stride=0] - The buffer stride.
  5874. * @param {number} [offset=0] - The buffer offset.
  5875. * @returns {BufferAttributeNode}
  5876. */
  5877. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5878. /**
  5879. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5880. *
  5881. * @tsl
  5882. * @function
  5883. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5884. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5885. * @param {number} [stride=0] - The buffer stride.
  5886. * @param {number} [offset=0] - The buffer offset.
  5887. * @returns {BufferAttributeNode}
  5888. */
  5889. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5890. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5891. /**
  5892. * TODO
  5893. *
  5894. * @augments Node
  5895. */
  5896. class ComputeNode extends Node {
  5897. static get type() {
  5898. return 'ComputeNode';
  5899. }
  5900. /**
  5901. * Constructs a new compute node.
  5902. *
  5903. * @param {Node} computeNode - TODO
  5904. * @param {number} count - TODO.
  5905. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  5906. */
  5907. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5908. super( 'void' );
  5909. /**
  5910. * This flag can be used for type testing.
  5911. *
  5912. * @type {boolean}
  5913. * @readonly
  5914. * @default true
  5915. */
  5916. this.isComputeNode = true;
  5917. /**
  5918. * TODO
  5919. *
  5920. * @type {Node}
  5921. */
  5922. this.computeNode = computeNode;
  5923. /**
  5924. * TODO
  5925. *
  5926. * @type {number}
  5927. */
  5928. this.count = count;
  5929. /**
  5930. * TODO
  5931. *
  5932. * @type {Array<number>}
  5933. * @default [64]
  5934. */
  5935. this.workgroupSize = workgroupSize;
  5936. /**
  5937. * TODO
  5938. *
  5939. * @type {number}
  5940. */
  5941. this.dispatchCount = 0;
  5942. /**
  5943. * TODO
  5944. *
  5945. * @type {number}
  5946. */
  5947. this.version = 1;
  5948. /**
  5949. * The name or label of the uniform.
  5950. *
  5951. * @type {string}
  5952. * @default ''
  5953. */
  5954. this.name = '';
  5955. /**
  5956. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5957. * is executed once per object by default.
  5958. *
  5959. * @type {string}
  5960. * @default 'object'
  5961. */
  5962. this.updateBeforeType = NodeUpdateType.OBJECT;
  5963. /**
  5964. * TODO
  5965. *
  5966. * @type {?Function}
  5967. */
  5968. this.onInitFunction = null;
  5969. this.updateDispatchCount();
  5970. }
  5971. /**
  5972. * Executes the `dispose` event for this node.
  5973. */
  5974. dispose() {
  5975. this.dispatchEvent( { type: 'dispose' } );
  5976. }
  5977. /**
  5978. * Sets the {@link ComputeNode#name} property.
  5979. *
  5980. * @param {string} name - The name of the uniform.
  5981. * @return {ComputeNode} A reference to this node.
  5982. */
  5983. label( name ) {
  5984. this.name = name;
  5985. return this;
  5986. }
  5987. /**
  5988. * TODO
  5989. */
  5990. updateDispatchCount() {
  5991. const { count, workgroupSize } = this;
  5992. let size = workgroupSize[ 0 ];
  5993. for ( let i = 1; i < workgroupSize.length; i ++ )
  5994. size *= workgroupSize[ i ];
  5995. this.dispatchCount = Math.ceil( count / size );
  5996. }
  5997. /**
  5998. * TODO
  5999. *
  6000. * @param {Function} callback - TODO.
  6001. * @return {ComputeNode} A reference to this node.
  6002. */
  6003. onInit( callback ) {
  6004. this.onInitFunction = callback;
  6005. return this;
  6006. }
  6007. /**
  6008. * The method execute the compute for this node.
  6009. *
  6010. * @param {NodeFrame} frame - A reference to the current node frame.
  6011. */
  6012. updateBefore( { renderer } ) {
  6013. renderer.compute( this );
  6014. }
  6015. generate( builder ) {
  6016. const { shaderStage } = builder;
  6017. if ( shaderStage === 'compute' ) {
  6018. const snippet = this.computeNode.build( builder, 'void' );
  6019. if ( snippet !== '' ) {
  6020. builder.addLineFlowCode( snippet, this );
  6021. }
  6022. }
  6023. }
  6024. }
  6025. /**
  6026. * TSL function for creating a compute node.
  6027. *
  6028. * @tsl
  6029. * @function
  6030. * @param {Node} node - TODO
  6031. * @param {number} count - TODO.
  6032. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6033. * @returns {AtomicFunctionNode}
  6034. */
  6035. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6036. addMethodChaining( 'compute', compute );
  6037. /**
  6038. * This node can be used as a cache management component for another node.
  6039. * Caching is in general used by default in {@link NodeBuilder} but this node
  6040. * allows the usage of a shared parent cache during the build process.
  6041. *
  6042. * @augments Node
  6043. */
  6044. class CacheNode extends Node {
  6045. static get type() {
  6046. return 'CacheNode';
  6047. }
  6048. /**
  6049. * Constructs a new cache node.
  6050. *
  6051. * @param {Node} node - The node that should be cached.
  6052. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6053. */
  6054. constructor( node, parent = true ) {
  6055. super();
  6056. /**
  6057. * The node that should be cached.
  6058. *
  6059. * @type {Node}
  6060. */
  6061. this.node = node;
  6062. /**
  6063. * Whether this node refers to a shared parent cache or not.
  6064. *
  6065. * @type {boolean}
  6066. * @default true
  6067. */
  6068. this.parent = parent;
  6069. /**
  6070. * This flag can be used for type testing.
  6071. *
  6072. * @type {boolean}
  6073. * @readonly
  6074. * @default true
  6075. */
  6076. this.isCacheNode = true;
  6077. }
  6078. getNodeType( builder ) {
  6079. const previousCache = builder.getCache();
  6080. const cache = builder.getCacheFromNode( this, this.parent );
  6081. builder.setCache( cache );
  6082. const nodeType = this.node.getNodeType( builder );
  6083. builder.setCache( previousCache );
  6084. return nodeType;
  6085. }
  6086. build( builder, ...params ) {
  6087. const previousCache = builder.getCache();
  6088. const cache = builder.getCacheFromNode( this, this.parent );
  6089. builder.setCache( cache );
  6090. const data = this.node.build( builder, ...params );
  6091. builder.setCache( previousCache );
  6092. return data;
  6093. }
  6094. }
  6095. /**
  6096. * TSL function for creating a cache node.
  6097. *
  6098. * @tsl
  6099. * @function
  6100. * @param {Node} node - The node that should be cached.
  6101. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6102. * @returns {CacheNode}
  6103. */
  6104. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6105. addMethodChaining( 'cache', cache );
  6106. /**
  6107. * The class generates the code of a given node but returns another node in the output.
  6108. * This can be used to call a method or node that does not return a value, i.e.
  6109. * type `void` on an input where returning a value is required. Example:
  6110. *
  6111. * ```js
  6112. * material.colorNode = myColor.bypass( runVoidFn() )
  6113. *```
  6114. *
  6115. * @augments Node
  6116. */
  6117. class BypassNode extends Node {
  6118. static get type() {
  6119. return 'BypassNode';
  6120. }
  6121. /**
  6122. * Constructs a new bypass node.
  6123. *
  6124. * @param {Node} outputNode - The output node.
  6125. * @param {Node} callNode - The call node.
  6126. */
  6127. constructor( outputNode, callNode ) {
  6128. super();
  6129. /**
  6130. * This flag can be used for type testing.
  6131. *
  6132. * @type {boolean}
  6133. * @readonly
  6134. * @default true
  6135. */
  6136. this.isBypassNode = true;
  6137. /**
  6138. * The output node.
  6139. *
  6140. * @type {Node}
  6141. */
  6142. this.outputNode = outputNode;
  6143. /**
  6144. * The call node.
  6145. *
  6146. * @type {Node}
  6147. */
  6148. this.callNode = callNode;
  6149. }
  6150. getNodeType( builder ) {
  6151. return this.outputNode.getNodeType( builder );
  6152. }
  6153. generate( builder ) {
  6154. const snippet = this.callNode.build( builder, 'void' );
  6155. if ( snippet !== '' ) {
  6156. builder.addLineFlowCode( snippet, this );
  6157. }
  6158. return this.outputNode.build( builder );
  6159. }
  6160. }
  6161. /**
  6162. * TSL function for creating a bypass node.
  6163. *
  6164. * @tsl
  6165. * @function
  6166. * @param {Node} outputNode - The output node.
  6167. * @param {Node} callNode - The call node.
  6168. * @returns {BypassNode}
  6169. */
  6170. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  6171. addMethodChaining( 'bypass', bypass );
  6172. /**
  6173. * This node allows to remap a node value from one range into another. E.g a value of
  6174. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6175. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6176. *
  6177. * @augments Node
  6178. */
  6179. class RemapNode extends Node {
  6180. static get type() {
  6181. return 'RemapNode';
  6182. }
  6183. /**
  6184. * Constructs a new remap node.
  6185. *
  6186. * @param {Node} node - The node that should be remapped.
  6187. * @param {Node} inLowNode - The source or current lower bound of the range.
  6188. * @param {Node} inHighNode - The source or current upper bound of the range.
  6189. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6190. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6191. */
  6192. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6193. super();
  6194. /**
  6195. * The node that should be remapped.
  6196. *
  6197. * @type {Node}
  6198. */
  6199. this.node = node;
  6200. /**
  6201. * The source or current lower bound of the range.
  6202. *
  6203. * @type {Node}
  6204. */
  6205. this.inLowNode = inLowNode;
  6206. /**
  6207. * The source or current upper bound of the range.
  6208. *
  6209. * @type {Node}
  6210. */
  6211. this.inHighNode = inHighNode;
  6212. /**
  6213. * The target lower bound of the range.
  6214. *
  6215. * @type {Node}
  6216. * @default float(0)
  6217. */
  6218. this.outLowNode = outLowNode;
  6219. /**
  6220. * The target upper bound of the range.
  6221. *
  6222. * @type {Node}
  6223. * @default float(1)
  6224. */
  6225. this.outHighNode = outHighNode;
  6226. /**
  6227. * Whether the node value should be clamped before
  6228. * remapping it to the target range.
  6229. *
  6230. * @type {boolean}
  6231. * @default true
  6232. */
  6233. this.doClamp = true;
  6234. }
  6235. setup() {
  6236. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6237. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6238. if ( doClamp === true ) t = t.clamp();
  6239. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6240. }
  6241. }
  6242. /**
  6243. * TSL function for creating a remap node.
  6244. *
  6245. * @tsl
  6246. * @function
  6247. * @param {Node} node - The node that should be remapped.
  6248. * @param {Node} inLowNode - The source or current lower bound of the range.
  6249. * @param {Node} inHighNode - The source or current upper bound of the range.
  6250. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6251. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6252. * @returns {RemapNode}
  6253. */
  6254. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  6255. /**
  6256. * TSL function for creating a remap node, but with enabled clamping.
  6257. *
  6258. * @tsl
  6259. * @function
  6260. * @param {Node} node - The node that should be remapped.
  6261. * @param {Node} inLowNode - The source or current lower bound of the range.
  6262. * @param {Node} inHighNode - The source or current upper bound of the range.
  6263. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6264. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6265. * @returns {RemapNode}
  6266. */
  6267. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  6268. addMethodChaining( 'remap', remap );
  6269. addMethodChaining( 'remapClamp', remapClamp );
  6270. /**
  6271. * This class can be used to implement basic expressions in shader code.
  6272. * Basic examples for that are `return`, `continue` or `discard` statements.
  6273. *
  6274. * @augments Node
  6275. */
  6276. class ExpressionNode extends Node {
  6277. static get type() {
  6278. return 'ExpressionNode';
  6279. }
  6280. /**
  6281. * Constructs a new expression node.
  6282. *
  6283. * @param {string} [snippet=''] - The native code snippet.
  6284. * @param {string} [nodeType='void'] - The node type.
  6285. */
  6286. constructor( snippet = '', nodeType = 'void' ) {
  6287. super( nodeType );
  6288. /**
  6289. * The native code snippet.
  6290. *
  6291. * @type {string}
  6292. * @default ''
  6293. */
  6294. this.snippet = snippet;
  6295. }
  6296. generate( builder, output ) {
  6297. const type = this.getNodeType( builder );
  6298. const snippet = this.snippet;
  6299. if ( type === 'void' ) {
  6300. builder.addLineFlowCode( snippet, this );
  6301. } else {
  6302. return builder.format( snippet, type, output );
  6303. }
  6304. }
  6305. }
  6306. /**
  6307. * TSL function for creating an expression node.
  6308. *
  6309. * @tsl
  6310. * @function
  6311. * @param {string} [snippet=''] - The native code snippet.
  6312. * @param {string} [nodeType='void'] - The node type.
  6313. * @returns {ExpressionNode}
  6314. */
  6315. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  6316. /**
  6317. * Represents a `discard` shader operation in TSL.
  6318. *
  6319. * @tsl
  6320. * @function
  6321. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6322. * @return {Node} The `discard` expression.
  6323. */
  6324. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  6325. /**
  6326. * Represents a `return` shader operation in TSL.
  6327. *
  6328. * @tsl
  6329. * @function
  6330. * @return {ExpressionNode} The `return` expression.
  6331. */
  6332. const Return = () => expression( 'return' ).append();
  6333. addMethodChaining( 'discard', Discard );
  6334. /**
  6335. * Normally, tone mapping and color conversion happens automatically
  6336. * before outputting pixel too the default (screen) framebuffer. In certain
  6337. * post processing setups this happens to late because certain effects
  6338. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6339. * to apply tone mapping and color space conversion at an arbitrary point
  6340. * in the effect chain.
  6341. *
  6342. * When applying tone mapping and color space conversion manually with this node,
  6343. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6344. *
  6345. * ```js
  6346. * const postProcessing = new PostProcessing( renderer );
  6347. * postProcessing.outputColorTransform = false;
  6348. *
  6349. * const scenePass = pass( scene, camera );
  6350. * const outputPass = renderOutput( scenePass );
  6351. *
  6352. * postProcessing.outputNode = outputPass;
  6353. * ```
  6354. *
  6355. * @augments TempNode
  6356. */
  6357. class RenderOutputNode extends TempNode {
  6358. static get type() {
  6359. return 'RenderOutputNode';
  6360. }
  6361. /**
  6362. * Constructs a new render output node.
  6363. *
  6364. * @param {Node} colorNode - The color node to process.
  6365. * @param {?number} toneMapping - The tone mapping type.
  6366. * @param {?string} outputColorSpace - The output color space.
  6367. */
  6368. constructor( colorNode, toneMapping, outputColorSpace ) {
  6369. super( 'vec4' );
  6370. /**
  6371. * The color node to process.
  6372. *
  6373. * @type {Node}
  6374. */
  6375. this.colorNode = colorNode;
  6376. /**
  6377. * The tone mapping type.
  6378. *
  6379. * @type {?number}
  6380. */
  6381. this.toneMapping = toneMapping;
  6382. /**
  6383. * The output color space.
  6384. *
  6385. * @type {?string}
  6386. */
  6387. this.outputColorSpace = outputColorSpace;
  6388. /**
  6389. * This flag can be used for type testing.
  6390. *
  6391. * @type {boolean}
  6392. * @readonly
  6393. * @default true
  6394. */
  6395. this.isRenderOutputNode = true;
  6396. }
  6397. setup( { context } ) {
  6398. let outputNode = this.colorNode || context.color;
  6399. // tone mapping
  6400. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6401. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6402. if ( toneMapping !== NoToneMapping ) {
  6403. outputNode = outputNode.toneMapping( toneMapping );
  6404. }
  6405. // working to output color space
  6406. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6407. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6408. }
  6409. return outputNode;
  6410. }
  6411. }
  6412. /**
  6413. * TSL function for creating a posterize node.
  6414. *
  6415. * @tsl
  6416. * @function
  6417. * @param {Node} color - The color node to process.
  6418. * @param {?number} [toneMapping=null] - The tone mapping type.
  6419. * @param {?string} [outputColorSpace=null] - The output color space.
  6420. * @returns {RenderOutputNode}
  6421. */
  6422. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6423. addMethodChaining( 'renderOutput', renderOutput );
  6424. // Non-PURE exports list, side-effects are required here.
  6425. // TSL Base Syntax
  6426. function addNodeElement( name/*, nodeElement*/ ) {
  6427. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6428. }
  6429. /**
  6430. * Base class for representing shader attributes as nodes.
  6431. *
  6432. * @augments Node
  6433. */
  6434. class AttributeNode extends Node {
  6435. static get type() {
  6436. return 'AttributeNode';
  6437. }
  6438. /**
  6439. * Constructs a new attribute node.
  6440. *
  6441. * @param {string} attributeName - The name of the attribute.
  6442. * @param {?string} nodeType - The node type.
  6443. */
  6444. constructor( attributeName, nodeType = null ) {
  6445. super( nodeType );
  6446. /**
  6447. * `AttributeNode` sets this property to `true` by default.
  6448. *
  6449. * @type {boolean}
  6450. * @default true
  6451. */
  6452. this.global = true;
  6453. this._attributeName = attributeName;
  6454. }
  6455. getHash( builder ) {
  6456. return this.getAttributeName( builder );
  6457. }
  6458. getNodeType( builder ) {
  6459. let nodeType = this.nodeType;
  6460. if ( nodeType === null ) {
  6461. const attributeName = this.getAttributeName( builder );
  6462. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6463. const attribute = builder.geometry.getAttribute( attributeName );
  6464. nodeType = builder.getTypeFromAttribute( attribute );
  6465. } else {
  6466. nodeType = 'float';
  6467. }
  6468. }
  6469. return nodeType;
  6470. }
  6471. /**
  6472. * Sets the attribute name to the given value. The method can be
  6473. * overwritten in derived classes if the final name must be computed
  6474. * analytically.
  6475. *
  6476. * @param {string} attributeName - The name of the attribute.
  6477. * @return {AttributeNode} A reference to this node.
  6478. */
  6479. setAttributeName( attributeName ) {
  6480. this._attributeName = attributeName;
  6481. return this;
  6482. }
  6483. /**
  6484. * Returns the attribute name of this node. The method can be
  6485. * overwritten in derived classes if the final name must be computed
  6486. * analytically.
  6487. *
  6488. * @param {NodeBuilder} builder - The current node builder.
  6489. * @return {string} The attribute name.
  6490. */
  6491. getAttributeName( /*builder*/ ) {
  6492. return this._attributeName;
  6493. }
  6494. generate( builder ) {
  6495. const attributeName = this.getAttributeName( builder );
  6496. const nodeType = this.getNodeType( builder );
  6497. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6498. if ( geometryAttribute === true ) {
  6499. const attribute = builder.geometry.getAttribute( attributeName );
  6500. const attributeType = builder.getTypeFromAttribute( attribute );
  6501. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6502. if ( builder.shaderStage === 'vertex' ) {
  6503. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6504. } else {
  6505. const nodeVarying = varying( this );
  6506. return nodeVarying.build( builder, nodeType );
  6507. }
  6508. } else {
  6509. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6510. return builder.generateConst( nodeType );
  6511. }
  6512. }
  6513. serialize( data ) {
  6514. super.serialize( data );
  6515. data.global = this.global;
  6516. data._attributeName = this._attributeName;
  6517. }
  6518. deserialize( data ) {
  6519. super.deserialize( data );
  6520. this.global = data.global;
  6521. this._attributeName = data._attributeName;
  6522. }
  6523. }
  6524. /**
  6525. * TSL function for creating an attribute node.
  6526. *
  6527. * @tsl
  6528. * @function
  6529. * @param {string} name - The name of the attribute.
  6530. * @param {string} [nodeType] - The node type.
  6531. * @returns {AttributeNode}
  6532. */
  6533. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6534. /**
  6535. * TSL function for creating an uv attribute node with the given index.
  6536. *
  6537. * @tsl
  6538. * @function
  6539. * @param {number} [index=0] - The uv index.
  6540. * @return {AttributeNode<vec2>} The uv attribute node.
  6541. */
  6542. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6543. /**
  6544. * A node that represents the dimensions of a texture. The texture size is
  6545. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6546. * or `textureSize()`.
  6547. *
  6548. * @augments Node
  6549. */
  6550. class TextureSizeNode extends Node {
  6551. static get type() {
  6552. return 'TextureSizeNode';
  6553. }
  6554. /**
  6555. * Constructs a new texture size node.
  6556. *
  6557. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6558. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6559. */
  6560. constructor( textureNode, levelNode = null ) {
  6561. super( 'uvec2' );
  6562. /**
  6563. * This flag can be used for type testing.
  6564. *
  6565. * @type {boolean}
  6566. * @readonly
  6567. * @default true
  6568. */
  6569. this.isTextureSizeNode = true;
  6570. /**
  6571. * A texture node which size should be retrieved.
  6572. *
  6573. * @type {TextureNode}
  6574. */
  6575. this.textureNode = textureNode;
  6576. /**
  6577. * A level node which defines the requested mip.
  6578. *
  6579. * @type {Node<int>}
  6580. * @default null
  6581. */
  6582. this.levelNode = levelNode;
  6583. }
  6584. generate( builder, output ) {
  6585. const textureProperty = this.textureNode.build( builder, 'property' );
  6586. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6587. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6588. }
  6589. }
  6590. /**
  6591. * TSL function for creating a texture size node.
  6592. *
  6593. * @tsl
  6594. * @function
  6595. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6596. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6597. * @returns {TextureSizeNode}
  6598. */
  6599. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6600. /**
  6601. * A special type of uniform node that computes the
  6602. * maximum mipmap level for a given texture node.
  6603. *
  6604. * ```js
  6605. * const level = maxMipLevel( textureNode );
  6606. * ```
  6607. *
  6608. * @augments UniformNode
  6609. */
  6610. class MaxMipLevelNode extends UniformNode {
  6611. static get type() {
  6612. return 'MaxMipLevelNode';
  6613. }
  6614. /**
  6615. * Constructs a new max mip level node.
  6616. *
  6617. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6618. */
  6619. constructor( textureNode ) {
  6620. super( 0 );
  6621. /**
  6622. * The texture node to compute the max mip level for.
  6623. *
  6624. * @private
  6625. * @type {TextureNode}
  6626. */
  6627. this._textureNode = textureNode;
  6628. /**
  6629. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6630. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6631. *
  6632. * @type {string}
  6633. * @default 'frame'
  6634. */
  6635. this.updateType = NodeUpdateType.FRAME;
  6636. }
  6637. /**
  6638. * The texture node to compute the max mip level for.
  6639. *
  6640. * @readonly
  6641. * @type {TextureNode}
  6642. */
  6643. get textureNode() {
  6644. return this._textureNode;
  6645. }
  6646. /**
  6647. * The texture.
  6648. *
  6649. * @readonly
  6650. * @type {Texture}
  6651. */
  6652. get texture() {
  6653. return this._textureNode.value;
  6654. }
  6655. update() {
  6656. const texture = this.texture;
  6657. const images = texture.images;
  6658. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6659. if ( image && image.width !== undefined ) {
  6660. const { width, height } = image;
  6661. this.value = Math.log2( Math.max( width, height ) );
  6662. }
  6663. }
  6664. }
  6665. /**
  6666. * TSL function for creating a max mip level node.
  6667. *
  6668. * @tsl
  6669. * @function
  6670. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6671. * @returns {MaxMipLevelNode}
  6672. */
  6673. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6674. /**
  6675. * This type of uniform node represents a 2D texture.
  6676. *
  6677. * @augments UniformNode
  6678. */
  6679. class TextureNode extends UniformNode {
  6680. static get type() {
  6681. return 'TextureNode';
  6682. }
  6683. /**
  6684. * Constructs a new texture node.
  6685. *
  6686. * @param {Texture} value - The texture.
  6687. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  6688. * @param {?Node<int>} [levelNode=null] - The level node.
  6689. * @param {?Node<float>} [biasNode=null] - The bias node.
  6690. */
  6691. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6692. super( value );
  6693. /**
  6694. * This flag can be used for type testing.
  6695. *
  6696. * @type {boolean}
  6697. * @readonly
  6698. * @default true
  6699. */
  6700. this.isTextureNode = true;
  6701. /**
  6702. * Represents the texture coordinates.
  6703. *
  6704. * @type {?Node<vec2|vec3>}
  6705. * @default null
  6706. */
  6707. this.uvNode = uvNode;
  6708. /**
  6709. * Represents the mip level that should be selected.
  6710. *
  6711. * @type {?Node<int>}
  6712. * @default null
  6713. */
  6714. this.levelNode = levelNode;
  6715. /**
  6716. * Represents the bias to be applied during level-of-detail computation.
  6717. *
  6718. * @type {?Node<float>}
  6719. * @default null
  6720. */
  6721. this.biasNode = biasNode;
  6722. /**
  6723. * Represents a reference value a texture sample is compared to.
  6724. *
  6725. * @type {?Node<float>}
  6726. * @default null
  6727. */
  6728. this.compareNode = null;
  6729. /**
  6730. * When using texture arrays, the depth node defines the layer to select.
  6731. *
  6732. * @type {?Node<int>}
  6733. * @default null
  6734. */
  6735. this.depthNode = null;
  6736. /**
  6737. * When defined, a texture is sampled using explicit gradients.
  6738. *
  6739. * @type {?Array<Node<vec2>>}
  6740. * @default null
  6741. */
  6742. this.gradNode = null;
  6743. /**
  6744. * Whether texture values should be sampled or fetched.
  6745. *
  6746. * @type {boolean}
  6747. * @default true
  6748. */
  6749. this.sampler = true;
  6750. /**
  6751. * Whether the uv transformation matrix should be
  6752. * automatically updated or not. Use `setUpdateMatrix()`
  6753. * if you want to change the value of the property.
  6754. *
  6755. * @type {boolean}
  6756. * @default false
  6757. */
  6758. this.updateMatrix = false;
  6759. /**
  6760. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6761. * sets the value to `frame` when the uv transformation matrix should
  6762. * automatically be updated.
  6763. *
  6764. * @type {string}
  6765. * @default 'none'
  6766. */
  6767. this.updateType = NodeUpdateType.NONE;
  6768. /**
  6769. * The reference node.
  6770. *
  6771. * @type {?Node}
  6772. * @default null
  6773. */
  6774. this.referenceNode = null;
  6775. /**
  6776. * The texture value is stored in a private property.
  6777. *
  6778. * @private
  6779. * @type {Texture}
  6780. */
  6781. this._value = value;
  6782. /**
  6783. * The uniform node that represents the uv transformation matrix.
  6784. *
  6785. * @private
  6786. * @type {?UniformNode<mat3>}
  6787. */
  6788. this._matrixUniform = null;
  6789. this.setUpdateMatrix( uvNode === null );
  6790. }
  6791. set value( value ) {
  6792. if ( this.referenceNode ) {
  6793. this.referenceNode.value = value;
  6794. } else {
  6795. this._value = value;
  6796. }
  6797. }
  6798. /**
  6799. * The texture value.
  6800. *
  6801. * @type {Texture}
  6802. */
  6803. get value() {
  6804. return this.referenceNode ? this.referenceNode.value : this._value;
  6805. }
  6806. /**
  6807. * Overwritten since the uniform hash is defined by the texture's UUID.
  6808. *
  6809. * @param {NodeBuilder} builder - The current node builder.
  6810. * @return {string} The uniform hash.
  6811. */
  6812. getUniformHash( /*builder*/ ) {
  6813. return this.value.uuid;
  6814. }
  6815. /**
  6816. * Overwritten since the node type is inferred from the texture type.
  6817. *
  6818. * @param {NodeBuilder} builder - The current node builder.
  6819. * @return {string} The node type.
  6820. */
  6821. getNodeType( /*builder*/ ) {
  6822. if ( this.value.isDepthTexture === true ) return 'float';
  6823. if ( this.value.type === UnsignedIntType ) {
  6824. return 'uvec4';
  6825. } else if ( this.value.type === IntType ) {
  6826. return 'ivec4';
  6827. }
  6828. return 'vec4';
  6829. }
  6830. /**
  6831. * Overwrites the default implementation to return a fixed value `'texture'`.
  6832. *
  6833. * @param {NodeBuilder} builder - The current node builder.
  6834. * @return {string} The input type.
  6835. */
  6836. getInputType( /*builder*/ ) {
  6837. return 'texture';
  6838. }
  6839. /**
  6840. * Returns a default uvs based on the current texture's channel.
  6841. *
  6842. * @return {AttributeNode<vec2>} The default uvs.
  6843. */
  6844. getDefaultUV() {
  6845. return uv( this.value.channel );
  6846. }
  6847. /**
  6848. * Overwritten to always return the texture reference of the node.
  6849. *
  6850. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6851. * @return {Texture} The texture reference.
  6852. */
  6853. updateReference( /*state*/ ) {
  6854. return this.value;
  6855. }
  6856. /**
  6857. * Transforms the given uv node with the texture transformation matrix.
  6858. *
  6859. * @param {Node} uvNode - The uv node to transform.
  6860. * @return {Node} The transformed uv node.
  6861. */
  6862. getTransformedUV( uvNode ) {
  6863. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6864. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6865. }
  6866. /**
  6867. * Defines whether the uv transformation matrix should automatically be updated or not.
  6868. *
  6869. * @param {boolean} value - The update toggle.
  6870. * @return {TextureNode} A reference to this node.
  6871. */
  6872. setUpdateMatrix( value ) {
  6873. this.updateMatrix = value;
  6874. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6875. return this;
  6876. }
  6877. /**
  6878. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6879. * to modify the uv node for correct sampling.
  6880. *
  6881. * @param {NodeBuilder} builder - The current node builder.
  6882. * @param {Node} uvNode - The uv node to setup.
  6883. * @return {Node} The updated uv node.
  6884. */
  6885. setupUV( builder, uvNode ) {
  6886. const texture = this.value;
  6887. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6888. if ( this.sampler ) {
  6889. uvNode = uvNode.flipY();
  6890. } else {
  6891. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6892. }
  6893. }
  6894. return uvNode;
  6895. }
  6896. /**
  6897. * Setups texture node by preparing the internal nodes for code generation.
  6898. *
  6899. * @param {NodeBuilder} builder - The current node builder.
  6900. */
  6901. setup( builder ) {
  6902. const properties = builder.getNodeProperties( this );
  6903. properties.referenceNode = this.referenceNode;
  6904. //
  6905. const texture = this.value;
  6906. if ( ! texture || texture.isTexture !== true ) {
  6907. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6908. }
  6909. //
  6910. let uvNode = this.uvNode;
  6911. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6912. uvNode = builder.context.getUV( this );
  6913. }
  6914. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6915. if ( this.updateMatrix === true ) {
  6916. uvNode = this.getTransformedUV( uvNode );
  6917. }
  6918. uvNode = this.setupUV( builder, uvNode );
  6919. //
  6920. let levelNode = this.levelNode;
  6921. if ( levelNode === null && builder.context.getTextureLevel ) {
  6922. levelNode = builder.context.getTextureLevel( this );
  6923. }
  6924. //
  6925. properties.uvNode = uvNode;
  6926. properties.levelNode = levelNode;
  6927. properties.biasNode = this.biasNode;
  6928. properties.compareNode = this.compareNode;
  6929. properties.gradNode = this.gradNode;
  6930. properties.depthNode = this.depthNode;
  6931. }
  6932. /**
  6933. * Generates the uv code snippet.
  6934. *
  6935. * @param {NodeBuilder} builder - The current node builder.
  6936. * @param {Node} uvNode - The uv node to generate code for.
  6937. * @return {string} The generated code snippet.
  6938. */
  6939. generateUV( builder, uvNode ) {
  6940. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6941. }
  6942. /**
  6943. * Generates the snippet for the texture sampling.
  6944. *
  6945. * @param {NodeBuilder} builder - The current node builder.
  6946. * @param {string} textureProperty - The texture property.
  6947. * @param {string} uvSnippet - The uv snippet.
  6948. * @param {?string} levelSnippet - The level snippet.
  6949. * @param {?string} biasSnippet - The bias snippet.
  6950. * @param {?string} depthSnippet - The depth snippet.
  6951. * @param {?string} compareSnippet - The compare snippet.
  6952. * @param {?Array<string>} gradSnippet - The grad snippet.
  6953. * @return {string} The generated code snippet.
  6954. */
  6955. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6956. const texture = this.value;
  6957. let snippet;
  6958. if ( levelSnippet ) {
  6959. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6960. } else if ( biasSnippet ) {
  6961. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6962. } else if ( gradSnippet ) {
  6963. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6964. } else if ( compareSnippet ) {
  6965. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6966. } else if ( this.sampler === false ) {
  6967. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6968. } else {
  6969. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6970. }
  6971. return snippet;
  6972. }
  6973. /**
  6974. * Generates the code snippet of the texture node.
  6975. *
  6976. * @param {NodeBuilder} builder - The current node builder.
  6977. * @param {string} output - The current output.
  6978. * @return {string} The generated code snippet.
  6979. */
  6980. generate( builder, output ) {
  6981. const texture = this.value;
  6982. const properties = builder.getNodeProperties( this );
  6983. const textureProperty = super.generate( builder, 'property' );
  6984. if ( /^sampler/.test( output ) ) {
  6985. return textureProperty + '_sampler';
  6986. } else if ( builder.isReference( output ) ) {
  6987. return textureProperty;
  6988. } else {
  6989. const nodeData = builder.getDataFromNode( this );
  6990. let propertyName = nodeData.propertyName;
  6991. if ( propertyName === undefined ) {
  6992. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6993. const uvSnippet = this.generateUV( builder, uvNode );
  6994. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6995. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6996. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6997. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6998. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6999. const nodeVar = builder.getVarFromNode( this );
  7000. propertyName = builder.getPropertyName( nodeVar );
  7001. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7002. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7003. nodeData.snippet = snippet;
  7004. nodeData.propertyName = propertyName;
  7005. }
  7006. let snippet = propertyName;
  7007. const nodeType = this.getNodeType( builder );
  7008. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7009. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7010. }
  7011. return builder.format( snippet, nodeType, output );
  7012. }
  7013. }
  7014. /**
  7015. * Sets the sampler value.
  7016. *
  7017. * @param {boolean} value - The sampler value to set.
  7018. * @return {TextureNode} A reference to this texture node.
  7019. */
  7020. setSampler( value ) {
  7021. this.sampler = value;
  7022. return this;
  7023. }
  7024. /**
  7025. * Returns the sampler value.
  7026. *
  7027. * @return {boolean} The sampler value.
  7028. */
  7029. getSampler() {
  7030. return this.sampler;
  7031. }
  7032. // @TODO: Move to TSL
  7033. /**
  7034. * @function
  7035. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7036. *
  7037. * @param {Node} uvNode - The uv node.
  7038. * @return {TextureNode} A texture node representing the texture sample.
  7039. */
  7040. uv( uvNode ) { // @deprecated, r172
  7041. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7042. return this.sample( uvNode );
  7043. }
  7044. /**
  7045. * Samples the texture with the given uv node.
  7046. *
  7047. * @param {Node} uvNode - The uv node.
  7048. * @return {TextureNode} A texture node representing the texture sample.
  7049. */
  7050. sample( uvNode ) {
  7051. const textureNode = this.clone();
  7052. textureNode.uvNode = nodeObject( uvNode );
  7053. textureNode.referenceNode = this.getSelf();
  7054. return nodeObject( textureNode );
  7055. }
  7056. /**
  7057. * Samples a blurred version of the texture by defining an internal bias.
  7058. *
  7059. * @param {Node<float>} amountNode - How blurred the texture should be.
  7060. * @return {TextureNode} A texture node representing the texture sample.
  7061. */
  7062. blur( amountNode ) {
  7063. const textureNode = this.clone();
  7064. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7065. textureNode.referenceNode = this.getSelf();
  7066. const map = textureNode.value;
  7067. if ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) {
  7068. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7069. textureNode.biasNode = null;
  7070. }
  7071. return nodeObject( textureNode );
  7072. }
  7073. /**
  7074. * Samples a specific mip of the texture.
  7075. *
  7076. * @param {Node<int>} levelNode - The mip level to sample.
  7077. * @return {TextureNode} A texture node representing the texture sample.
  7078. */
  7079. level( levelNode ) {
  7080. const textureNode = this.clone();
  7081. textureNode.levelNode = nodeObject( levelNode );
  7082. textureNode.referenceNode = this.getSelf();
  7083. return nodeObject( textureNode );
  7084. }
  7085. /**
  7086. * Returns the texture size of the requested level.
  7087. *
  7088. * @param {Node<int>} levelNode - The level to compute the size for.
  7089. * @return {TextureSizeNode} The texture size.
  7090. */
  7091. size( levelNode ) {
  7092. return textureSize( this, levelNode );
  7093. }
  7094. /**
  7095. * Samples the texture with the given bias.
  7096. *
  7097. * @param {Node<float>} biasNode - The bias node.
  7098. * @return {TextureNode} A texture node representing the texture sample.
  7099. */
  7100. bias( biasNode ) {
  7101. const textureNode = this.clone();
  7102. textureNode.biasNode = nodeObject( biasNode );
  7103. textureNode.referenceNode = this.getSelf();
  7104. return nodeObject( textureNode );
  7105. }
  7106. /**
  7107. * Samples the texture by executing a compare operation.
  7108. *
  7109. * @param {Node<float>} compareNode - The node that defines the compare value.
  7110. * @return {TextureNode} A texture node representing the texture sample.
  7111. */
  7112. compare( compareNode ) {
  7113. const textureNode = this.clone();
  7114. textureNode.compareNode = nodeObject( compareNode );
  7115. textureNode.referenceNode = this.getSelf();
  7116. return nodeObject( textureNode );
  7117. }
  7118. /**
  7119. * Samples the texture using an explicit gradient.
  7120. *
  7121. * @param {Node<vec2>} gradNodeX - The gradX node.
  7122. * @param {Node<vec2>} gradNodeY - The gradY node.
  7123. * @return {TextureNode} A texture node representing the texture sample.
  7124. */
  7125. grad( gradNodeX, gradNodeY ) {
  7126. const textureNode = this.clone();
  7127. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7128. textureNode.referenceNode = this.getSelf();
  7129. return nodeObject( textureNode );
  7130. }
  7131. /**
  7132. * Samples the texture by defining a depth node.
  7133. *
  7134. * @param {Node<int>} depthNode - The depth node.
  7135. * @return {TextureNode} A texture node representing the texture sample.
  7136. */
  7137. depth( depthNode ) {
  7138. const textureNode = this.clone();
  7139. textureNode.depthNode = nodeObject( depthNode );
  7140. textureNode.referenceNode = this.getSelf();
  7141. return nodeObject( textureNode );
  7142. }
  7143. // --
  7144. serialize( data ) {
  7145. super.serialize( data );
  7146. data.value = this.value.toJSON( data.meta ).uuid;
  7147. data.sampler = this.sampler;
  7148. data.updateMatrix = this.updateMatrix;
  7149. data.updateType = this.updateType;
  7150. }
  7151. deserialize( data ) {
  7152. super.deserialize( data );
  7153. this.value = data.meta.textures[ data.value ];
  7154. this.sampler = data.sampler;
  7155. this.updateMatrix = data.updateMatrix;
  7156. this.updateType = data.updateType;
  7157. }
  7158. /**
  7159. * The update is used to implement the update of the uv transformation matrix.
  7160. */
  7161. update() {
  7162. const texture = this.value;
  7163. const matrixUniform = this._matrixUniform;
  7164. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7165. if ( texture.matrixAutoUpdate === true ) {
  7166. texture.updateMatrix();
  7167. }
  7168. }
  7169. /**
  7170. * Clones the texture node.
  7171. *
  7172. * @return {TextureNode} The cloned texture node.
  7173. */
  7174. clone() {
  7175. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7176. newNode.sampler = this.sampler;
  7177. return newNode;
  7178. }
  7179. }
  7180. /**
  7181. * TSL function for creating a texture node.
  7182. *
  7183. * @tsl
  7184. * @function
  7185. * @param {Texture} value - The texture.
  7186. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7187. * @param {?Node<int>} [levelNode=null] - The level node.
  7188. * @param {?Node<float>} [biasNode=null] - The bias node.
  7189. * @returns {TextureNode}
  7190. */
  7191. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  7192. /**
  7193. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7194. *
  7195. * @tsl
  7196. * @function
  7197. * @param {Texture} value - The texture.
  7198. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7199. * @param {?Node<int>} [levelNode=null] - The level node.
  7200. * @param {?Node<float>} [biasNode=null] - The bias node.
  7201. * @returns {TextureNode}
  7202. */
  7203. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7204. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7205. /**
  7206. * Converts a texture or texture node to a sampler.
  7207. *
  7208. * @tsl
  7209. * @function
  7210. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7211. * @returns {Node}
  7212. */
  7213. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7214. /**
  7215. * Converts a texture or texture node to a sampler comparison.
  7216. *
  7217. * @tsl
  7218. * @function
  7219. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7220. * @returns {Node}
  7221. */
  7222. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7223. /**
  7224. * A special type of uniform node which represents array-like data
  7225. * as uniform buffers. The access usually happens via `element()`
  7226. * which returns an instance of {@link ArrayElementNode}. For example:
  7227. *
  7228. * ```js
  7229. * const bufferNode = buffer( array, 'mat4', count );
  7230. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7231. * ```
  7232. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7233. * since it handles more input types and automatically cares about buffer paddings.
  7234. *
  7235. * @augments UniformNode
  7236. */
  7237. class BufferNode extends UniformNode {
  7238. static get type() {
  7239. return 'BufferNode';
  7240. }
  7241. /**
  7242. * Constructs a new buffer node.
  7243. *
  7244. * @param {Array<number>} value - Array-like buffer data.
  7245. * @param {string} bufferType - The data type of the buffer.
  7246. * @param {number} [bufferCount=0] - The count of buffer elements.
  7247. */
  7248. constructor( value, bufferType, bufferCount = 0 ) {
  7249. super( value, bufferType );
  7250. /**
  7251. * This flag can be used for type testing.
  7252. *
  7253. * @type {boolean}
  7254. * @readonly
  7255. * @default true
  7256. */
  7257. this.isBufferNode = true;
  7258. /**
  7259. * The data type of the buffer.
  7260. *
  7261. * @type {string}
  7262. */
  7263. this.bufferType = bufferType;
  7264. /**
  7265. * The uniform node that holds the value of the reference node.
  7266. *
  7267. * @type {number}
  7268. * @default 0
  7269. */
  7270. this.bufferCount = bufferCount;
  7271. }
  7272. /**
  7273. * The data type of the buffer elements.
  7274. *
  7275. * @param {NodeBuilder} builder - The current node builder.
  7276. * @return {string} The element type.
  7277. */
  7278. getElementType( builder ) {
  7279. return this.getNodeType( builder );
  7280. }
  7281. /**
  7282. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7283. *
  7284. * @param {NodeBuilder} builder - The current node builder.
  7285. * @return {string} The input type.
  7286. */
  7287. getInputType( /*builder*/ ) {
  7288. return 'buffer';
  7289. }
  7290. }
  7291. /**
  7292. * TSL function for creating a buffer node.
  7293. *
  7294. * @tsl
  7295. * @function
  7296. * @param {Array} value - Array-like buffer data.
  7297. * @param {string} type - The data type of a buffer element.
  7298. * @param {number} count - The count of buffer elements.
  7299. * @returns {BufferNode}
  7300. */
  7301. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7302. /**
  7303. * Represents the element access on uniform array nodes.
  7304. *
  7305. * @augments ArrayElementNode
  7306. */
  7307. class UniformArrayElementNode extends ArrayElementNode {
  7308. static get type() {
  7309. return 'UniformArrayElementNode';
  7310. }
  7311. /**
  7312. * Constructs a new buffer node.
  7313. *
  7314. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7315. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7316. */
  7317. constructor( uniformArrayNode, indexNode ) {
  7318. super( uniformArrayNode, indexNode );
  7319. /**
  7320. * This flag can be used for type testing.
  7321. *
  7322. * @type {boolean}
  7323. * @readonly
  7324. * @default true
  7325. */
  7326. this.isArrayBufferElementNode = true;
  7327. }
  7328. generate( builder ) {
  7329. const snippet = super.generate( builder );
  7330. const type = this.getNodeType();
  7331. const paddedType = this.node.getPaddedType();
  7332. return builder.format( snippet, paddedType, type );
  7333. }
  7334. }
  7335. /**
  7336. * Similar to {@link BufferNode} this module represents array-like data as
  7337. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7338. * data types in the array (e.g `three.js` primitives) and automatically
  7339. * manage buffer padding. It should be the first choice when working with
  7340. * uniforms buffers.
  7341. * ```js
  7342. * const tintColors = uniformArray( [
  7343. * new Color( 1, 0, 0 ),
  7344. * new Color( 0, 1, 0 ),
  7345. * new Color( 0, 0, 1 )
  7346. * ], 'color' );
  7347. *
  7348. * const redColor = tintColors.element( 0 );
  7349. *
  7350. * @augments BufferNode
  7351. */
  7352. class UniformArrayNode extends BufferNode {
  7353. static get type() {
  7354. return 'UniformArrayNode';
  7355. }
  7356. /**
  7357. * Constructs a new uniform array node.
  7358. *
  7359. * @param {Array<any>} value - Array holding the buffer data.
  7360. * @param {?string} [elementType=null] - The data type of a buffer element.
  7361. */
  7362. constructor( value, elementType = null ) {
  7363. super( null );
  7364. /**
  7365. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7366. * hold number primitives as well as three.js objects like vectors, matrices
  7367. * or colors.
  7368. *
  7369. * @type {Array<any>}
  7370. */
  7371. this.array = value;
  7372. /**
  7373. * The data type of an array element.
  7374. *
  7375. * @type {string}
  7376. */
  7377. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7378. /**
  7379. * The padded type. Uniform buffers must conform to a certain buffer layout
  7380. * so a separate type is computed to ensure correct buffer size.
  7381. *
  7382. * @type {string}
  7383. */
  7384. this.paddedType = this.getPaddedType();
  7385. /**
  7386. * Overwritten since uniform array nodes are updated per render.
  7387. *
  7388. * @type {string}
  7389. * @default 'render'
  7390. */
  7391. this.updateType = NodeUpdateType.RENDER;
  7392. /**
  7393. * This flag can be used for type testing.
  7394. *
  7395. * @type {boolean}
  7396. * @readonly
  7397. * @default true
  7398. */
  7399. this.isArrayBufferNode = true;
  7400. }
  7401. /**
  7402. * This method is overwritten since the node type is inferred from the
  7403. * {@link UniformArrayNode#paddedType}.
  7404. *
  7405. * @param {NodeBuilder} builder - The current node builder.
  7406. * @return {string} The node type.
  7407. */
  7408. getNodeType( /*builder*/ ) {
  7409. return this.paddedType;
  7410. }
  7411. /**
  7412. * The data type of the array elements.
  7413. *
  7414. * @param {NodeBuilder} builder - The current node builder.
  7415. * @return {string} The element type.
  7416. */
  7417. getElementType() {
  7418. return this.elementType;
  7419. }
  7420. /**
  7421. * Returns the padded type based on the element type.
  7422. *
  7423. * @return {string} The padded type.
  7424. */
  7425. getPaddedType() {
  7426. const elementType = this.elementType;
  7427. let paddedType = 'vec4';
  7428. if ( elementType === 'mat2' ) {
  7429. paddedType = 'mat2';
  7430. } else if ( /mat/.test( elementType ) === true ) {
  7431. paddedType = 'mat4';
  7432. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7433. paddedType = 'ivec4';
  7434. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7435. paddedType = 'uvec4';
  7436. }
  7437. return paddedType;
  7438. }
  7439. /**
  7440. * The update makes sure to correctly transfer the data from the (complex) objects
  7441. * in the array to the internal, correctly padded value buffer.
  7442. *
  7443. * @param {NodeFrame} frame - A reference to the current node frame.
  7444. */
  7445. update( /*frame*/ ) {
  7446. const { array, value } = this;
  7447. const elementType = this.elementType;
  7448. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7449. for ( let i = 0; i < array.length; i ++ ) {
  7450. const index = i * 4;
  7451. value[ index ] = array[ i ];
  7452. }
  7453. } else if ( elementType === 'color' ) {
  7454. for ( let i = 0; i < array.length; i ++ ) {
  7455. const index = i * 4;
  7456. const vector = array[ i ];
  7457. value[ index ] = vector.r;
  7458. value[ index + 1 ] = vector.g;
  7459. value[ index + 2 ] = vector.b || 0;
  7460. //value[ index + 3 ] = vector.a || 0;
  7461. }
  7462. } else if ( elementType === 'mat2' ) {
  7463. for ( let i = 0; i < array.length; i ++ ) {
  7464. const index = i * 4;
  7465. const matrix = array[ i ];
  7466. value[ index ] = matrix.elements[ 0 ];
  7467. value[ index + 1 ] = matrix.elements[ 1 ];
  7468. value[ index + 2 ] = matrix.elements[ 2 ];
  7469. value[ index + 3 ] = matrix.elements[ 3 ];
  7470. }
  7471. } else if ( elementType === 'mat3' ) {
  7472. for ( let i = 0; i < array.length; i ++ ) {
  7473. const index = i * 16;
  7474. const matrix = array[ i ];
  7475. value[ index ] = matrix.elements[ 0 ];
  7476. value[ index + 1 ] = matrix.elements[ 1 ];
  7477. value[ index + 2 ] = matrix.elements[ 2 ];
  7478. value[ index + 4 ] = matrix.elements[ 3 ];
  7479. value[ index + 5 ] = matrix.elements[ 4 ];
  7480. value[ index + 6 ] = matrix.elements[ 5 ];
  7481. value[ index + 8 ] = matrix.elements[ 6 ];
  7482. value[ index + 9 ] = matrix.elements[ 7 ];
  7483. value[ index + 10 ] = matrix.elements[ 8 ];
  7484. value[ index + 15 ] = 1;
  7485. }
  7486. } else if ( elementType === 'mat4' ) {
  7487. for ( let i = 0; i < array.length; i ++ ) {
  7488. const index = i * 16;
  7489. const matrix = array[ i ];
  7490. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7491. value[ index + i ] = matrix.elements[ i ];
  7492. }
  7493. }
  7494. } else {
  7495. for ( let i = 0; i < array.length; i ++ ) {
  7496. const index = i * 4;
  7497. const vector = array[ i ];
  7498. value[ index ] = vector.x;
  7499. value[ index + 1 ] = vector.y;
  7500. value[ index + 2 ] = vector.z || 0;
  7501. value[ index + 3 ] = vector.w || 0;
  7502. }
  7503. }
  7504. }
  7505. /**
  7506. * Implement the value buffer creation based on the array data.
  7507. *
  7508. * @param {NodeBuilder} builder - A reference to the current node builder.
  7509. * @return {null}
  7510. */
  7511. setup( builder ) {
  7512. const length = this.array.length;
  7513. const elementType = this.elementType;
  7514. let arrayType = Float32Array;
  7515. const paddedType = this.paddedType;
  7516. const paddedElementLength = builder.getTypeLength( paddedType );
  7517. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7518. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7519. this.value = new arrayType( length * paddedElementLength );
  7520. this.bufferCount = length;
  7521. this.bufferType = paddedType;
  7522. return super.setup( builder );
  7523. }
  7524. /**
  7525. * Overwrites the default `element()` method to provide element access
  7526. * based on {@link UniformArrayNode}.
  7527. *
  7528. * @param {IndexNode} indexNode - The index node.
  7529. * @return {UniformArrayElementNode}
  7530. */
  7531. element( indexNode ) {
  7532. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7533. }
  7534. }
  7535. /**
  7536. * TSL function for creating an uniform array node.
  7537. *
  7538. * @tsl
  7539. * @function
  7540. * @param {Array<any>} values - Array-like data.
  7541. * @param {?string} [nodeType] - The data type of the array elements.
  7542. * @returns {UniformArrayNode}
  7543. */
  7544. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7545. /**
  7546. * @tsl
  7547. * @function
  7548. * @deprecated since r168. Use {@link uniformArray} instead.
  7549. *
  7550. * @param {Array<any>} values - Array-like data.
  7551. * @param {string} nodeType - The data type of the array elements.
  7552. * @returns {UniformArrayNode}
  7553. */
  7554. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7555. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7556. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7557. };
  7558. /**
  7559. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7560. *
  7561. * @tsl
  7562. * @type {UniformNode<uint>}
  7563. */
  7564. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7565. /**
  7566. * TSL object that represents the `near` value of the camera used for the current render.
  7567. *
  7568. * @tsl
  7569. * @type {UniformNode<float>}
  7570. */
  7571. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7572. /**
  7573. * TSL object that represents the `far` value of the camera used for the current render.
  7574. *
  7575. * @tsl
  7576. * @type {UniformNode<float>}
  7577. */
  7578. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7579. /**
  7580. * TSL object that represents the projection matrix of the camera used for the current render.
  7581. *
  7582. * @tsl
  7583. * @type {UniformNode<mat4>}
  7584. */
  7585. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7586. let cameraProjectionMatrix;
  7587. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7588. const matrices = [];
  7589. for ( const subCamera of camera.cameras ) {
  7590. matrices.push( subCamera.projectionMatrix );
  7591. }
  7592. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7593. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7594. } else {
  7595. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7596. }
  7597. return cameraProjectionMatrix;
  7598. } ).once() )();
  7599. /**
  7600. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7601. *
  7602. * @tsl
  7603. * @type {UniformNode<mat4>}
  7604. */
  7605. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7606. /**
  7607. * TSL object that represents the view matrix of the camera used for the current render.
  7608. *
  7609. * @tsl
  7610. * @type {UniformNode<mat4>}
  7611. */
  7612. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7613. let cameraViewMatrix;
  7614. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7615. const matrices = [];
  7616. for ( const subCamera of camera.cameras ) {
  7617. matrices.push( subCamera.matrixWorldInverse );
  7618. }
  7619. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7620. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7621. } else {
  7622. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7623. }
  7624. return cameraViewMatrix;
  7625. } ).once() )();
  7626. /**
  7627. * TSL object that represents the world matrix of the camera used for the current render.
  7628. *
  7629. * @tsl
  7630. * @type {UniformNode<mat4>}
  7631. */
  7632. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7633. /**
  7634. * TSL object that represents the normal matrix of the camera used for the current render.
  7635. *
  7636. * @tsl
  7637. * @type {UniformNode<mat3>}
  7638. */
  7639. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7640. /**
  7641. * TSL object that represents the position in world space of the camera used for the current render.
  7642. *
  7643. * @tsl
  7644. * @type {UniformNode<vec3>}
  7645. */
  7646. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7647. const _sphere = /*@__PURE__*/ new Sphere();
  7648. /**
  7649. * This node can be used to access transformation related metrics of 3D objects.
  7650. * Depending on the selected scope, a different metric is represented as a uniform
  7651. * in the shader. The following scopes are supported:
  7652. *
  7653. * - `POSITION`: The object's position in world space.
  7654. * - `VIEW_POSITION`: The object's position in view/camera space.
  7655. * - `DIRECTION`: The object's direction in world space.
  7656. * - `SCALE`: The object's scale in world space.
  7657. * - `WORLD_MATRIX`: The object's matrix in world space.
  7658. *
  7659. * @augments Node
  7660. */
  7661. class Object3DNode extends Node {
  7662. static get type() {
  7663. return 'Object3DNode';
  7664. }
  7665. /**
  7666. * Constructs a new object 3D node.
  7667. *
  7668. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7669. * @param {?Object3D} [object3d=null] - The 3D object.
  7670. */
  7671. constructor( scope, object3d = null ) {
  7672. super();
  7673. /**
  7674. * The node reports a different type of transformation depending on the scope.
  7675. *
  7676. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7677. */
  7678. this.scope = scope;
  7679. /**
  7680. * The 3D object.
  7681. *
  7682. * @type {?Object3D}
  7683. * @default null
  7684. */
  7685. this.object3d = object3d;
  7686. /**
  7687. * Overwritten since this type of node is updated per object.
  7688. *
  7689. * @type {string}
  7690. * @default 'object'
  7691. */
  7692. this.updateType = NodeUpdateType.OBJECT;
  7693. /**
  7694. * Holds the value of the node as a uniform.
  7695. *
  7696. * @private
  7697. * @type {UniformNode}
  7698. */
  7699. this._uniformNode = new UniformNode( null );
  7700. }
  7701. /**
  7702. * Overwritten since the node type is inferred from the scope.
  7703. *
  7704. * @return {string} The node type.
  7705. */
  7706. getNodeType() {
  7707. const scope = this.scope;
  7708. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7709. return 'mat4';
  7710. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7711. return 'vec3';
  7712. } else if ( scope === Object3DNode.RADIUS ) {
  7713. return 'float';
  7714. }
  7715. }
  7716. /**
  7717. * Updates the uniform value depending on the scope.
  7718. *
  7719. * @param {NodeFrame} frame - The current node frame.
  7720. */
  7721. update( frame ) {
  7722. const object = this.object3d;
  7723. const uniformNode = this._uniformNode;
  7724. const scope = this.scope;
  7725. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7726. uniformNode.value = object.matrixWorld;
  7727. } else if ( scope === Object3DNode.POSITION ) {
  7728. uniformNode.value = uniformNode.value || new Vector3();
  7729. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7730. } else if ( scope === Object3DNode.SCALE ) {
  7731. uniformNode.value = uniformNode.value || new Vector3();
  7732. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7733. } else if ( scope === Object3DNode.DIRECTION ) {
  7734. uniformNode.value = uniformNode.value || new Vector3();
  7735. object.getWorldDirection( uniformNode.value );
  7736. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7737. const camera = frame.camera;
  7738. uniformNode.value = uniformNode.value || new Vector3();
  7739. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7740. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7741. } else if ( scope === Object3DNode.RADIUS ) {
  7742. const geometry = frame.object.geometry;
  7743. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7744. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7745. uniformNode.value = _sphere.radius;
  7746. }
  7747. }
  7748. /**
  7749. * Generates the code snippet of the uniform node. The node type of the uniform
  7750. * node also depends on the selected scope.
  7751. *
  7752. * @param {NodeBuilder} builder - The current node builder.
  7753. * @return {string} The generated code snippet.
  7754. */
  7755. generate( builder ) {
  7756. const scope = this.scope;
  7757. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7758. this._uniformNode.nodeType = 'mat4';
  7759. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7760. this._uniformNode.nodeType = 'vec3';
  7761. } else if ( scope === Object3DNode.RADIUS ) {
  7762. this._uniformNode.nodeType = 'float';
  7763. }
  7764. return this._uniformNode.build( builder );
  7765. }
  7766. serialize( data ) {
  7767. super.serialize( data );
  7768. data.scope = this.scope;
  7769. }
  7770. deserialize( data ) {
  7771. super.deserialize( data );
  7772. this.scope = data.scope;
  7773. }
  7774. }
  7775. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7776. Object3DNode.POSITION = 'position';
  7777. Object3DNode.SCALE = 'scale';
  7778. Object3DNode.VIEW_POSITION = 'viewPosition';
  7779. Object3DNode.DIRECTION = 'direction';
  7780. Object3DNode.RADIUS = 'radius';
  7781. /**
  7782. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7783. *
  7784. * @tsl
  7785. * @function
  7786. * @param {?Object3D} [object3d=null] - The 3D object.
  7787. * @returns {Object3DNode<vec3>}
  7788. */
  7789. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7790. /**
  7791. * TSL function for creating an object 3D node that represents the object's world matrix.
  7792. *
  7793. * @tsl
  7794. * @function
  7795. * @param {?Object3D} [object3d=null] - The 3D object.
  7796. * @returns {Object3DNode<mat4>}
  7797. */
  7798. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7799. /**
  7800. * TSL function for creating an object 3D node that represents the object's position in world space.
  7801. *
  7802. * @tsl
  7803. * @function
  7804. * @param {?Object3D} [object3d=null] - The 3D object.
  7805. * @returns {Object3DNode<vec3>}
  7806. */
  7807. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7808. /**
  7809. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7810. *
  7811. * @tsl
  7812. * @function
  7813. * @param {?Object3D} [object3d=null] - The 3D object.
  7814. * @returns {Object3DNode<vec3>}
  7815. */
  7816. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7817. /**
  7818. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7819. *
  7820. * @tsl
  7821. * @function
  7822. * @param {?Object3D} [object3d=null] - The 3D object.
  7823. * @returns {Object3DNode<vec3>}
  7824. */
  7825. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7826. /**
  7827. * TSL function for creating an object 3D node that represents the object's radius.
  7828. *
  7829. * @tsl
  7830. * @function
  7831. * @param {?Object3D} [object3d=null] - The 3D object.
  7832. * @returns {Object3DNode<vec3>}
  7833. */
  7834. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS );
  7835. /**
  7836. * This type of node is a specialized version of `Object3DNode`
  7837. * with larger set of model related metrics. Unlike `Object3DNode`,
  7838. * `ModelNode` extracts the reference to the 3D object from the
  7839. * current node frame state.
  7840. *
  7841. * @augments Object3DNode
  7842. */
  7843. class ModelNode extends Object3DNode {
  7844. static get type() {
  7845. return 'ModelNode';
  7846. }
  7847. /**
  7848. * Constructs a new object model node.
  7849. *
  7850. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7851. */
  7852. constructor( scope ) {
  7853. super( scope );
  7854. }
  7855. /**
  7856. * Extracts the model reference from the frame state and then
  7857. * updates the uniform value depending on the scope.
  7858. *
  7859. * @param {NodeFrame} frame - The current node frame.
  7860. */
  7861. update( frame ) {
  7862. this.object3d = frame.object;
  7863. super.update( frame );
  7864. }
  7865. }
  7866. /**
  7867. * TSL object that represents the object's direction in world space.
  7868. *
  7869. * @tsl
  7870. * @type {ModelNode<vec3>}
  7871. */
  7872. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7873. /**
  7874. * TSL object that represents the object's world matrix.
  7875. *
  7876. * @tsl
  7877. * @type {ModelNode<mat4>}
  7878. */
  7879. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7880. /**
  7881. * TSL object that represents the object's position in world space.
  7882. *
  7883. * @tsl
  7884. * @type {ModelNode<vec3>}
  7885. */
  7886. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7887. /**
  7888. * TSL object that represents the object's scale in world space.
  7889. *
  7890. * @tsl
  7891. * @type {ModelNode<vec3>}
  7892. */
  7893. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7894. /**
  7895. * TSL object that represents the object's position in view/camera space.
  7896. *
  7897. * @tsl
  7898. * @type {ModelNode<vec3>}
  7899. */
  7900. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7901. /**
  7902. * TSL object that represents the object's radius.
  7903. *
  7904. * @tsl
  7905. * @type {ModelNode<float>}
  7906. */
  7907. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  7908. /**
  7909. * TSL object that represents the object's normal matrix.
  7910. *
  7911. * @tsl
  7912. * @type {UniformNode<mat3>}
  7913. */
  7914. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7915. /**
  7916. * TSL object that represents the object's inverse world matrix.
  7917. *
  7918. * @tsl
  7919. * @type {UniformNode<mat4>}
  7920. */
  7921. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7922. /**
  7923. * TSL object that represents the object's model view matrix.
  7924. *
  7925. * @tsl
  7926. * @type {Node<mat4>}
  7927. */
  7928. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7929. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7930. } ).once() )().toVar( 'modelViewMatrix' );
  7931. // GPU Precision
  7932. /**
  7933. * TSL object that represents the object's model view in `mediump` precision.
  7934. *
  7935. * @tsl
  7936. * @type {Node<mat4>}
  7937. */
  7938. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7939. // CPU Precision
  7940. /**
  7941. * TSL object that represents the object's model view in `highp` precision
  7942. * which is achieved by computing the matrix in JS and not in the shader.
  7943. *
  7944. * @tsl
  7945. * @type {Node<mat4>}
  7946. */
  7947. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7948. builder.context.isHighPrecisionModelViewMatrix = true;
  7949. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7950. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7951. } );
  7952. } ).once() )().toVar( 'highpModelViewMatrix' );
  7953. /**
  7954. * TSL object that represents the object's model normal view in `highp` precision
  7955. * which is achieved by computing the matrix in JS and not in the shader.
  7956. *
  7957. * @tsl
  7958. * @type {Node<mat3>}
  7959. */
  7960. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7961. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7962. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7963. if ( isHighPrecisionModelViewMatrix !== true ) {
  7964. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7965. }
  7966. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7967. } );
  7968. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7969. /**
  7970. * TSL object that represents the position attribute of the current rendered object.
  7971. *
  7972. * @tsl
  7973. * @type {AttributeNode<vec3>}
  7974. */
  7975. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7976. /**
  7977. * TSL object that represents the vertex position in local space of the current rendered object.
  7978. *
  7979. * @tsl
  7980. * @type {AttributeNode<vec3>}
  7981. */
  7982. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7983. /**
  7984. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7985. * Used in context of {@link VelocityNode} for rendering motion vectors.
  7986. *
  7987. * @tsl
  7988. * @type {AttributeNode<vec3>}
  7989. */
  7990. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7991. /**
  7992. * TSL object that represents the vertex position in world space of the current rendered object.
  7993. *
  7994. * @tsl
  7995. * @type {VaryingNode<vec3>}
  7996. */
  7997. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7998. /**
  7999. * TSL object that represents the position world direction of the current rendered object.
  8000. *
  8001. * @tsl
  8002. * @type {Node<vec3>}
  8003. */
  8004. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  8005. /**
  8006. * TSL object that represents the vertex position in view space of the current rendered object.
  8007. *
  8008. * @tsl
  8009. * @type {VaryingNode<vec3>}
  8010. */
  8011. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8012. return builder.context.setupPositionView();
  8013. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  8014. /**
  8015. * TSL object that represents the position view direction of the current rendered object.
  8016. *
  8017. * @tsl
  8018. * @type {VaryingNode<vec3>}
  8019. */
  8020. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8021. /**
  8022. * This node can be used to evaluate whether a primitive is front or back facing.
  8023. *
  8024. * @augments Node
  8025. */
  8026. class FrontFacingNode extends Node {
  8027. static get type() {
  8028. return 'FrontFacingNode';
  8029. }
  8030. /**
  8031. * Constructs a new front facing node.
  8032. */
  8033. constructor() {
  8034. super( 'bool' );
  8035. /**
  8036. * This flag can be used for type testing.
  8037. *
  8038. * @type {boolean}
  8039. * @readonly
  8040. * @default true
  8041. */
  8042. this.isFrontFacingNode = true;
  8043. }
  8044. generate( builder ) {
  8045. const { renderer, material } = builder;
  8046. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8047. if ( material.side === BackSide ) {
  8048. return 'false';
  8049. }
  8050. }
  8051. return builder.getFrontFacing();
  8052. }
  8053. }
  8054. /**
  8055. * TSL object that represents whether a primitive is front or back facing
  8056. *
  8057. * @tsl
  8058. * @type {FrontFacingNode<bool>}
  8059. */
  8060. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8061. /**
  8062. * TSL object that represents the front facing status as a number instead of a bool.
  8063. * `1` means front facing, `-1` means back facing.
  8064. *
  8065. * @tsl
  8066. * @type {Node<float>}
  8067. */
  8068. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8069. /**
  8070. * TSL object that represents the normal attribute of the current rendered object.
  8071. *
  8072. * @tsl
  8073. * @type {Node<vec3>}
  8074. */
  8075. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8076. /**
  8077. * TSL object that represents the vertex normal in local space of the current rendered object.
  8078. *
  8079. * @tsl
  8080. * @type {Node<vec3>}
  8081. */
  8082. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8083. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8084. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  8085. return vec3( 0, 1, 0 );
  8086. }
  8087. return normalGeometry;
  8088. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8089. /**
  8090. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8091. *
  8092. * @tsl
  8093. * @type {Node<vec3>}
  8094. */
  8095. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8096. /**
  8097. * TSL object that represents the vertex normal in view space of the current rendered object.
  8098. *
  8099. * @tsl
  8100. * @type {Node<vec3>}
  8101. */
  8102. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8103. let node;
  8104. if ( builder.material.flatShading === true ) {
  8105. node = normalFlat;
  8106. } else {
  8107. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8108. }
  8109. return node;
  8110. }, 'vec3' ).once() )().toVar( 'normalView' );
  8111. /**
  8112. * TSL object that represents the vertex normal in world space of the current rendered object.
  8113. *
  8114. * @tsl
  8115. * @type {Node<vec3>}
  8116. */
  8117. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  8118. /**
  8119. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8120. *
  8121. * @tsl
  8122. * @type {Node<vec3>}
  8123. */
  8124. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8125. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8126. return builder.context.setupNormal().context( { getUV: null } );
  8127. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  8128. /**
  8129. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8130. *
  8131. * @tsl
  8132. * @type {Node<vec3>}
  8133. */
  8134. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8135. /**
  8136. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8137. *
  8138. * @tsl
  8139. * @type {Node<vec3>}
  8140. */
  8141. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8142. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8143. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  8144. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  8145. /**
  8146. * Transforms the normal with the given matrix.
  8147. *
  8148. * @tsl
  8149. * @function
  8150. * @param {Node<vec3>} normal - The normal.
  8151. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8152. * @return {Node<vec3>} The transformed normal.
  8153. */
  8154. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8155. const m = mat3( matrix );
  8156. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8157. return m.mul( transformedNormal ).xyz;
  8158. } );
  8159. /**
  8160. * Transforms the given normal from local to view space.
  8161. *
  8162. * @tsl
  8163. * @function
  8164. * @param {Node<vec3>} normal - The normal.
  8165. * @param {NodeBuilder} builder - The current node builder.
  8166. * @return {Node<vec3>} The transformed normal.
  8167. */
  8168. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8169. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  8170. if ( modelNormalViewMatrix !== null ) {
  8171. return modelNormalViewMatrix.transformDirection( normal );
  8172. }
  8173. //
  8174. const transformedNormal = modelNormalMatrix.mul( normal );
  8175. return cameraViewMatrix.transformDirection( transformedNormal );
  8176. } );
  8177. const _e1$1 = /*@__PURE__*/ new Euler();
  8178. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8179. /**
  8180. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8181. *
  8182. * @tsl
  8183. * @type {UniformNode<float>}
  8184. */
  8185. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8186. /**
  8187. * TSL object that represents the intensity of environment maps of PBR materials.
  8188. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8189. *
  8190. * @tsl
  8191. * @type {Node<float>}
  8192. */
  8193. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8194. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8195. } );
  8196. /**
  8197. * TSL object that represents the rotation of environment maps.
  8198. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8199. * rotation of `scene.environment` instead.
  8200. *
  8201. * @tsl
  8202. * @type {Node<mat4>}
  8203. */
  8204. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8205. return frame.material;
  8206. } ).onObjectUpdate( function ( { material, scene } ) {
  8207. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8208. if ( rotation ) {
  8209. _e1$1.copy( rotation );
  8210. _m1$1.makeRotationFromEuler( _e1$1 );
  8211. } else {
  8212. _m1$1.identity();
  8213. }
  8214. return _m1$1;
  8215. } );
  8216. /**
  8217. * The reflect vector in view space.
  8218. *
  8219. * @tsl
  8220. * @type {Node<vec3>}
  8221. */
  8222. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8223. /**
  8224. * The refract vector in view space.
  8225. *
  8226. * @tsl
  8227. * @type {Node<vec3>}
  8228. */
  8229. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8230. /**
  8231. * Used for sampling cube maps when using cube reflection mapping.
  8232. *
  8233. * @tsl
  8234. * @type {Node<vec3>}
  8235. */
  8236. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8237. /**
  8238. * Used for sampling cube maps when using cube refraction mapping.
  8239. *
  8240. * @tsl
  8241. * @type {Node<vec3>}
  8242. */
  8243. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8244. /**
  8245. * This type of uniform node represents a cube texture.
  8246. *
  8247. * @augments TextureNode
  8248. */
  8249. class CubeTextureNode extends TextureNode {
  8250. static get type() {
  8251. return 'CubeTextureNode';
  8252. }
  8253. /**
  8254. * Constructs a new cube texture node.
  8255. *
  8256. * @param {CubeTexture} value - The cube texture.
  8257. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8258. * @param {?Node<int>} [levelNode=null] - The level node.
  8259. * @param {?Node<float>} [biasNode=null] - The bias node.
  8260. */
  8261. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8262. super( value, uvNode, levelNode, biasNode );
  8263. /**
  8264. * This flag can be used for type testing.
  8265. *
  8266. * @type {boolean}
  8267. * @readonly
  8268. * @default true
  8269. */
  8270. this.isCubeTextureNode = true;
  8271. }
  8272. /**
  8273. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8274. *
  8275. * @param {NodeBuilder} builder - The current node builder.
  8276. * @return {string} The input type.
  8277. */
  8278. getInputType( /*builder*/ ) {
  8279. return 'cubeTexture';
  8280. }
  8281. /**
  8282. * Returns a default uvs based on the mapping type of the cube texture.
  8283. *
  8284. * @return {Node<vec3>} The default uv attribute.
  8285. */
  8286. getDefaultUV() {
  8287. const texture = this.value;
  8288. if ( texture.mapping === CubeReflectionMapping ) {
  8289. return reflectVector;
  8290. } else if ( texture.mapping === CubeRefractionMapping ) {
  8291. return refractVector;
  8292. } else {
  8293. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8294. return vec3( 0, 0, 0 );
  8295. }
  8296. }
  8297. /**
  8298. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8299. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8300. *
  8301. * @param {boolean} value - The update toggle.
  8302. */
  8303. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8304. /**
  8305. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8306. * to modify the uv node for correct sampling.
  8307. *
  8308. * @param {NodeBuilder} builder - The current node builder.
  8309. * @param {Node} uvNode - The uv node to setup.
  8310. * @return {Node} The updated uv node.
  8311. */
  8312. setupUV( builder, uvNode ) {
  8313. const texture = this.value;
  8314. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8315. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8316. }
  8317. return materialEnvRotation.mul( uvNode );
  8318. }
  8319. /**
  8320. * Generates the uv code snippet.
  8321. *
  8322. * @param {NodeBuilder} builder - The current node builder.
  8323. * @param {Node} cubeUV - The uv node to generate code for.
  8324. * @return {string} The generated code snippet.
  8325. */
  8326. generateUV( builder, cubeUV ) {
  8327. return cubeUV.build( builder, 'vec3' );
  8328. }
  8329. }
  8330. /**
  8331. * TSL function for creating a cube texture node.
  8332. *
  8333. * @tsl
  8334. * @function
  8335. * @param {CubeTexture} value - The cube texture.
  8336. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8337. * @param {?Node<int>} [levelNode=null] - The level node.
  8338. * @param {?Node<float>} [biasNode=null] - The bias node.
  8339. * @returns {CubeTextureNode}
  8340. */
  8341. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  8342. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8343. /**
  8344. * This class is only relevant if the referenced property is array-like.
  8345. * In this case, `ReferenceElementNode` allows to refer to a specific
  8346. * element inside the data structure via an index.
  8347. *
  8348. * @augments ArrayElementNode
  8349. */
  8350. class ReferenceElementNode extends ArrayElementNode {
  8351. static get type() {
  8352. return 'ReferenceElementNode';
  8353. }
  8354. /**
  8355. * Constructs a new reference element node.
  8356. *
  8357. * @param {?ReferenceNode} referenceNode - The reference node.
  8358. * @param {Node} indexNode - The index node that defines the element access.
  8359. */
  8360. constructor( referenceNode, indexNode ) {
  8361. super( referenceNode, indexNode );
  8362. /**
  8363. * Similar to {@link ReferenceNode#reference}, an additional
  8364. * property references to the current node.
  8365. *
  8366. * @type {?ReferenceNode}
  8367. * @default null
  8368. */
  8369. this.referenceNode = referenceNode;
  8370. /**
  8371. * This flag can be used for type testing.
  8372. *
  8373. * @type {boolean}
  8374. * @readonly
  8375. * @default true
  8376. */
  8377. this.isReferenceElementNode = true;
  8378. }
  8379. /**
  8380. * This method is overwritten since the node type is inferred from
  8381. * the uniform type of the reference node.
  8382. *
  8383. * @return {string} The node type.
  8384. */
  8385. getNodeType() {
  8386. return this.referenceNode.uniformType;
  8387. }
  8388. generate( builder ) {
  8389. const snippet = super.generate( builder );
  8390. const arrayType = this.referenceNode.getNodeType();
  8391. const elementType = this.getNodeType();
  8392. return builder.format( snippet, arrayType, elementType );
  8393. }
  8394. }
  8395. /**
  8396. * This type of node establishes a reference to a property of another object.
  8397. * In this way, the value of the node is automatically linked to the value of
  8398. * referenced object. Reference nodes internally represent the linked value
  8399. * as a uniform.
  8400. *
  8401. * @augments Node
  8402. */
  8403. class ReferenceNode extends Node {
  8404. static get type() {
  8405. return 'ReferenceNode';
  8406. }
  8407. /**
  8408. * Constructs a new reference node.
  8409. *
  8410. * @param {string} property - The name of the property the node refers to.
  8411. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  8412. * @param {?Object} [object=null] - The object the property belongs to.
  8413. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8414. */
  8415. constructor( property, uniformType, object = null, count = null ) {
  8416. super();
  8417. /**
  8418. * The name of the property the node refers to.
  8419. *
  8420. * @type {string}
  8421. */
  8422. this.property = property;
  8423. /**
  8424. * The uniform type that should be used to represent the property value.
  8425. *
  8426. * @type {string}
  8427. */
  8428. this.uniformType = uniformType;
  8429. /**
  8430. * The object the property belongs to.
  8431. *
  8432. * @type {?Object}
  8433. * @default null
  8434. */
  8435. this.object = object;
  8436. /**
  8437. * When the linked property is an array, this parameter defines its length.
  8438. *
  8439. * @type {?number}
  8440. * @default null
  8441. */
  8442. this.count = count;
  8443. /**
  8444. * The property name might have dots so nested properties can be referred.
  8445. * The hierarchy of the names is stored inside this array.
  8446. *
  8447. * @type {Array<string>}
  8448. */
  8449. this.properties = property.split( '.' );
  8450. /**
  8451. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  8452. * since the final reference might be updated from calling code.
  8453. *
  8454. * @type {?Object}
  8455. * @default null
  8456. */
  8457. this.reference = object;
  8458. /**
  8459. * The uniform node that holds the value of the reference node.
  8460. *
  8461. * @type {UniformNode}
  8462. * @default null
  8463. */
  8464. this.node = null;
  8465. /**
  8466. * The uniform group of the internal uniform.
  8467. *
  8468. * @type {UniformGroupNode}
  8469. * @default null
  8470. */
  8471. this.group = null;
  8472. /**
  8473. * An optional label of the internal uniform node.
  8474. *
  8475. * @type {?string}
  8476. * @default null
  8477. */
  8478. this.name = null;
  8479. /**
  8480. * Overwritten since reference nodes are updated per object.
  8481. *
  8482. * @type {string}
  8483. * @default 'object'
  8484. */
  8485. this.updateType = NodeUpdateType.OBJECT;
  8486. }
  8487. /**
  8488. * When the referred property is array-like, this method can be used
  8489. * to access elements via an index node.
  8490. *
  8491. * @param {IndexNode} indexNode - indexNode.
  8492. * @return {ReferenceElementNode} A reference to an element.
  8493. */
  8494. element( indexNode ) {
  8495. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8496. }
  8497. /**
  8498. * Sets the uniform group for this reference node.
  8499. *
  8500. * @param {UniformGroupNode} group - The uniform group to set.
  8501. * @return {ReferenceNode} A reference to this node.
  8502. */
  8503. setGroup( group ) {
  8504. this.group = group;
  8505. return this;
  8506. }
  8507. /**
  8508. * Sets the label for the internal uniform.
  8509. *
  8510. * @param {string} name - The label to set.
  8511. * @return {ReferenceNode} A reference to this node.
  8512. */
  8513. label( name ) {
  8514. this.name = name;
  8515. return this;
  8516. }
  8517. /**
  8518. * Sets the node type which automatically defines the internal
  8519. * uniform type.
  8520. *
  8521. * @param {string} uniformType - The type to set.
  8522. */
  8523. setNodeType( uniformType ) {
  8524. let node = null;
  8525. if ( this.count !== null ) {
  8526. node = buffer( null, uniformType, this.count );
  8527. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8528. node = uniformArray( null, uniformType );
  8529. } else if ( uniformType === 'texture' ) {
  8530. node = texture( null );
  8531. } else if ( uniformType === 'cubeTexture' ) {
  8532. node = cubeTexture( null );
  8533. } else {
  8534. node = uniform( null, uniformType );
  8535. }
  8536. if ( this.group !== null ) {
  8537. node.setGroup( this.group );
  8538. }
  8539. if ( this.name !== null ) node.label( this.name );
  8540. this.node = node.getSelf();
  8541. }
  8542. /**
  8543. * This method is overwritten since the node type is inferred from
  8544. * the type of the reference node.
  8545. *
  8546. * @param {NodeBuilder} builder - The current node builder.
  8547. * @return {string} The node type.
  8548. */
  8549. getNodeType( builder ) {
  8550. if ( this.node === null ) {
  8551. this.updateReference( builder );
  8552. this.updateValue();
  8553. }
  8554. return this.node.getNodeType( builder );
  8555. }
  8556. /**
  8557. * Returns the property value from the given referred object.
  8558. *
  8559. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8560. * @return {any} The value.
  8561. */
  8562. getValueFromReference( object = this.reference ) {
  8563. const { properties } = this;
  8564. let value = object[ properties[ 0 ] ];
  8565. for ( let i = 1; i < properties.length; i ++ ) {
  8566. value = value[ properties[ i ] ];
  8567. }
  8568. return value;
  8569. }
  8570. /**
  8571. * Allows to update the reference based on the given state. The state is only
  8572. * evaluated {@link ReferenceNode#object} is not set.
  8573. *
  8574. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8575. * @return {Object} The updated reference.
  8576. */
  8577. updateReference( state ) {
  8578. this.reference = this.object !== null ? this.object : state.object;
  8579. return this.reference;
  8580. }
  8581. /**
  8582. * The output of the reference node is the internal uniform node.
  8583. *
  8584. * @param {NodeBuilder} builder - The current node builder.
  8585. * @return {UniformNode} The output node.
  8586. */
  8587. setup( /* builder */ ) {
  8588. this.updateValue();
  8589. return this.node;
  8590. }
  8591. /**
  8592. * Overwritten to to update the internal uniform value.
  8593. *
  8594. * @param {NodeFrame} frame - A reference to the current node frame.
  8595. */
  8596. update( /*frame*/ ) {
  8597. this.updateValue();
  8598. }
  8599. /**
  8600. * Retrieves the value from the referred object property and uses it
  8601. * to updated the internal uniform.
  8602. */
  8603. updateValue() {
  8604. if ( this.node === null ) this.setNodeType( this.uniformType );
  8605. const value = this.getValueFromReference();
  8606. if ( Array.isArray( value ) ) {
  8607. this.node.array = value;
  8608. } else {
  8609. this.node.value = value;
  8610. }
  8611. }
  8612. }
  8613. /**
  8614. * TSL function for creating a reference node.
  8615. *
  8616. * @tsl
  8617. * @function
  8618. * @param {string} name - The name of the property the node refers to.
  8619. * @param {string} type - The uniform type that should be used to represent the property value.
  8620. * @param {?Object} [object] - The object the property belongs to.
  8621. * @returns {ReferenceNode}
  8622. */
  8623. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8624. /**
  8625. * TSL function for creating a reference node. Use this function if you want need a reference
  8626. * to an array-like property that should be represented as a uniform buffer.
  8627. *
  8628. * @tsl
  8629. * @function
  8630. * @param {string} name - The name of the property the node refers to.
  8631. * @param {string} type - The uniform type that should be used to represent the property value.
  8632. * @param {number} count - The number of value inside the array-like object.
  8633. * @param {Object} object - An array-like object the property belongs to.
  8634. * @returns {ReferenceNode}
  8635. */
  8636. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8637. /**
  8638. * This node is a special type of reference node which is intended
  8639. * for linking material properties with node values.
  8640. * ```js
  8641. * const opacityNode = materialReference( 'opacity', 'float', material );
  8642. * ```
  8643. * When changing `material.opacity`, the node value of `opacityNode` will
  8644. * automatically be updated.
  8645. *
  8646. * @augments ReferenceNode
  8647. */
  8648. class MaterialReferenceNode extends ReferenceNode {
  8649. static get type() {
  8650. return 'MaterialReferenceNode';
  8651. }
  8652. /**
  8653. * Constructs a new material reference node.
  8654. *
  8655. * @param {string} property - The name of the property the node refers to.
  8656. * @param {string} inputType - The uniform type that should be used to represent the property value.
  8657. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  8658. * the node refers to the material of the current rendered object.
  8659. */
  8660. constructor( property, inputType, material = null ) {
  8661. super( property, inputType, material );
  8662. /**
  8663. * The material the property belongs to. When no material is set,
  8664. * the node refers to the material of the current rendered object.
  8665. *
  8666. * @type {?Material}
  8667. * @default null
  8668. */
  8669. this.material = material;
  8670. /**
  8671. * This flag can be used for type testing.
  8672. *
  8673. * @type {boolean}
  8674. * @readonly
  8675. * @default true
  8676. */
  8677. this.isMaterialReferenceNode = true;
  8678. }
  8679. /**
  8680. * Updates the reference based on the given state. The state is only evaluated
  8681. * {@link MaterialReferenceNode#material} is not set.
  8682. *
  8683. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8684. * @return {Object} The updated reference.
  8685. */
  8686. updateReference( state ) {
  8687. this.reference = this.material !== null ? this.material : state.material;
  8688. return this.reference;
  8689. }
  8690. }
  8691. /**
  8692. * TSL function for creating a material reference node.
  8693. *
  8694. * @tsl
  8695. * @function
  8696. * @param {string} name - The name of the property the node refers to.
  8697. * @param {string} type - The uniform type that should be used to represent the property value.
  8698. * @param {?Material} [material=null] - The material the property belongs to.
  8699. * When no material is set, the node refers to the material of the current rendered object.
  8700. * @returns {MaterialReferenceNode}
  8701. */
  8702. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8703. /**
  8704. * TSL object that represents the tangent attribute of the current rendered object.
  8705. *
  8706. * @tsl
  8707. * @type {Node<vec4>}
  8708. */
  8709. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8710. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8711. builder.geometry.computeTangents();
  8712. }
  8713. return attribute( 'tangent', 'vec4' );
  8714. } )();
  8715. /**
  8716. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8717. *
  8718. * @tsl
  8719. * @type {Node<vec3>}
  8720. */
  8721. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8722. /**
  8723. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8724. *
  8725. * @tsl
  8726. * @type {Node<vec3>}
  8727. */
  8728. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8729. /**
  8730. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8731. *
  8732. * @tsl
  8733. * @type {Node<vec3>}
  8734. */
  8735. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8736. /**
  8737. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8738. *
  8739. * @tsl
  8740. * @type {Node<vec3>}
  8741. */
  8742. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8743. /**
  8744. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8745. *
  8746. * @tsl
  8747. * @type {Node<vec3>}
  8748. */
  8749. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8750. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8751. /**
  8752. * TSL object that represents the bitangent attribute of the current rendered object.
  8753. *
  8754. * @tsl
  8755. * @type {Node<vec3>}
  8756. */
  8757. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8758. /**
  8759. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8760. *
  8761. * @tsl
  8762. * @type {Node<vec3>}
  8763. */
  8764. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8765. /**
  8766. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8767. *
  8768. * @tsl
  8769. * @type {Node<vec4>}
  8770. */
  8771. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8772. /**
  8773. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8774. *
  8775. * @tsl
  8776. * @type {Node<vec4>}
  8777. */
  8778. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8779. /**
  8780. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8781. *
  8782. * @tsl
  8783. * @type {Node<vec4>}
  8784. */
  8785. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8786. /**
  8787. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8788. *
  8789. * @tsl
  8790. * @type {Node<vec4>}
  8791. */
  8792. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8793. /**
  8794. * TSL object that represents the TBN matrix in view space.
  8795. *
  8796. * @tsl
  8797. * @type {Node<mat3>}
  8798. */
  8799. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8800. /**
  8801. * TSL object that represents the parallax direction.
  8802. *
  8803. * @tsl
  8804. * @type {Node<mat3>}
  8805. */
  8806. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8807. /**
  8808. * TSL function for computing parallax uv coordinates.
  8809. *
  8810. * @tsl
  8811. * @function
  8812. * @param {Node<vec2>} uv - A uv node.
  8813. * @param {Node<vec2>} scale - A scale node.
  8814. * @returns {Node<vec2>} Parallax uv coordinates.
  8815. */
  8816. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8817. /**
  8818. * TSL function for computing bent normals.
  8819. *
  8820. * @tsl
  8821. * @function
  8822. * @returns {Node<vec3>} Bent normals.
  8823. */
  8824. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8825. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8826. let bentNormal = anisotropyB.cross( positionViewDirection );
  8827. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8828. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8829. return bentNormal;
  8830. } )();
  8831. // Normal Mapping Without Precomputed Tangents
  8832. // http://www.thetenthplanet.de/archives/1180
  8833. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8834. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8835. const q0 = eye_pos.dFdx();
  8836. const q1 = eye_pos.dFdy();
  8837. const st0 = uv.dFdx();
  8838. const st1 = uv.dFdy();
  8839. const N = surf_norm; // normalized
  8840. const q1perp = q1.cross( N );
  8841. const q0perp = N.cross( q0 );
  8842. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8843. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8844. const det = T.dot( T ).max( B.dot( B ) );
  8845. const scale = faceDirection.mul( det.inverseSqrt() );
  8846. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8847. } );
  8848. /**
  8849. * This class can be used for applying normals maps to materials.
  8850. *
  8851. * ```js
  8852. * material.normalNode = normalMap( texture( normalTex ) );
  8853. * ```
  8854. *
  8855. * @augments TempNode
  8856. */
  8857. class NormalMapNode extends TempNode {
  8858. static get type() {
  8859. return 'NormalMapNode';
  8860. }
  8861. /**
  8862. * Constructs a new normal map node.
  8863. *
  8864. * @param {Node<vec3>} node - Represents the normal map data.
  8865. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8866. */
  8867. constructor( node, scaleNode = null ) {
  8868. super( 'vec3' );
  8869. /**
  8870. * Represents the normal map data.
  8871. *
  8872. * @type {Node<vec3>}
  8873. */
  8874. this.node = node;
  8875. /**
  8876. * Controls the intensity of the effect.
  8877. *
  8878. * @type {?Node<vec2>}
  8879. * @default null
  8880. */
  8881. this.scaleNode = scaleNode;
  8882. /**
  8883. * The normal map type.
  8884. *
  8885. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8886. * @default TangentSpaceNormalMap
  8887. */
  8888. this.normalMapType = TangentSpaceNormalMap;
  8889. }
  8890. setup( builder ) {
  8891. const { normalMapType, scaleNode } = this;
  8892. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8893. if ( scaleNode !== null ) {
  8894. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8895. }
  8896. let outputNode = null;
  8897. if ( normalMapType === ObjectSpaceNormalMap ) {
  8898. outputNode = transformNormalToView( normalMap );
  8899. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8900. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8901. if ( tangent === true ) {
  8902. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8903. } else {
  8904. outputNode = perturbNormal2Arb( {
  8905. eye_pos: positionView,
  8906. surf_norm: normalView,
  8907. mapN: normalMap,
  8908. uv: uv()
  8909. } );
  8910. }
  8911. }
  8912. return outputNode;
  8913. }
  8914. }
  8915. /**
  8916. * TSL function for creating a normal map node.
  8917. *
  8918. * @tsl
  8919. * @function
  8920. * @param {Node<vec3>} node - Represents the normal map data.
  8921. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8922. * @returns {NormalMapNode}
  8923. */
  8924. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8925. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8926. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8927. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8928. // It's used to preserve the same TextureNode instance
  8929. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8930. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8931. return vec2(
  8932. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8933. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8934. ).mul( bumpScale );
  8935. } );
  8936. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8937. const perturbNormalArb = Fn( ( inputs ) => {
  8938. const { surf_pos, surf_norm, dHdxy } = inputs;
  8939. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8940. const vSigmaX = surf_pos.dFdx().normalize();
  8941. const vSigmaY = surf_pos.dFdy().normalize();
  8942. const vN = surf_norm; // normalized
  8943. const R1 = vSigmaY.cross( vN );
  8944. const R2 = vN.cross( vSigmaX );
  8945. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8946. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8947. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8948. } );
  8949. /**
  8950. * This class can be used for applying bump maps to materials.
  8951. *
  8952. * ```js
  8953. * material.normalNode = bumpMap( texture( bumpTex ) );
  8954. * ```
  8955. *
  8956. * @augments TempNode
  8957. */
  8958. class BumpMapNode extends TempNode {
  8959. static get type() {
  8960. return 'BumpMapNode';
  8961. }
  8962. /**
  8963. * Constructs a new bump map node.
  8964. *
  8965. * @param {Node<float>} textureNode - Represents the bump map data.
  8966. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  8967. */
  8968. constructor( textureNode, scaleNode = null ) {
  8969. super( 'vec3' );
  8970. /**
  8971. * Represents the bump map data.
  8972. *
  8973. * @type {Node<float>}
  8974. */
  8975. this.textureNode = textureNode;
  8976. /**
  8977. * Controls the intensity of the bump effect.
  8978. *
  8979. * @type {?Node<float>}
  8980. * @default null
  8981. */
  8982. this.scaleNode = scaleNode;
  8983. }
  8984. setup() {
  8985. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8986. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8987. return perturbNormalArb( {
  8988. surf_pos: positionView,
  8989. surf_norm: normalView,
  8990. dHdxy
  8991. } );
  8992. }
  8993. }
  8994. /**
  8995. * TSL function for creating a bump map node.
  8996. *
  8997. * @tsl
  8998. * @function
  8999. * @param {Node<float>} textureNode - Represents the bump map data.
  9000. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9001. * @returns {BumpMapNode}
  9002. */
  9003. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  9004. const _propertyCache = new Map();
  9005. /**
  9006. * This class should simplify the node access to material properties.
  9007. * It internal uses reference nodes to make sure changes to material
  9008. * properties are automatically reflected to predefined TSL objects
  9009. * like e.g. `materialColor`.
  9010. *
  9011. * @augments Node
  9012. */
  9013. class MaterialNode extends Node {
  9014. static get type() {
  9015. return 'MaterialNode';
  9016. }
  9017. /**
  9018. * Constructs a new material node.
  9019. *
  9020. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9021. */
  9022. constructor( scope ) {
  9023. super();
  9024. /**
  9025. * The scope defines what material property is referred by the node.
  9026. *
  9027. * @type {string}
  9028. */
  9029. this.scope = scope;
  9030. }
  9031. /**
  9032. * Returns a cached reference node for the given property and type.
  9033. *
  9034. * @param {string} property - The name of the material property.
  9035. * @param {string} type - The uniform type of the property.
  9036. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9037. */
  9038. getCache( property, type ) {
  9039. let node = _propertyCache.get( property );
  9040. if ( node === undefined ) {
  9041. node = materialReference( property, type );
  9042. _propertyCache.set( property, node );
  9043. }
  9044. return node;
  9045. }
  9046. /**
  9047. * Returns a float-typed material reference node for the given property name.
  9048. *
  9049. * @param {string} property - The name of the material property.
  9050. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9051. */
  9052. getFloat( property ) {
  9053. return this.getCache( property, 'float' );
  9054. }
  9055. /**
  9056. * Returns a color-typed material reference node for the given property name.
  9057. *
  9058. * @param {string} property - The name of the material property.
  9059. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9060. */
  9061. getColor( property ) {
  9062. return this.getCache( property, 'color' );
  9063. }
  9064. /**
  9065. * Returns a texture-typed material reference node for the given property name.
  9066. *
  9067. * @param {string} property - The name of the material property.
  9068. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9069. */
  9070. getTexture( property ) {
  9071. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9072. }
  9073. /**
  9074. * The node setup is done depending on the selected scope. Multiple material properties
  9075. * might be grouped into a single node composition if they logically belong together.
  9076. *
  9077. * @param {NodeBuilder} builder - The current node builder.
  9078. * @return {Node} The node representing the selected scope.
  9079. */
  9080. setup( builder ) {
  9081. const material = builder.context.material;
  9082. const scope = this.scope;
  9083. let node = null;
  9084. if ( scope === MaterialNode.COLOR ) {
  9085. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9086. if ( material.map && material.map.isTexture === true ) {
  9087. node = colorNode.mul( this.getTexture( 'map' ) );
  9088. } else {
  9089. node = colorNode;
  9090. }
  9091. } else if ( scope === MaterialNode.OPACITY ) {
  9092. const opacityNode = this.getFloat( scope );
  9093. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9094. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9095. } else {
  9096. node = opacityNode;
  9097. }
  9098. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9099. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9100. node = this.getTexture( 'specular' ).r;
  9101. } else {
  9102. node = float( 1 );
  9103. }
  9104. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9105. const specularIntensityNode = this.getFloat( scope );
  9106. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9107. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9108. } else {
  9109. node = specularIntensityNode;
  9110. }
  9111. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9112. const specularColorNode = this.getColor( scope );
  9113. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9114. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9115. } else {
  9116. node = specularColorNode;
  9117. }
  9118. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9119. const roughnessNode = this.getFloat( scope );
  9120. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9121. node = roughnessNode.mul( this.getTexture( scope ).g );
  9122. } else {
  9123. node = roughnessNode;
  9124. }
  9125. } else if ( scope === MaterialNode.METALNESS ) {
  9126. const metalnessNode = this.getFloat( scope );
  9127. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9128. node = metalnessNode.mul( this.getTexture( scope ).b );
  9129. } else {
  9130. node = metalnessNode;
  9131. }
  9132. } else if ( scope === MaterialNode.EMISSIVE ) {
  9133. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9134. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9135. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9136. node = emissiveNode.mul( this.getTexture( scope ) );
  9137. } else {
  9138. node = emissiveNode;
  9139. }
  9140. } else if ( scope === MaterialNode.NORMAL ) {
  9141. if ( material.normalMap ) {
  9142. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9143. node.normalMapType = material.normalMapType;
  9144. } else if ( material.bumpMap ) {
  9145. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9146. } else {
  9147. node = normalView;
  9148. }
  9149. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9150. const clearcoatNode = this.getFloat( scope );
  9151. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9152. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9153. } else {
  9154. node = clearcoatNode;
  9155. }
  9156. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9157. const clearcoatRoughnessNode = this.getFloat( scope );
  9158. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9159. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9160. } else {
  9161. node = clearcoatRoughnessNode;
  9162. }
  9163. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9164. if ( material.clearcoatNormalMap ) {
  9165. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9166. } else {
  9167. node = normalView;
  9168. }
  9169. } else if ( scope === MaterialNode.SHEEN ) {
  9170. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9171. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9172. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9173. } else {
  9174. node = sheenNode;
  9175. }
  9176. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9177. const sheenRoughnessNode = this.getFloat( scope );
  9178. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9179. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9180. } else {
  9181. node = sheenRoughnessNode;
  9182. }
  9183. node = node.clamp( 0.07, 1.0 );
  9184. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9185. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9186. const anisotropyPolar = this.getTexture( scope );
  9187. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9188. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9189. } else {
  9190. node = materialAnisotropyVector;
  9191. }
  9192. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9193. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9194. if ( material.iridescenceThicknessMap ) {
  9195. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9196. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9197. } else {
  9198. node = iridescenceThicknessMaximum;
  9199. }
  9200. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9201. const transmissionNode = this.getFloat( scope );
  9202. if ( material.transmissionMap ) {
  9203. node = transmissionNode.mul( this.getTexture( scope ).r );
  9204. } else {
  9205. node = transmissionNode;
  9206. }
  9207. } else if ( scope === MaterialNode.THICKNESS ) {
  9208. const thicknessNode = this.getFloat( scope );
  9209. if ( material.thicknessMap ) {
  9210. node = thicknessNode.mul( this.getTexture( scope ).g );
  9211. } else {
  9212. node = thicknessNode;
  9213. }
  9214. } else if ( scope === MaterialNode.IOR ) {
  9215. node = this.getFloat( scope );
  9216. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9217. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9218. } else if ( scope === MaterialNode.AO ) {
  9219. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9220. } else {
  9221. const outputType = this.getNodeType( builder );
  9222. node = this.getCache( scope, outputType );
  9223. }
  9224. return node;
  9225. }
  9226. }
  9227. MaterialNode.ALPHA_TEST = 'alphaTest';
  9228. MaterialNode.COLOR = 'color';
  9229. MaterialNode.OPACITY = 'opacity';
  9230. MaterialNode.SHININESS = 'shininess';
  9231. MaterialNode.SPECULAR = 'specular';
  9232. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9233. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9234. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9235. MaterialNode.REFLECTIVITY = 'reflectivity';
  9236. MaterialNode.ROUGHNESS = 'roughness';
  9237. MaterialNode.METALNESS = 'metalness';
  9238. MaterialNode.NORMAL = 'normal';
  9239. MaterialNode.CLEARCOAT = 'clearcoat';
  9240. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9241. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9242. MaterialNode.EMISSIVE = 'emissive';
  9243. MaterialNode.ROTATION = 'rotation';
  9244. MaterialNode.SHEEN = 'sheen';
  9245. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9246. MaterialNode.ANISOTROPY = 'anisotropy';
  9247. MaterialNode.IRIDESCENCE = 'iridescence';
  9248. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9249. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9250. MaterialNode.IOR = 'ior';
  9251. MaterialNode.TRANSMISSION = 'transmission';
  9252. MaterialNode.THICKNESS = 'thickness';
  9253. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9254. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9255. MaterialNode.LINE_SCALE = 'scale';
  9256. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9257. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9258. MaterialNode.LINE_WIDTH = 'linewidth';
  9259. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9260. MaterialNode.POINT_SIZE = 'size';
  9261. MaterialNode.DISPERSION = 'dispersion';
  9262. MaterialNode.LIGHT_MAP = 'light';
  9263. MaterialNode.AO = 'ao';
  9264. /**
  9265. * TSL object that represents alpha test of the current material.
  9266. *
  9267. * @tsl
  9268. * @type {Node<float>}
  9269. */
  9270. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9271. /**
  9272. * TSL object that represents the diffuse color of the current material.
  9273. * The value is composed via `color` * `map`.
  9274. *
  9275. * @tsl
  9276. * @type {Node<vec3>}
  9277. */
  9278. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9279. /**
  9280. * TSL object that represents the shininess of the current material.
  9281. *
  9282. * @tsl
  9283. * @type {Node<float>}
  9284. */
  9285. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9286. /**
  9287. * TSL object that represents the emissive color of the current material.
  9288. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9289. *
  9290. * @tsl
  9291. * @type {Node<vec3>}
  9292. */
  9293. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9294. /**
  9295. * TSL object that represents the opacity of the current material.
  9296. * The value is composed via `opacity` * `alphaMap`.
  9297. *
  9298. * @tsl
  9299. * @type {Node<float>}
  9300. */
  9301. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9302. /**
  9303. * TSL object that represents the specular of the current material.
  9304. *
  9305. * @tsl
  9306. * @type {Node<vec3>}
  9307. */
  9308. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9309. /**
  9310. * TSL object that represents the specular intensity of the current material.
  9311. * The value is composed via `specularIntensity` * `specularMap.a`.
  9312. *
  9313. * @tsl
  9314. * @type {Node<float>}
  9315. */
  9316. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9317. /**
  9318. * TSL object that represents the specular color of the current material.
  9319. * The value is composed via `specularColor` * `specularMap.rgb`.
  9320. *
  9321. * @tsl
  9322. * @type {Node<vec3>}
  9323. */
  9324. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9325. /**
  9326. * TSL object that represents the specular strength of the current material.
  9327. * The value is composed via `specularMap.r`.
  9328. *
  9329. * @tsl
  9330. * @type {Node<float>}
  9331. */
  9332. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9333. /**
  9334. * TSL object that represents the reflectivity of the current material.
  9335. *
  9336. * @tsl
  9337. * @type {Node<float>}
  9338. */
  9339. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9340. /**
  9341. * TSL object that represents the roughness of the current material.
  9342. * The value is composed via `roughness` * `roughnessMap.g`.
  9343. *
  9344. * @tsl
  9345. * @type {Node<float>}
  9346. */
  9347. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9348. /**
  9349. * TSL object that represents the metalness of the current material.
  9350. * The value is composed via `metalness` * `metalnessMap.b`.
  9351. *
  9352. * @tsl
  9353. * @type {Node<float>}
  9354. */
  9355. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9356. /**
  9357. * TSL object that represents the normal of the current material.
  9358. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9359. *
  9360. * @tsl
  9361. * @type {Node<vec3>}
  9362. */
  9363. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9364. /**
  9365. * TSL object that represents the clearcoat of the current material.
  9366. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9367. *
  9368. * @tsl
  9369. * @type {Node<float>}
  9370. */
  9371. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9372. /**
  9373. * TSL object that represents the clearcoat roughness of the current material.
  9374. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9375. *
  9376. * @tsl
  9377. * @type {Node<float>}
  9378. */
  9379. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9380. /**
  9381. * TSL object that represents the clearcoat normal of the current material.
  9382. * The value will be either `clearcoatNormalMap` or `normalView`.
  9383. *
  9384. * @tsl
  9385. * @type {Node<vec3>}
  9386. */
  9387. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9388. /**
  9389. * TSL object that represents the rotation of the current sprite material.
  9390. *
  9391. * @tsl
  9392. * @type {Node<float>}
  9393. */
  9394. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9395. /**
  9396. * TSL object that represents the sheen color of the current material.
  9397. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9398. *
  9399. * @tsl
  9400. * @type {Node<vec3>}
  9401. */
  9402. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9403. /**
  9404. * TSL object that represents the sheen roughness of the current material.
  9405. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9406. *
  9407. * @tsl
  9408. * @type {Node<float>}
  9409. */
  9410. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9411. /**
  9412. * TSL object that represents the anisotropy of the current material.
  9413. *
  9414. * @tsl
  9415. * @type {Node<vec2>}
  9416. */
  9417. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9418. /**
  9419. * TSL object that represents the iridescence of the current material.
  9420. *
  9421. * @tsl
  9422. * @type {Node<float>}
  9423. */
  9424. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9425. /**
  9426. * TSL object that represents the iridescence IOR of the current material.
  9427. *
  9428. * @tsl
  9429. * @type {Node<float>}
  9430. */
  9431. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9432. /**
  9433. * TSL object that represents the iridescence thickness of the current material.
  9434. *
  9435. * @tsl
  9436. * @type {Node<float>}
  9437. */
  9438. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9439. /**
  9440. * TSL object that represents the transmission of the current material.
  9441. * The value is composed via `transmission` * `transmissionMap.r`.
  9442. *
  9443. * @tsl
  9444. * @type {Node<float>}
  9445. */
  9446. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9447. /**
  9448. * TSL object that represents the thickness of the current material.
  9449. * The value is composed via `thickness` * `thicknessMap.g`.
  9450. *
  9451. * @tsl
  9452. * @type {Node<float>}
  9453. */
  9454. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9455. /**
  9456. * TSL object that represents the IOR of the current material.
  9457. *
  9458. * @tsl
  9459. * @type {Node<float>}
  9460. */
  9461. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9462. /**
  9463. * TSL object that represents the attenuation distance of the current material.
  9464. *
  9465. * @tsl
  9466. * @type {Node<float>}
  9467. */
  9468. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9469. /**
  9470. * TSL object that represents the attenuation color of the current material.
  9471. *
  9472. * @tsl
  9473. * @type {Node<vec3>}
  9474. */
  9475. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9476. /**
  9477. * TSL object that represents the scale of the current dashed line material.
  9478. *
  9479. * @tsl
  9480. * @type {Node<float>}
  9481. */
  9482. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9483. /**
  9484. * TSL object that represents the dash size of the current dashed line material.
  9485. *
  9486. * @tsl
  9487. * @type {Node<float>}
  9488. */
  9489. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9490. /**
  9491. * TSL object that represents the gap size of the current dashed line material.
  9492. *
  9493. * @tsl
  9494. * @type {Node<float>}
  9495. */
  9496. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9497. /**
  9498. * TSL object that represents the line width of the current line material.
  9499. *
  9500. * @tsl
  9501. * @type {Node<float>}
  9502. */
  9503. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9504. /**
  9505. * TSL object that represents the dash offset of the current line material.
  9506. *
  9507. * @tsl
  9508. * @type {Node<float>}
  9509. */
  9510. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9511. /**
  9512. * TSL object that represents the point size of the current points material.
  9513. *
  9514. * @tsl
  9515. * @type {Node<float>}
  9516. */
  9517. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9518. /**
  9519. * TSL object that represents the dispersion of the current material.
  9520. *
  9521. * @tsl
  9522. * @type {Node<float>}
  9523. */
  9524. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9525. /**
  9526. * TSL object that represents the light map of the current material.
  9527. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9528. *
  9529. * @tsl
  9530. * @type {Node<vec3>}
  9531. */
  9532. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9533. /**
  9534. * TSL object that represents the ambient occlusion map of the current material.
  9535. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9536. *
  9537. * @tsl
  9538. * @type {Node<float>}
  9539. */
  9540. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9541. /**
  9542. * TSL object that represents the anisotropy vector of the current material.
  9543. *
  9544. * @tsl
  9545. * @type {Node<vec2>}
  9546. */
  9547. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9548. return frame.material;
  9549. } ).onRenderUpdate( function ( { material } ) {
  9550. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9551. } );
  9552. /**
  9553. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9554. *
  9555. * @tsl
  9556. * @type {VaryingNode<vec4>}
  9557. */
  9558. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9559. return builder.context.setupModelViewProjection();
  9560. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9561. /**
  9562. * This class represents shader indices of different types. The following predefined node
  9563. * objects cover frequent use cases:
  9564. *
  9565. * - `vertexIndex`: The index of a vertex within a mesh.
  9566. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9567. * - `drawIndex`: The index of a draw call.
  9568. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9569. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9570. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9571. *
  9572. * @augments Node
  9573. */
  9574. class IndexNode extends Node {
  9575. static get type() {
  9576. return 'IndexNode';
  9577. }
  9578. /**
  9579. * Constructs a new index node.
  9580. *
  9581. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9582. */
  9583. constructor( scope ) {
  9584. super( 'uint' );
  9585. /**
  9586. * The scope of the index node.
  9587. *
  9588. * @type {string}
  9589. */
  9590. this.scope = scope;
  9591. /**
  9592. * This flag can be used for type testing.
  9593. *
  9594. * @type {boolean}
  9595. * @readonly
  9596. * @default true
  9597. */
  9598. this.isIndexNode = true;
  9599. }
  9600. generate( builder ) {
  9601. const nodeType = this.getNodeType( builder );
  9602. const scope = this.scope;
  9603. let propertyName;
  9604. if ( scope === IndexNode.VERTEX ) {
  9605. propertyName = builder.getVertexIndex();
  9606. } else if ( scope === IndexNode.INSTANCE ) {
  9607. propertyName = builder.getInstanceIndex();
  9608. } else if ( scope === IndexNode.DRAW ) {
  9609. propertyName = builder.getDrawIndex();
  9610. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9611. propertyName = builder.getInvocationLocalIndex();
  9612. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9613. propertyName = builder.getInvocationSubgroupIndex();
  9614. } else if ( scope === IndexNode.SUBGROUP ) {
  9615. propertyName = builder.getSubgroupIndex();
  9616. } else {
  9617. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9618. }
  9619. let output;
  9620. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9621. output = propertyName;
  9622. } else {
  9623. const nodeVarying = varying( this );
  9624. output = nodeVarying.build( builder, nodeType );
  9625. }
  9626. return output;
  9627. }
  9628. }
  9629. IndexNode.VERTEX = 'vertex';
  9630. IndexNode.INSTANCE = 'instance';
  9631. IndexNode.SUBGROUP = 'subgroup';
  9632. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9633. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9634. IndexNode.DRAW = 'draw';
  9635. /**
  9636. * TSL object that represents the index of a vertex within a mesh.
  9637. *
  9638. * @tsl
  9639. * @type {IndexNode}
  9640. */
  9641. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9642. /**
  9643. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9644. *
  9645. * @tsl
  9646. * @type {IndexNode}
  9647. */
  9648. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9649. /**
  9650. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9651. *
  9652. * @tsl
  9653. * @type {IndexNode}
  9654. */
  9655. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9656. /**
  9657. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9658. *
  9659. * @tsl
  9660. * @type {IndexNode}
  9661. */
  9662. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9663. /**
  9664. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9665. *
  9666. * @tsl
  9667. * @type {IndexNode}
  9668. */
  9669. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9670. /**
  9671. * TSL object that represents the index of a draw call.
  9672. *
  9673. * @tsl
  9674. * @type {IndexNode}
  9675. */
  9676. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9677. /**
  9678. * This node implements the vertex shader logic which is required
  9679. * when rendering 3D objects via instancing. The code makes sure
  9680. * vertex positions, normals and colors can be modified via instanced
  9681. * data.
  9682. *
  9683. * @augments Node
  9684. */
  9685. class InstanceNode extends Node {
  9686. static get type() {
  9687. return 'InstanceNode';
  9688. }
  9689. /**
  9690. * Constructs a new instance node.
  9691. *
  9692. * @param {number} count - The number of instances.
  9693. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9694. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9695. */
  9696. constructor( count, instanceMatrix, instanceColor ) {
  9697. super( 'void' );
  9698. /**
  9699. * The number of instances.
  9700. *
  9701. * @type {number}
  9702. */
  9703. this.count = count;
  9704. /**
  9705. * Instanced buffer attribute representing the transformation of instances.
  9706. *
  9707. * @type {InstancedBufferAttribute}
  9708. */
  9709. this.instanceMatrix = instanceMatrix;
  9710. /**
  9711. * Instanced buffer attribute representing the color of instances.
  9712. *
  9713. * @type {InstancedBufferAttribute}
  9714. */
  9715. this.instanceColor = instanceColor;
  9716. /**
  9717. * The node that represents the instance matrix data.
  9718. *
  9719. * @type {?Node}
  9720. */
  9721. this.instanceMatrixNode = null;
  9722. /**
  9723. * The node that represents the instance color data.
  9724. *
  9725. * @type {?Node}
  9726. */
  9727. this.instanceColorNode = null;
  9728. /**
  9729. * The update type is set to `frame` since an update
  9730. * of instanced buffer data must be checked per frame.
  9731. *
  9732. * @type {string}
  9733. * @default 'frame'
  9734. */
  9735. this.updateType = NodeUpdateType.FRAME;
  9736. /**
  9737. * A reference to a buffer that is used by `instanceMatrixNode`.
  9738. *
  9739. * @type {?InstancedInterleavedBuffer}
  9740. */
  9741. this.buffer = null;
  9742. /**
  9743. * A reference to a buffer that is used by `instanceColorNode`.
  9744. *
  9745. * @type {?InstancedBufferAttribute}
  9746. */
  9747. this.bufferColor = null;
  9748. }
  9749. /**
  9750. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9751. * to predefined node variables for accumulation. That follows the same patterns
  9752. * like with morph and skinning nodes.
  9753. *
  9754. * @param {NodeBuilder} builder - The current node builder.
  9755. */
  9756. setup( builder ) {
  9757. const { count, instanceMatrix, instanceColor } = this;
  9758. let { instanceMatrixNode, instanceColorNode } = this;
  9759. if ( instanceMatrixNode === null ) {
  9760. // 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.
  9761. if ( count <= 1000 ) {
  9762. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9763. } else {
  9764. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9765. this.buffer = buffer;
  9766. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9767. const instanceBuffers = [
  9768. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9769. bufferFn( buffer, 'vec4', 16, 0 ),
  9770. bufferFn( buffer, 'vec4', 16, 4 ),
  9771. bufferFn( buffer, 'vec4', 16, 8 ),
  9772. bufferFn( buffer, 'vec4', 16, 12 )
  9773. ];
  9774. instanceMatrixNode = mat4( ...instanceBuffers );
  9775. }
  9776. this.instanceMatrixNode = instanceMatrixNode;
  9777. }
  9778. if ( instanceColor && instanceColorNode === null ) {
  9779. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9780. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9781. this.bufferColor = buffer;
  9782. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9783. this.instanceColorNode = instanceColorNode;
  9784. }
  9785. // POSITION
  9786. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9787. positionLocal.assign( instancePosition );
  9788. // NORMAL
  9789. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9790. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9791. // ASSIGNS
  9792. normalLocal.assign( instanceNormal );
  9793. }
  9794. // COLOR
  9795. if ( this.instanceColorNode !== null ) {
  9796. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9797. }
  9798. }
  9799. /**
  9800. * Checks if the internal buffers required an update.
  9801. *
  9802. * @param {NodeFrame} frame - The current node frame.
  9803. */
  9804. update( /*frame*/ ) {
  9805. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9806. this.buffer.version = this.instanceMatrix.version;
  9807. }
  9808. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9809. this.bufferColor.version = this.instanceColor.version;
  9810. }
  9811. }
  9812. }
  9813. /**
  9814. * TSL function for creating an instance node.
  9815. *
  9816. * @tsl
  9817. * @function
  9818. * @param {number} count - The number of instances.
  9819. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9820. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9821. * @returns {InstanceNode}
  9822. */
  9823. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9824. /**
  9825. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9826. * It allows an easier setup of the instance node.
  9827. *
  9828. * @augments InstanceNode
  9829. */
  9830. class InstancedMeshNode extends InstanceNode {
  9831. static get type() {
  9832. return 'InstancedMeshNode';
  9833. }
  9834. /**
  9835. * Constructs a new instanced mesh node.
  9836. *
  9837. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9838. */
  9839. constructor( instancedMesh ) {
  9840. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9841. super( count, instanceMatrix, instanceColor );
  9842. /**
  9843. * A reference to the instanced mesh.
  9844. *
  9845. * @type {InstancedMesh}
  9846. */
  9847. this.instancedMesh = instancedMesh;
  9848. }
  9849. }
  9850. /**
  9851. * TSL function for creating an instanced mesh node.
  9852. *
  9853. * @tsl
  9854. * @function
  9855. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9856. * @returns {InstancedMeshNode}
  9857. */
  9858. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9859. /**
  9860. * This node implements the vertex shader logic which is required
  9861. * when rendering 3D objects via batching. `BatchNode` must be used
  9862. * with instances of {@link BatchedMesh}.
  9863. *
  9864. * @augments Node
  9865. */
  9866. class BatchNode extends Node {
  9867. static get type() {
  9868. return 'BatchNode';
  9869. }
  9870. /**
  9871. * Constructs a new batch node.
  9872. *
  9873. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9874. */
  9875. constructor( batchMesh ) {
  9876. super( 'void' );
  9877. /**
  9878. * A reference to batched mesh.
  9879. *
  9880. * @type {BatchedMesh}
  9881. */
  9882. this.batchMesh = batchMesh;
  9883. /**
  9884. * The batching index node.
  9885. *
  9886. * @type {?IndexNode}
  9887. * @default null
  9888. */
  9889. this.batchingIdNode = null;
  9890. }
  9891. /**
  9892. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9893. * to predefined node variables for accumulation. That follows the same patterns
  9894. * like with morph and skinning nodes.
  9895. *
  9896. * @param {NodeBuilder} builder - The current node builder.
  9897. */
  9898. setup( builder ) {
  9899. if ( this.batchingIdNode === null ) {
  9900. if ( builder.getDrawIndex() === null ) {
  9901. this.batchingIdNode = instanceIndex;
  9902. } else {
  9903. this.batchingIdNode = drawIndex;
  9904. }
  9905. }
  9906. const getIndirectIndex = Fn( ( [ id ] ) => {
  9907. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ) );
  9908. const x = int( id ).modInt( size );
  9909. const y = int( id ).div( size );
  9910. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9911. } ).setLayout( {
  9912. name: 'getIndirectIndex',
  9913. type: 'uint',
  9914. inputs: [
  9915. { name: 'id', type: 'int' }
  9916. ]
  9917. } );
  9918. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9919. const matricesTexture = this.batchMesh._matricesTexture;
  9920. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9921. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9922. const x = j.modInt( size );
  9923. const y = j.div( int( size ) );
  9924. const batchingMatrix = mat4(
  9925. textureLoad( matricesTexture, ivec2( x, y ) ),
  9926. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9927. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9928. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9929. );
  9930. const colorsTexture = this.batchMesh._colorsTexture;
  9931. if ( colorsTexture !== null ) {
  9932. const getBatchingColor = Fn( ( [ id ] ) => {
  9933. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9934. const j = id;
  9935. const x = j.modInt( size );
  9936. const y = j.div( size );
  9937. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9938. } ).setLayout( {
  9939. name: 'getBatchingColor',
  9940. type: 'vec3',
  9941. inputs: [
  9942. { name: 'id', type: 'int' }
  9943. ]
  9944. } );
  9945. const color = getBatchingColor( indirectId );
  9946. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9947. }
  9948. const bm = mat3( batchingMatrix );
  9949. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9950. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9951. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9952. normalLocal.assign( batchingNormal );
  9953. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9954. tangentLocal.mulAssign( bm );
  9955. }
  9956. }
  9957. }
  9958. /**
  9959. * TSL function for creating a batch node.
  9960. *
  9961. * @tsl
  9962. * @function
  9963. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9964. * @returns {BatchNode}
  9965. */
  9966. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9967. const _frameId = new WeakMap();
  9968. /**
  9969. * This node implements the vertex transformation shader logic which is required
  9970. * for skinning/skeletal animation.
  9971. *
  9972. * @augments Node
  9973. */
  9974. class SkinningNode extends Node {
  9975. static get type() {
  9976. return 'SkinningNode';
  9977. }
  9978. /**
  9979. * Constructs a new skinning node.
  9980. *
  9981. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9982. * @param {boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9983. */
  9984. constructor( skinnedMesh, useReference = false ) {
  9985. super( 'void' );
  9986. /**
  9987. * The skinned mesh.
  9988. *
  9989. * @type {SkinnedMesh}
  9990. */
  9991. this.skinnedMesh = skinnedMesh;
  9992. /**
  9993. * Whether to use reference nodes for internal skinned mesh related data or not.
  9994. * TODO: Explain the purpose of the property.
  9995. *
  9996. * @type {boolean}
  9997. */
  9998. this.useReference = useReference;
  9999. /**
  10000. * The update type overwritten since skinning nodes are updated per object.
  10001. *
  10002. * @type {string}
  10003. */
  10004. this.updateType = NodeUpdateType.OBJECT;
  10005. //
  10006. /**
  10007. * The skin index attribute.
  10008. *
  10009. * @type {AttributeNode}
  10010. */
  10011. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  10012. /**
  10013. * The skin weight attribute.
  10014. *
  10015. * @type {AttributeNode}
  10016. */
  10017. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  10018. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  10019. if ( useReference ) {
  10020. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  10021. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  10022. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10023. } else {
  10024. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  10025. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  10026. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  10027. }
  10028. /**
  10029. * The bind matrix node.
  10030. *
  10031. * @type {Node<mat4>}
  10032. */
  10033. this.bindMatrixNode = bindMatrixNode;
  10034. /**
  10035. * The bind matrix inverse node.
  10036. *
  10037. * @type {Node<mat4>}
  10038. */
  10039. this.bindMatrixInverseNode = bindMatrixInverseNode;
  10040. /**
  10041. * The bind matrices as a uniform buffer node.
  10042. *
  10043. * @type {Node}
  10044. */
  10045. this.boneMatricesNode = boneMatricesNode;
  10046. /**
  10047. * The previous bind matrices as a uniform buffer node.
  10048. * Required for computing motion vectors.
  10049. *
  10050. * @type {?Node}
  10051. * @default null
  10052. */
  10053. this.previousBoneMatricesNode = null;
  10054. }
  10055. /**
  10056. * Transforms the given vertex position via skinning.
  10057. *
  10058. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10059. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  10060. * @return {Node<vec3>} The transformed vertex position.
  10061. */
  10062. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  10063. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10064. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10065. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10066. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10067. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10068. // POSITION
  10069. const skinVertex = bindMatrixNode.mul( position );
  10070. const skinned = add(
  10071. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  10072. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  10073. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  10074. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  10075. );
  10076. return bindMatrixInverseNode.mul( skinned ).xyz;
  10077. }
  10078. /**
  10079. * Transforms the given vertex normal via skinning.
  10080. *
  10081. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10082. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  10083. * @return {Node<vec3>} The transformed vertex normal.
  10084. */
  10085. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  10086. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10087. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10088. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10089. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10090. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10091. // NORMAL
  10092. let skinMatrix = add(
  10093. skinWeightNode.x.mul( boneMatX ),
  10094. skinWeightNode.y.mul( boneMatY ),
  10095. skinWeightNode.z.mul( boneMatZ ),
  10096. skinWeightNode.w.mul( boneMatW )
  10097. );
  10098. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  10099. return skinMatrix.transformDirection( normal ).xyz;
  10100. }
  10101. /**
  10102. * Transforms the given vertex normal via skinning.
  10103. *
  10104. * @param {NodeBuilder} builder - The current node builder.
  10105. * @return {Node<vec3>} The skinned position from the previous frame.
  10106. */
  10107. getPreviousSkinnedPosition( builder ) {
  10108. const skinnedMesh = builder.object;
  10109. if ( this.previousBoneMatricesNode === null ) {
  10110. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  10111. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10112. }
  10113. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  10114. }
  10115. /**
  10116. * Returns `true` if bone matrices from the previous frame are required.
  10117. *
  10118. * @param {NodeBuilder} builder - The current node builder.
  10119. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  10120. */
  10121. needsPreviousBoneMatrices( builder ) {
  10122. const mrt = builder.renderer.getMRT();
  10123. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  10124. }
  10125. /**
  10126. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  10127. *
  10128. * @param {NodeBuilder} builder - The current node builder.
  10129. */
  10130. setup( builder ) {
  10131. if ( this.needsPreviousBoneMatrices( builder ) ) {
  10132. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  10133. }
  10134. const skinPosition = this.getSkinnedPosition();
  10135. positionLocal.assign( skinPosition );
  10136. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10137. const skinNormal = this.getSkinnedNormal();
  10138. normalLocal.assign( skinNormal );
  10139. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10140. tangentLocal.assign( skinNormal );
  10141. }
  10142. }
  10143. }
  10144. /**
  10145. * Generates the code snippet of the skinning node.
  10146. *
  10147. * @param {NodeBuilder} builder - The current node builder.
  10148. * @param {string} output - The current output.
  10149. * @return {string} The generated code snippet.
  10150. */
  10151. generate( builder, output ) {
  10152. if ( output !== 'void' ) {
  10153. return positionLocal.build( builder, output );
  10154. }
  10155. }
  10156. /**
  10157. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  10158. *
  10159. * @param {NodeFrame} frame - The current node frame.
  10160. */
  10161. update( frame ) {
  10162. const object = this.useReference ? frame.object : this.skinnedMesh;
  10163. const skeleton = object.skeleton;
  10164. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  10165. _frameId.set( skeleton, frame.frameId );
  10166. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  10167. skeleton.update();
  10168. }
  10169. }
  10170. /**
  10171. * TSL function for creating a skinning node.
  10172. *
  10173. * @tsl
  10174. * @function
  10175. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10176. * @returns {SkinningNode}
  10177. */
  10178. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  10179. /**
  10180. * TSL function for creating a skinning node with reference usage.
  10181. *
  10182. * @tsl
  10183. * @function
  10184. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10185. * @returns {SkinningNode}
  10186. */
  10187. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  10188. /**
  10189. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  10190. * ```js
  10191. * Loop( count, ( { i } ) => {
  10192. *
  10193. * } );
  10194. * ```
  10195. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  10196. * ```js
  10197. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  10198. *
  10199. * } );
  10200. *```
  10201. * Nested loops can be defined in a compacted form:
  10202. * ```js
  10203. * Loop( 10, 5, ( { i, j } ) => {
  10204. *
  10205. * } );
  10206. * ```
  10207. * Loops that should run backwards can be defined like so:
  10208. * ```js
  10209. * Loop( { start: 10 }, () => {} );
  10210. * ```
  10211. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  10212. * @augments Node
  10213. */
  10214. class LoopNode extends Node {
  10215. static get type() {
  10216. return 'LoopNode';
  10217. }
  10218. /**
  10219. * Constructs a new loop node.
  10220. *
  10221. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  10222. */
  10223. constructor( params = [] ) {
  10224. super();
  10225. this.params = params;
  10226. }
  10227. /**
  10228. * Returns a loop variable name based on an index. The pattern is
  10229. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  10230. *
  10231. * @param {number} index - The index.
  10232. * @return {string} The loop variable name.
  10233. */
  10234. getVarName( index ) {
  10235. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  10236. }
  10237. /**
  10238. * Returns properties about this node.
  10239. *
  10240. * @param {NodeBuilder} builder - The current node builder.
  10241. * @return {Object} The node properties.
  10242. */
  10243. getProperties( builder ) {
  10244. const properties = builder.getNodeProperties( this );
  10245. if ( properties.stackNode !== undefined ) return properties;
  10246. //
  10247. const inputs = {};
  10248. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10249. const param = this.params[ i ];
  10250. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  10251. const type = ( param.isNode !== true && param.type ) || 'int';
  10252. inputs[ name ] = expression( name, type );
  10253. }
  10254. const stack = builder.addStack(); // TODO: cache() it
  10255. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  10256. properties.stackNode = stack;
  10257. builder.removeStack();
  10258. return properties;
  10259. }
  10260. /**
  10261. * This method is overwritten since the node type is inferred based on the loop configuration.
  10262. *
  10263. * @param {NodeBuilder} builder - The current node builder.
  10264. * @return {string} The node type.
  10265. */
  10266. getNodeType( builder ) {
  10267. const { returnsNode } = this.getProperties( builder );
  10268. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  10269. }
  10270. setup( builder ) {
  10271. // setup properties
  10272. this.getProperties( builder );
  10273. }
  10274. generate( builder ) {
  10275. const properties = this.getProperties( builder );
  10276. const params = this.params;
  10277. const stackNode = properties.stackNode;
  10278. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  10279. const param = params[ i ];
  10280. let start = null, end = null, name = null, type = null, condition = null, update = null;
  10281. if ( param.isNode ) {
  10282. type = 'int';
  10283. name = this.getVarName( i );
  10284. start = '0';
  10285. end = param.build( builder, type );
  10286. condition = '<';
  10287. } else {
  10288. type = param.type || 'int';
  10289. name = param.name || this.getVarName( i );
  10290. start = param.start;
  10291. end = param.end;
  10292. condition = param.condition;
  10293. update = param.update;
  10294. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  10295. else if ( start && start.isNode ) start = start.build( builder, type );
  10296. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  10297. else if ( end && end.isNode ) end = end.build( builder, type );
  10298. if ( start !== undefined && end === undefined ) {
  10299. start = start + ' - 1';
  10300. end = '0';
  10301. condition = '>=';
  10302. } else if ( end !== undefined && start === undefined ) {
  10303. start = '0';
  10304. condition = '<';
  10305. }
  10306. if ( condition === undefined ) {
  10307. if ( Number( start ) > Number( end ) ) {
  10308. condition = '>=';
  10309. } else {
  10310. condition = '<';
  10311. }
  10312. }
  10313. }
  10314. const internalParam = { start, end, condition };
  10315. //
  10316. const startSnippet = internalParam.start;
  10317. const endSnippet = internalParam.end;
  10318. let declarationSnippet = '';
  10319. let conditionalSnippet = '';
  10320. let updateSnippet = '';
  10321. if ( ! update ) {
  10322. if ( type === 'int' || type === 'uint' ) {
  10323. if ( condition.includes( '<' ) ) update = '++';
  10324. else update = '--';
  10325. } else {
  10326. if ( condition.includes( '<' ) ) update = '+= 1.';
  10327. else update = '-= 1.';
  10328. }
  10329. }
  10330. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  10331. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  10332. updateSnippet += name + ' ' + update;
  10333. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  10334. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  10335. }
  10336. const stackSnippet = stackNode.build( builder, 'void' );
  10337. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  10338. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  10339. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10340. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  10341. }
  10342. builder.addFlowTab();
  10343. return returnsSnippet;
  10344. }
  10345. }
  10346. /**
  10347. * TSL function for creating a loop node.
  10348. *
  10349. * @tsl
  10350. * @function
  10351. * @param {...any} params - A list of parameters.
  10352. * @returns {LoopNode}
  10353. */
  10354. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  10355. /**
  10356. * TSL function for creating a `Continue()` expression.
  10357. *
  10358. * @tsl
  10359. * @function
  10360. * @returns {ExpressionNode}
  10361. */
  10362. const Continue = () => expression( 'continue' ).append();
  10363. /**
  10364. * TSL function for creating a `Break()` expression.
  10365. *
  10366. * @tsl
  10367. * @function
  10368. * @returns {ExpressionNode}
  10369. */
  10370. const Break = () => expression( 'break' ).append();
  10371. // Deprecated
  10372. /**
  10373. * @tsl
  10374. * @function
  10375. * @deprecated since r168. Use {@link Loop} instead.
  10376. *
  10377. * @param {...any} params
  10378. * @returns {LoopNode}
  10379. */
  10380. const loop = ( ...params ) => { // @deprecated, r168
  10381. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  10382. return Loop( ...params );
  10383. };
  10384. const _morphTextures = /*@__PURE__*/ new WeakMap();
  10385. const _morphVec4 = /*@__PURE__*/ new Vector4();
  10386. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  10387. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  10388. const y = texelIndex.div( width );
  10389. const x = texelIndex.sub( y.mul( width ) );
  10390. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  10391. return bufferAttrib.mul( influence );
  10392. } );
  10393. function getEntry( geometry ) {
  10394. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10395. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10396. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10397. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10398. // into an array of data textures. Each layer represents a single morph target.
  10399. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10400. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10401. let entry = _morphTextures.get( geometry );
  10402. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10403. if ( entry !== undefined ) entry.texture.dispose();
  10404. const morphTargets = geometry.morphAttributes.position || [];
  10405. const morphNormals = geometry.morphAttributes.normal || [];
  10406. const morphColors = geometry.morphAttributes.color || [];
  10407. let vertexDataCount = 0;
  10408. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10409. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10410. if ( hasMorphColors === true ) vertexDataCount = 3;
  10411. let width = geometry.attributes.position.count * vertexDataCount;
  10412. let height = 1;
  10413. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  10414. if ( width > maxTextureSize ) {
  10415. height = Math.ceil( width / maxTextureSize );
  10416. width = maxTextureSize;
  10417. }
  10418. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10419. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10420. bufferTexture.type = FloatType;
  10421. bufferTexture.needsUpdate = true;
  10422. // fill buffer
  10423. const vertexDataStride = vertexDataCount * 4;
  10424. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10425. const morphTarget = morphTargets[ i ];
  10426. const morphNormal = morphNormals[ i ];
  10427. const morphColor = morphColors[ i ];
  10428. const offset = width * height * 4 * i;
  10429. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10430. const stride = j * vertexDataStride;
  10431. if ( hasMorphPosition === true ) {
  10432. _morphVec4.fromBufferAttribute( morphTarget, j );
  10433. buffer[ offset + stride + 0 ] = _morphVec4.x;
  10434. buffer[ offset + stride + 1 ] = _morphVec4.y;
  10435. buffer[ offset + stride + 2 ] = _morphVec4.z;
  10436. buffer[ offset + stride + 3 ] = 0;
  10437. }
  10438. if ( hasMorphNormals === true ) {
  10439. _morphVec4.fromBufferAttribute( morphNormal, j );
  10440. buffer[ offset + stride + 4 ] = _morphVec4.x;
  10441. buffer[ offset + stride + 5 ] = _morphVec4.y;
  10442. buffer[ offset + stride + 6 ] = _morphVec4.z;
  10443. buffer[ offset + stride + 7 ] = 0;
  10444. }
  10445. if ( hasMorphColors === true ) {
  10446. _morphVec4.fromBufferAttribute( morphColor, j );
  10447. buffer[ offset + stride + 8 ] = _morphVec4.x;
  10448. buffer[ offset + stride + 9 ] = _morphVec4.y;
  10449. buffer[ offset + stride + 10 ] = _morphVec4.z;
  10450. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  10451. }
  10452. }
  10453. }
  10454. entry = {
  10455. count: morphTargetsCount,
  10456. texture: bufferTexture,
  10457. stride: vertexDataCount,
  10458. size: new Vector2( width, height )
  10459. };
  10460. _morphTextures.set( geometry, entry );
  10461. function disposeTexture() {
  10462. bufferTexture.dispose();
  10463. _morphTextures.delete( geometry );
  10464. geometry.removeEventListener( 'dispose', disposeTexture );
  10465. }
  10466. geometry.addEventListener( 'dispose', disposeTexture );
  10467. }
  10468. return entry;
  10469. }
  10470. /**
  10471. * This node implements the vertex transformation shader logic which is required
  10472. * for morph target animation.
  10473. *
  10474. * @augments Node
  10475. */
  10476. class MorphNode extends Node {
  10477. static get type() {
  10478. return 'MorphNode';
  10479. }
  10480. /**
  10481. * Constructs a new morph node.
  10482. *
  10483. * @param {Mesh} mesh - The mesh holding the morph targets.
  10484. */
  10485. constructor( mesh ) {
  10486. super( 'void' );
  10487. /**
  10488. * The mesh holding the morph targets.
  10489. *
  10490. * @type {Mesh}
  10491. */
  10492. this.mesh = mesh;
  10493. /**
  10494. * A uniform node which represents the morph base influence value.
  10495. *
  10496. * @type {UniformNode<float>}
  10497. */
  10498. this.morphBaseInfluence = uniform( 1 );
  10499. /**
  10500. * The update type overwritten since morph nodes are updated per object.
  10501. *
  10502. * @type {string}
  10503. */
  10504. this.updateType = NodeUpdateType.OBJECT;
  10505. }
  10506. /**
  10507. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  10508. *
  10509. * @param {NodeBuilder} builder - The current node builder.
  10510. */
  10511. setup( builder ) {
  10512. const { geometry } = builder;
  10513. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10514. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  10515. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10516. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10517. // nodes
  10518. const { texture: bufferMap, stride, size } = getEntry( geometry );
  10519. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  10520. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  10521. const width = int( size.width );
  10522. Loop( morphTargetsCount, ( { i } ) => {
  10523. const influence = float( 0 ).toVar();
  10524. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10525. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10526. } else {
  10527. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10528. }
  10529. If( influence.notEqual( 0 ), () => {
  10530. if ( hasMorphPosition === true ) {
  10531. positionLocal.addAssign( getMorph( {
  10532. bufferMap,
  10533. influence,
  10534. stride,
  10535. width,
  10536. depth: i,
  10537. offset: int( 0 )
  10538. } ) );
  10539. }
  10540. if ( hasMorphNormals === true ) {
  10541. normalLocal.addAssign( getMorph( {
  10542. bufferMap,
  10543. influence,
  10544. stride,
  10545. width,
  10546. depth: i,
  10547. offset: int( 1 )
  10548. } ) );
  10549. }
  10550. } );
  10551. } );
  10552. }
  10553. /**
  10554. * Updates the state of the morphed mesh by updating the base influence.
  10555. *
  10556. * @param {NodeFrame} frame - The current node frame.
  10557. */
  10558. update( /*frame*/ ) {
  10559. const morphBaseInfluence = this.morphBaseInfluence;
  10560. if ( this.mesh.geometry.morphTargetsRelative ) {
  10561. morphBaseInfluence.value = 1;
  10562. } else {
  10563. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10564. }
  10565. }
  10566. }
  10567. /**
  10568. * TSL function for creating a morph node.
  10569. *
  10570. * @tsl
  10571. * @function
  10572. * @param {Mesh} mesh - The mesh holding the morph targets.
  10573. * @returns {MorphNode}
  10574. */
  10575. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10576. /**
  10577. * Base class for lighting nodes.
  10578. *
  10579. * @augments Node
  10580. */
  10581. class LightingNode extends Node {
  10582. static get type() {
  10583. return 'LightingNode';
  10584. }
  10585. /**
  10586. * Constructs a new lighting node.
  10587. */
  10588. constructor() {
  10589. super( 'vec3' );
  10590. /**
  10591. * This flag can be used for type testing.
  10592. *
  10593. * @type {boolean}
  10594. * @readonly
  10595. * @default true
  10596. */
  10597. this.isLightingNode = true;
  10598. }
  10599. }
  10600. /**
  10601. * A generic class that can be used by nodes which contribute
  10602. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10603. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10604. *
  10605. * @augments LightingNode
  10606. */
  10607. class AONode extends LightingNode {
  10608. static get type() {
  10609. return 'AONode';
  10610. }
  10611. /**
  10612. * Constructs a new AO node.
  10613. *
  10614. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  10615. */
  10616. constructor( aoNode = null ) {
  10617. super();
  10618. /**
  10619. * The ambient occlusion node.
  10620. *
  10621. * @type {?Node<float>}
  10622. * @default null
  10623. */
  10624. this.aoNode = aoNode;
  10625. }
  10626. setup( builder ) {
  10627. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10628. }
  10629. }
  10630. /**
  10631. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  10632. * by adding lighting specific context data. It represents the runtime context of
  10633. * {@link LightsNode}.
  10634. *
  10635. * @augments ContextNode
  10636. */
  10637. class LightingContextNode extends ContextNode {
  10638. static get type() {
  10639. return 'LightingContextNode';
  10640. }
  10641. /**
  10642. * Constructs a new lighting context node.
  10643. *
  10644. * @param {LightsNode} lightsNode - The lights node.
  10645. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  10646. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  10647. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  10648. */
  10649. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10650. super( lightsNode );
  10651. /**
  10652. * The current lighting model.
  10653. *
  10654. * @type {?LightingModel}
  10655. * @default null
  10656. */
  10657. this.lightingModel = lightingModel;
  10658. /**
  10659. * A backdrop node.
  10660. *
  10661. * @type {?Node<vec3>}
  10662. * @default null
  10663. */
  10664. this.backdropNode = backdropNode;
  10665. /**
  10666. * A backdrop alpha node.
  10667. *
  10668. * @type {?Node<float>}
  10669. * @default null
  10670. */
  10671. this.backdropAlphaNode = backdropAlphaNode;
  10672. this._value = null;
  10673. }
  10674. /**
  10675. * Returns a lighting context object.
  10676. *
  10677. * @return {{
  10678. * radiance: Node<vec3>,
  10679. * irradiance: Node<vec3>,
  10680. * iblIrradiance: Node<vec3>,
  10681. * ambientOcclusion: Node<float>,
  10682. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10683. * backdrop: Node<vec3>,
  10684. * backdropAlpha: Node<float>
  10685. * }} The lighting context object.
  10686. */
  10687. getContext() {
  10688. const { backdropNode, backdropAlphaNode } = this;
  10689. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10690. directSpecular = vec3().toVar( 'directSpecular' ),
  10691. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10692. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10693. const reflectedLight = {
  10694. directDiffuse,
  10695. directSpecular,
  10696. indirectDiffuse,
  10697. indirectSpecular
  10698. };
  10699. const context = {
  10700. radiance: vec3().toVar( 'radiance' ),
  10701. irradiance: vec3().toVar( 'irradiance' ),
  10702. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10703. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10704. reflectedLight,
  10705. backdrop: backdropNode,
  10706. backdropAlpha: backdropAlphaNode
  10707. };
  10708. return context;
  10709. }
  10710. setup( builder ) {
  10711. this.value = this._value || ( this._value = this.getContext() );
  10712. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10713. return super.setup( builder );
  10714. }
  10715. }
  10716. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10717. /**
  10718. * A generic class that can be used by nodes which contribute
  10719. * irradiance to the scene. E.g. a light map node can be used
  10720. * as input for this module. Used in {@link NodeMaterial}.
  10721. *
  10722. * @augments LightingNode
  10723. */
  10724. class IrradianceNode extends LightingNode {
  10725. static get type() {
  10726. return 'IrradianceNode';
  10727. }
  10728. /**
  10729. * Constructs a new irradiance node.
  10730. *
  10731. * @param {Node<vec3>} node - A node contributing irradiance.
  10732. */
  10733. constructor( node ) {
  10734. super();
  10735. /**
  10736. * A node contributing irradiance.
  10737. *
  10738. * @type {Node<vec3>}
  10739. */
  10740. this.node = node;
  10741. }
  10742. setup( builder ) {
  10743. builder.context.irradiance.addAssign( this.node );
  10744. }
  10745. }
  10746. let screenSizeVec, viewportVec;
  10747. /**
  10748. * This node provides a collection of screen related metrics.
  10749. * Depending on {@link ScreenNode#scope}, the nodes can represent
  10750. * resolution or viewport data as well as fragment or uv coordinates.
  10751. *
  10752. * @augments Node
  10753. */
  10754. class ScreenNode extends Node {
  10755. static get type() {
  10756. return 'ScreenNode';
  10757. }
  10758. /**
  10759. * Constructs a new screen node.
  10760. *
  10761. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10762. */
  10763. constructor( scope ) {
  10764. super();
  10765. /**
  10766. * The node represents different metric depending on which scope is selected.
  10767. *
  10768. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10769. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10770. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10771. * - `ScreenNode.UV`: Normalized coordinates.
  10772. *
  10773. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10774. */
  10775. this.scope = scope;
  10776. /**
  10777. * This flag can be used for type testing.
  10778. *
  10779. * @type {boolean}
  10780. * @readonly
  10781. * @default true
  10782. */
  10783. this.isViewportNode = true;
  10784. }
  10785. /**
  10786. * This method is overwritten since the node type depends on the selected scope.
  10787. *
  10788. * @return {('vec2'|'vec4')} The node type.
  10789. */
  10790. getNodeType() {
  10791. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10792. else return 'vec2';
  10793. }
  10794. /**
  10795. * This method is overwritten since the node's update type depends on the selected scope.
  10796. *
  10797. * @return {NodeUpdateType} The update type.
  10798. */
  10799. getUpdateType() {
  10800. let updateType = NodeUpdateType.NONE;
  10801. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10802. updateType = NodeUpdateType.RENDER;
  10803. }
  10804. this.updateType = updateType;
  10805. return updateType;
  10806. }
  10807. /**
  10808. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10809. * from the current renderer.
  10810. *
  10811. * @param {NodeFrame} frame - A reference to the current node frame.
  10812. */
  10813. update( { renderer } ) {
  10814. const renderTarget = renderer.getRenderTarget();
  10815. if ( this.scope === ScreenNode.VIEWPORT ) {
  10816. if ( renderTarget !== null ) {
  10817. viewportVec.copy( renderTarget.viewport );
  10818. } else {
  10819. renderer.getViewport( viewportVec );
  10820. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10821. }
  10822. } else {
  10823. if ( renderTarget !== null ) {
  10824. screenSizeVec.width = renderTarget.width;
  10825. screenSizeVec.height = renderTarget.height;
  10826. } else {
  10827. renderer.getDrawingBufferSize( screenSizeVec );
  10828. }
  10829. }
  10830. }
  10831. setup( /*builder*/ ) {
  10832. const scope = this.scope;
  10833. let output = null;
  10834. if ( scope === ScreenNode.SIZE ) {
  10835. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10836. } else if ( scope === ScreenNode.VIEWPORT ) {
  10837. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10838. } else {
  10839. output = vec2( screenCoordinate.div( screenSize ) );
  10840. }
  10841. return output;
  10842. }
  10843. generate( builder ) {
  10844. if ( this.scope === ScreenNode.COORDINATE ) {
  10845. let coord = builder.getFragCoord();
  10846. if ( builder.isFlipY() ) {
  10847. // follow webgpu standards
  10848. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10849. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10850. }
  10851. return coord;
  10852. }
  10853. return super.generate( builder );
  10854. }
  10855. }
  10856. ScreenNode.COORDINATE = 'coordinate';
  10857. ScreenNode.VIEWPORT = 'viewport';
  10858. ScreenNode.SIZE = 'size';
  10859. ScreenNode.UV = 'uv';
  10860. // Screen
  10861. /**
  10862. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10863. *
  10864. * @tsl
  10865. * @type {ScreenNode<vec2>}
  10866. */
  10867. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10868. /**
  10869. * TSL object that represents the screen resolution in physical pixel units.
  10870. *
  10871. * @tsl
  10872. * @type {ScreenNode<vec2>}
  10873. */
  10874. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10875. /**
  10876. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10877. *
  10878. * @tsl
  10879. * @type {ScreenNode<vec2>}
  10880. */
  10881. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10882. // Viewport
  10883. /**
  10884. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10885. *
  10886. * @tsl
  10887. * @type {ScreenNode<vec4>}
  10888. */
  10889. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10890. /**
  10891. * TSL object that represents the viewport resolution in physical pixel units.
  10892. *
  10893. * @tsl
  10894. * @type {ScreenNode<vec2>}
  10895. */
  10896. const viewportSize = viewport.zw;
  10897. /**
  10898. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10899. *
  10900. * @tsl
  10901. * @type {ScreenNode<vec2>}
  10902. */
  10903. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10904. /**
  10905. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10906. *
  10907. * @tsl
  10908. * @type {ScreenNode<vec2>}
  10909. */
  10910. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10911. // Deprecated
  10912. /**
  10913. * @deprecated since r169. Use {@link screenSize} instead.
  10914. */
  10915. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10916. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10917. return screenSize;
  10918. }, 'vec2' ).once() )();
  10919. /**
  10920. * @tsl
  10921. * @deprecated since r168. Use {@link screenUV} instead.
  10922. * @type {Node<vec2>}
  10923. */
  10924. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10925. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10926. return screenUV;
  10927. }, 'vec2' ).once() )();
  10928. /**
  10929. * @tsl
  10930. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10931. * @type {Node<vec2>}
  10932. */
  10933. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10934. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10935. return screenUV.flipY();
  10936. }, 'vec2' ).once() )();
  10937. const _size$4 = /*@__PURE__*/ new Vector2();
  10938. /**
  10939. * A special type of texture node which represents the data of the current viewport
  10940. * as a texture. The module extracts data from the current bound framebuffer with
  10941. * a copy operation so no extra render pass is required to produce the texture data
  10942. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10943. * variety of effects like refractive or transmissive materials.
  10944. *
  10945. * @augments TextureNode
  10946. */
  10947. class ViewportTextureNode extends TextureNode {
  10948. static get type() {
  10949. return 'ViewportTextureNode';
  10950. }
  10951. /**
  10952. * Constructs a new viewport texture node.
  10953. *
  10954. * @param {Node} [uvNode=screenUV] - The uv node.
  10955. * @param {?Node} [levelNode=null] - The level node.
  10956. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10957. */
  10958. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10959. if ( framebufferTexture === null ) {
  10960. framebufferTexture = new FramebufferTexture();
  10961. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10962. }
  10963. super( framebufferTexture, uvNode, levelNode );
  10964. /**
  10965. * Whether to generate mipmaps or not.
  10966. *
  10967. * @type {boolean}
  10968. * @default false
  10969. */
  10970. this.generateMipmaps = false;
  10971. /**
  10972. * This flag can be used for type testing.
  10973. *
  10974. * @type {boolean}
  10975. * @readonly
  10976. * @default true
  10977. */
  10978. this.isOutputTextureNode = true;
  10979. /**
  10980. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10981. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10982. *
  10983. * @type {string}
  10984. * @default 'frame'
  10985. */
  10986. this.updateBeforeType = NodeUpdateType.FRAME;
  10987. }
  10988. updateBefore( frame ) {
  10989. const renderer = frame.renderer;
  10990. renderer.getDrawingBufferSize( _size$4 );
  10991. //
  10992. const framebufferTexture = this.value;
  10993. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10994. framebufferTexture.image.width = _size$4.width;
  10995. framebufferTexture.image.height = _size$4.height;
  10996. framebufferTexture.needsUpdate = true;
  10997. }
  10998. //
  10999. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  11000. framebufferTexture.generateMipmaps = this.generateMipmaps;
  11001. renderer.copyFramebufferToTexture( framebufferTexture );
  11002. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  11003. }
  11004. clone() {
  11005. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  11006. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  11007. return viewportTextureNode;
  11008. }
  11009. }
  11010. /**
  11011. * TSL function for creating a viewport texture node.
  11012. *
  11013. * @tsl
  11014. * @function
  11015. * @param {Node} [uvNode=screenUV] - The uv node.
  11016. * @param {?Node} [levelNode=null] - The level node.
  11017. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11018. * @returns {ViewportTextureNode}
  11019. */
  11020. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  11021. /**
  11022. * TSL function for creating a viewport texture node with enabled mipmap generation.
  11023. *
  11024. * @tsl
  11025. * @function
  11026. * @param {Node} [uvNode=screenUV] - The uv node.
  11027. * @param {?Node} [levelNode=null] - The level node.
  11028. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11029. * @returns {ViewportTextureNode}
  11030. */
  11031. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  11032. let sharedDepthbuffer = null;
  11033. /**
  11034. * Represents the depth of the current viewport as a texture. This module
  11035. * can be used in combination with viewport texture to achieve effects
  11036. * that require depth evaluation.
  11037. *
  11038. * @augments ViewportTextureNode
  11039. */
  11040. class ViewportDepthTextureNode extends ViewportTextureNode {
  11041. static get type() {
  11042. return 'ViewportDepthTextureNode';
  11043. }
  11044. /**
  11045. * Constructs a new viewport depth texture node.
  11046. *
  11047. * @param {Node} [uvNode=screenUV] - The uv node.
  11048. * @param {?Node} [levelNode=null] - The level node.
  11049. */
  11050. constructor( uvNode = screenUV, levelNode = null ) {
  11051. if ( sharedDepthbuffer === null ) {
  11052. sharedDepthbuffer = new DepthTexture();
  11053. }
  11054. super( uvNode, levelNode, sharedDepthbuffer );
  11055. }
  11056. }
  11057. /**
  11058. * TSL function for a viewport depth texture node.
  11059. *
  11060. * @tsl
  11061. * @function
  11062. * @param {Node} [uvNode=screenUV] - The uv node.
  11063. * @param {?Node} [levelNode=null] - The level node.
  11064. * @returns {ViewportDepthTextureNode}
  11065. */
  11066. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  11067. /**
  11068. * This node offers a collection of features in context of the depth logic in the fragment shader.
  11069. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  11070. * fragment or for depth evaluation purposes.
  11071. *
  11072. * @augments Node
  11073. */
  11074. class ViewportDepthNode extends Node {
  11075. static get type() {
  11076. return 'ViewportDepthNode';
  11077. }
  11078. /**
  11079. * Constructs a new viewport depth node.
  11080. *
  11081. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  11082. * @param {?Node} [valueNode=null] - The value node.
  11083. */
  11084. constructor( scope, valueNode = null ) {
  11085. super( 'float' );
  11086. /**
  11087. * The node behaves differently depending on which scope is selected.
  11088. *
  11089. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  11090. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  11091. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  11092. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  11093. *
  11094. * @type {('depth'|'depthBase'|'linearDepth')}
  11095. */
  11096. this.scope = scope;
  11097. /**
  11098. * Can be used to define a custom depth value.
  11099. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  11100. *
  11101. * @type {?Node}
  11102. * @default null
  11103. */
  11104. this.valueNode = valueNode;
  11105. /**
  11106. * This flag can be used for type testing.
  11107. *
  11108. * @type {boolean}
  11109. * @readonly
  11110. * @default true
  11111. */
  11112. this.isViewportDepthNode = true;
  11113. }
  11114. generate( builder ) {
  11115. const { scope } = this;
  11116. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11117. return builder.getFragDepth();
  11118. }
  11119. return super.generate( builder );
  11120. }
  11121. setup( { camera } ) {
  11122. const { scope } = this;
  11123. const value = this.valueNode;
  11124. let node = null;
  11125. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11126. if ( value !== null ) {
  11127. node = depthBase().assign( value );
  11128. }
  11129. } else if ( scope === ViewportDepthNode.DEPTH ) {
  11130. if ( camera.isPerspectiveCamera ) {
  11131. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  11132. } else {
  11133. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11134. }
  11135. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  11136. if ( value !== null ) {
  11137. if ( camera.isPerspectiveCamera ) {
  11138. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  11139. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  11140. } else {
  11141. node = value;
  11142. }
  11143. } else {
  11144. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11145. }
  11146. }
  11147. return node;
  11148. }
  11149. }
  11150. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  11151. ViewportDepthNode.DEPTH = 'depth';
  11152. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  11153. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  11154. /**
  11155. * TSL function for converting a viewZ value to an orthographic depth value.
  11156. *
  11157. * @tsl
  11158. * @function
  11159. * @param {Node<float>} viewZ - The viewZ node.
  11160. * @param {Node<float>} near - The camera's near value.
  11161. * @param {Node<float>} far - The camera's far value.
  11162. * @returns {Node<float>}
  11163. */
  11164. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  11165. /**
  11166. * TSL function for converting an orthographic depth value to a viewZ value.
  11167. *
  11168. * @tsl
  11169. * @function
  11170. * @param {Node<float>} depth - The orthographic depth.
  11171. * @param {Node<float>} near - The camera's near value.
  11172. * @param {Node<float>} far - The camera's far value.
  11173. * @returns {Node<float>}
  11174. */
  11175. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  11176. /**
  11177. * TSL function for converting a viewZ value to a perspective depth value.
  11178. *
  11179. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  11180. *
  11181. * @tsl
  11182. * @function
  11183. * @param {Node<float>} viewZ - The viewZ node.
  11184. * @param {Node<float>} near - The camera's near value.
  11185. * @param {Node<float>} far - The camera's far value.
  11186. * @returns {Node<float>}
  11187. */
  11188. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  11189. /**
  11190. * TSL function for converting a perspective depth value to a viewZ value.
  11191. *
  11192. * @tsl
  11193. * @function
  11194. * @param {Node<float>} depth - The perspective depth.
  11195. * @param {Node<float>} near - The camera's near value.
  11196. * @param {Node<float>} far - The camera's far value.
  11197. * @returns {Node<float>}
  11198. */
  11199. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  11200. /**
  11201. * TSL function for converting a viewZ value to a logarithmic depth value.
  11202. *
  11203. * @tsl
  11204. * @function
  11205. * @param {Node<float>} viewZ - The viewZ node.
  11206. * @param {Node<float>} near - The camera's near value.
  11207. * @param {Node<float>} far - The camera's far value.
  11208. * @returns {Node<float>}
  11209. */
  11210. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  11211. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  11212. // The final logarithmic depth formula used here is adapted from one described in an
  11213. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  11214. // which was an improvement upon an earlier formula one described in an
  11215. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  11216. // Ulrich's formula is the following:
  11217. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  11218. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  11219. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  11220. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  11221. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  11222. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  11223. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  11224. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  11225. // be used, and ultimately Ulrich's "near plane" version was chosen.
  11226. // Outerra eventually made another improvement to their original "C-constant" variant,
  11227. // but it still does not incorporate the camera near plane (for this version,
  11228. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  11229. // Here we make 4 changes to Ulrich's formula:
  11230. // 1. Clamp the camera near plane so we don't divide by 0.
  11231. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  11232. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  11233. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  11234. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  11235. // so we do the same here, hence the 'viewZ.negate()' call.
  11236. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  11237. near = near.max( 1e-6 ).toVar();
  11238. const numerator = log2( viewZ.negate().div( near ) );
  11239. const denominator = log2( far.div( near ) );
  11240. return numerator.div( denominator );
  11241. };
  11242. /**
  11243. * TSL function for converting a logarithmic depth value to a viewZ value.
  11244. *
  11245. * @tsl
  11246. * @function
  11247. * @param {Node<float>} depth - The logarithmic depth.
  11248. * @param {Node<float>} near - The camera's near value.
  11249. * @param {Node<float>} far - The camera's far value.
  11250. * @returns {Node<float>}
  11251. */
  11252. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  11253. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  11254. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  11255. // a negative viewZ).
  11256. const exponent = depth.mul( log( far.div( near ) ) );
  11257. return float( Math.E ).pow( exponent ).mul( near ).negate();
  11258. };
  11259. /**
  11260. * TSL function for defining a value for the current fragment's depth.
  11261. *
  11262. * @tsl
  11263. * @function
  11264. * @param {Node<float>} value - The depth value to set.
  11265. * @returns {ViewportDepthNode<float>}
  11266. */
  11267. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  11268. /**
  11269. * TSL object that represents the depth value for the current fragment.
  11270. *
  11271. * @tsl
  11272. * @type {ViewportDepthNode}
  11273. */
  11274. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  11275. /**
  11276. * TSL function for converting a perspective depth value to linear depth.
  11277. *
  11278. * @tsl
  11279. * @function
  11280. * @param {Node<float>} value - The perspective depth.
  11281. * @returns {ViewportDepthNode<float>}
  11282. */
  11283. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  11284. /**
  11285. * TSL object that represents the linear (orthographic) depth value of the current fragment
  11286. *
  11287. * @tsl
  11288. * @type {ViewportDepthNode}
  11289. */
  11290. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  11291. depth.assign = ( value ) => depthBase( value );
  11292. /**
  11293. * The node allows to set values for built-in shader variables. That is
  11294. * required for features like hardware-accelerated vertex clipping.
  11295. *
  11296. * @augments Node
  11297. */
  11298. class BuiltinNode extends Node {
  11299. /**
  11300. * Constructs a new builtin node.
  11301. *
  11302. * @param {string} name - The name of the built-in shader variable.
  11303. */
  11304. constructor( name ) {
  11305. super( 'float' );
  11306. /**
  11307. * The name of the built-in shader variable.
  11308. *
  11309. * @type {string}
  11310. */
  11311. this.name = name;
  11312. /**
  11313. * This flag can be used for type testing.
  11314. *
  11315. * @type {boolean}
  11316. * @readonly
  11317. * @default true
  11318. */
  11319. this.isBuiltinNode = true;
  11320. }
  11321. /**
  11322. * Generates the code snippet of the builtin node.
  11323. *
  11324. * @param {NodeBuilder} builder - The current node builder.
  11325. * @return {string} The generated code snippet.
  11326. */
  11327. generate( /* builder */ ) {
  11328. return this.name;
  11329. }
  11330. }
  11331. /**
  11332. * TSL function for creating a builtin node.
  11333. *
  11334. * @tsl
  11335. * @function
  11336. * @param {string} name - The name of the built-in shader variable.
  11337. * @returns {BuiltinNode}
  11338. */
  11339. const builtin = nodeProxy( BuiltinNode );
  11340. /**
  11341. * This node is used in {@link NodeMaterial} to setup the clipping
  11342. * which can happen hardware-accelerated (if supported) and optionally
  11343. * use alpha-to-coverage for anti-aliasing clipped edges.
  11344. *
  11345. * @augments Node
  11346. */
  11347. class ClippingNode extends Node {
  11348. static get type() {
  11349. return 'ClippingNode';
  11350. }
  11351. /**
  11352. * Constructs a new clipping node.
  11353. *
  11354. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  11355. * the selected scope influences the behavior of the node and what type of code is generated.
  11356. */
  11357. constructor( scope = ClippingNode.DEFAULT ) {
  11358. super();
  11359. /**
  11360. * The node's scope. Similar to other nodes, the selected scope influences
  11361. * the behavior of the node and what type of code is generated.
  11362. *
  11363. * @type {('default'|'hardware'|'alphaToCoverage')}
  11364. */
  11365. this.scope = scope;
  11366. }
  11367. /**
  11368. * Setups the node depending on the selected scope.
  11369. *
  11370. * @param {NodeBuilder} builder - The current node builder.
  11371. * @return {Node} The result node.
  11372. */
  11373. setup( builder ) {
  11374. super.setup( builder );
  11375. const clippingContext = builder.clippingContext;
  11376. const { intersectionPlanes, unionPlanes } = clippingContext;
  11377. this.hardwareClipping = builder.material.hardwareClipping;
  11378. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  11379. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  11380. } else if ( this.scope === ClippingNode.HARDWARE ) {
  11381. return this.setupHardwareClipping( unionPlanes, builder );
  11382. } else {
  11383. return this.setupDefault( intersectionPlanes, unionPlanes );
  11384. }
  11385. }
  11386. /**
  11387. * Setups alpha to coverage.
  11388. *
  11389. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11390. * @param {Array<Vector4>} unionPlanes - The union planes.
  11391. * @return {Node} The result node.
  11392. */
  11393. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  11394. return Fn( () => {
  11395. const distanceToPlane = float().toVar( 'distanceToPlane' );
  11396. const distanceGradient = float().toVar( 'distanceToGradient' );
  11397. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  11398. const numUnionPlanes = unionPlanes.length;
  11399. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11400. const clippingPlanes = uniformArray( unionPlanes );
  11401. Loop( numUnionPlanes, ( { i } ) => {
  11402. const plane = clippingPlanes.element( i );
  11403. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11404. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11405. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  11406. } );
  11407. }
  11408. const numIntersectionPlanes = intersectionPlanes.length;
  11409. if ( numIntersectionPlanes > 0 ) {
  11410. const clippingPlanes = uniformArray( intersectionPlanes );
  11411. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  11412. Loop( numIntersectionPlanes, ( { i } ) => {
  11413. const plane = clippingPlanes.element( i );
  11414. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11415. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11416. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  11417. } );
  11418. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  11419. }
  11420. diffuseColor.a.mulAssign( clipOpacity );
  11421. diffuseColor.a.equal( 0.0 ).discard();
  11422. } )();
  11423. }
  11424. /**
  11425. * Setups the default clipping.
  11426. *
  11427. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11428. * @param {Array<Vector4>} unionPlanes - The union planes.
  11429. * @return {Node} The result node.
  11430. */
  11431. setupDefault( intersectionPlanes, unionPlanes ) {
  11432. return Fn( () => {
  11433. const numUnionPlanes = unionPlanes.length;
  11434. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11435. const clippingPlanes = uniformArray( unionPlanes );
  11436. Loop( numUnionPlanes, ( { i } ) => {
  11437. const plane = clippingPlanes.element( i );
  11438. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  11439. } );
  11440. }
  11441. const numIntersectionPlanes = intersectionPlanes.length;
  11442. if ( numIntersectionPlanes > 0 ) {
  11443. const clippingPlanes = uniformArray( intersectionPlanes );
  11444. const clipped = bool( true ).toVar( 'clipped' );
  11445. Loop( numIntersectionPlanes, ( { i } ) => {
  11446. const plane = clippingPlanes.element( i );
  11447. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  11448. } );
  11449. clipped.discard();
  11450. }
  11451. } )();
  11452. }
  11453. /**
  11454. * Setups hardware clipping.
  11455. *
  11456. * @param {Array<Vector4>} unionPlanes - The union planes.
  11457. * @param {NodeBuilder} builder - The current node builder.
  11458. * @return {Node} The result node.
  11459. */
  11460. setupHardwareClipping( unionPlanes, builder ) {
  11461. const numUnionPlanes = unionPlanes.length;
  11462. builder.enableHardwareClipping( numUnionPlanes );
  11463. return Fn( () => {
  11464. const clippingPlanes = uniformArray( unionPlanes );
  11465. const hw_clip_distances = builtin( builder.getClipDistance() );
  11466. Loop( numUnionPlanes, ( { i } ) => {
  11467. const plane = clippingPlanes.element( i );
  11468. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  11469. hw_clip_distances.element( i ).assign( distance );
  11470. } );
  11471. } )();
  11472. }
  11473. }
  11474. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  11475. ClippingNode.DEFAULT = 'default';
  11476. ClippingNode.HARDWARE = 'hardware';
  11477. /**
  11478. * TSL function for setting up the default clipping logic.
  11479. *
  11480. * @tsl
  11481. * @function
  11482. * @returns {ClippingNode}
  11483. */
  11484. const clipping = () => nodeObject( new ClippingNode() );
  11485. /**
  11486. * TSL function for setting up alpha to coverage.
  11487. *
  11488. * @tsl
  11489. * @function
  11490. * @returns {ClippingNode}
  11491. */
  11492. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  11493. /**
  11494. * TSL function for setting up hardware-based clipping.
  11495. *
  11496. * @tsl
  11497. * @function
  11498. * @returns {ClippingNode}
  11499. */
  11500. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  11501. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  11502. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  11503. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11504. 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 ) ) ) ) ) );
  11505. } );
  11506. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11507. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  11508. } );
  11509. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  11510. // Find the discretized derivatives of our coordinates
  11511. const maxDeriv = max$1(
  11512. length( dFdx( position.xyz ) ),
  11513. length( dFdy( position.xyz ) )
  11514. );
  11515. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  11516. // Find two nearest log-discretized noise scales
  11517. const pixScales = vec2(
  11518. exp2( floor( log2( pixScale ) ) ),
  11519. exp2( ceil( log2( pixScale ) ) )
  11520. );
  11521. // Compute alpha thresholds at our two noise scales
  11522. const alpha = vec2(
  11523. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  11524. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  11525. );
  11526. // Factor to interpolate lerp with
  11527. const lerpFactor = fract( log2( pixScale ) );
  11528. // Interpolate alpha threshold from noise at two scales
  11529. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  11530. // Pass into CDF to compute uniformly distrib threshold
  11531. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  11532. const cases = vec3(
  11533. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  11534. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  11535. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  11536. // Find our final, uniformly distributed alpha threshold (ατ)
  11537. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  11538. // Avoids ατ == 0. Could also do ατ =1-ατ
  11539. return clamp( threshold, 1.0e-6, 1.0 );
  11540. } ).setLayout( {
  11541. name: 'getAlphaHashThreshold',
  11542. type: 'float',
  11543. inputs: [
  11544. { name: 'position', type: 'vec3' }
  11545. ]
  11546. } );
  11547. /**
  11548. * Base class for all node materials.
  11549. *
  11550. * @augments Material
  11551. */
  11552. class NodeMaterial extends Material {
  11553. static get type() {
  11554. return 'NodeMaterial';
  11555. }
  11556. /**
  11557. * Represents the type of the node material.
  11558. *
  11559. * @type {string}
  11560. */
  11561. get type() {
  11562. return this.constructor.type;
  11563. }
  11564. set type( _value ) { /* */ }
  11565. /**
  11566. * Constructs a new node material.
  11567. */
  11568. constructor() {
  11569. super();
  11570. /**
  11571. * This flag can be used for type testing.
  11572. *
  11573. * @type {boolean}
  11574. * @readonly
  11575. * @default true
  11576. */
  11577. this.isNodeMaterial = true;
  11578. /**
  11579. * Whether this material is affected by fog or not.
  11580. *
  11581. * @type {boolean}
  11582. * @default true
  11583. */
  11584. this.fog = true;
  11585. /**
  11586. * Whether this material is affected by lights or not.
  11587. *
  11588. * @type {boolean}
  11589. * @default false
  11590. */
  11591. this.lights = false;
  11592. /**
  11593. * Whether this material uses hardware clipping or not.
  11594. * This property is managed by the engine and should not be
  11595. * modified by apps.
  11596. *
  11597. * @type {boolean}
  11598. * @default false
  11599. */
  11600. this.hardwareClipping = false;
  11601. /**
  11602. * Node materials which set their `lights` property to `true`
  11603. * are affected by all lights of the scene. Sometimes selective
  11604. * lighting is wanted which means only _some_ lights in the scene
  11605. * affect a material. This can be achieved by creating an instance
  11606. * of {@link LightsNode} with a list of selective
  11607. * lights and assign the node to this property.
  11608. *
  11609. * ```js
  11610. * const customLightsNode = lights( [ light1, light2 ] );
  11611. * material.lightsNode = customLightsNode;
  11612. * ```
  11613. *
  11614. * @type {?LightsNode}
  11615. * @default null
  11616. */
  11617. this.lightsNode = null;
  11618. /**
  11619. * The environment of node materials can be defined by an environment
  11620. * map assigned to the `envMap` property or by `Scene.environment`
  11621. * if the node material is a PBR material. This node property allows to overwrite
  11622. * the default behavior and define the environment with a custom node.
  11623. *
  11624. * ```js
  11625. * material.envNode = pmremTexture( renderTarget.texture );
  11626. * ```
  11627. *
  11628. * @type {?Node<vec3>}
  11629. * @default null
  11630. */
  11631. this.envNode = null;
  11632. /**
  11633. * The lighting of node materials might be influenced by ambient occlusion.
  11634. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11635. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11636. * the default and define the ambient occlusion with a custom node instead.
  11637. *
  11638. * If you don't want to overwrite the diffuse color but modify the existing
  11639. * values instead, use {@link materialAO}.
  11640. *
  11641. * @type {?Node<float>}
  11642. * @default null
  11643. */
  11644. this.aoNode = null;
  11645. /**
  11646. * The diffuse color of node materials is by default inferred from the
  11647. * `color` and `map` properties. This node property allows to overwrite the default
  11648. * and define the diffuse color with a node instead.
  11649. *
  11650. * ```js
  11651. * material.colorNode = color( 0xff0000 ); // define red color
  11652. * ```
  11653. *
  11654. * If you don't want to overwrite the diffuse color but modify the existing
  11655. * values instead, use {@link materialColor}.
  11656. *
  11657. * ```js
  11658. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11659. * ```
  11660. *
  11661. * @type {?Node<vec3>}
  11662. * @default null
  11663. */
  11664. this.colorNode = null;
  11665. /**
  11666. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11667. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11668. * and define the normals with a node instead.
  11669. *
  11670. * If you don't want to overwrite the normals but modify the existing values instead,
  11671. * use {@link materialNormal}.
  11672. *
  11673. * @type {?Node<vec3>}
  11674. * @default null
  11675. */
  11676. this.normalNode = null;
  11677. /**
  11678. * The opacity of node materials is by default inferred from the `opacity`
  11679. * and `alphaMap` properties. This node property allows to overwrite the default
  11680. * and define the opacity with a node instead.
  11681. *
  11682. * If you don't want to overwrite the normals but modify the existing
  11683. * value instead, use {@link materialOpacity}.
  11684. *
  11685. * @type {?Node<float>}
  11686. * @default null
  11687. */
  11688. this.opacityNode = null;
  11689. /**
  11690. * This node can be used to to implement a variety of filter-like effects. The idea is
  11691. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11692. * to create an arbitrary effect and then assign the node composition to this property.
  11693. * Everything behind the object using this material will now be affected by a filter.
  11694. *
  11695. * ```js
  11696. * const material = new NodeMaterial()
  11697. * material.transparent = true;
  11698. *
  11699. * // everything behind the object will be monochromatic
  11700. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  11701. * ```
  11702. *
  11703. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11704. *
  11705. * @type {?Node<vec3>}
  11706. * @default null
  11707. */
  11708. this.backdropNode = null;
  11709. /**
  11710. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11711. *
  11712. * @type {?Node<float>}
  11713. * @default null
  11714. */
  11715. this.backdropAlphaNode = null;
  11716. /**
  11717. * The alpha test of node materials is by default inferred from the `alphaTest`
  11718. * property. This node property allows to overwrite the default and define the
  11719. * alpha test with a node instead.
  11720. *
  11721. * If you don't want to overwrite the alpha test but modify the existing
  11722. * value instead, use {@link materialAlphaTest}.
  11723. *
  11724. * @type {?Node<float>}
  11725. * @default null
  11726. */
  11727. this.alphaTestNode = null;
  11728. /**
  11729. * The local vertex positions are computed based on multiple factors like the
  11730. * attribute data, morphing or skinning. This node property allows to overwrite
  11731. * the default and define local vertex positions with nodes instead.
  11732. *
  11733. * If you don't want to overwrite the vertex positions but modify the existing
  11734. * values instead, use {@link positionLocal}.
  11735. *
  11736. *```js
  11737. * material.positionNode = positionLocal.add( displace );
  11738. * ```
  11739. *
  11740. * @type {?Node<vec3>}
  11741. * @default null
  11742. */
  11743. this.positionNode = null;
  11744. /**
  11745. * This node property is intended for logic which modifies geometry data once or per animation step.
  11746. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11747. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11748. * can be implemented.
  11749. *
  11750. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11751. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11752. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11753. * eventually assigned to `geometryNode`.
  11754. *
  11755. * @type {?Function}
  11756. * @default null
  11757. */
  11758. this.geometryNode = null;
  11759. /**
  11760. * Allows to overwrite depth values in the fragment shader.
  11761. *
  11762. * @type {?Node<float>}
  11763. * @default null
  11764. */
  11765. this.depthNode = null;
  11766. /**
  11767. * Allows to overwrite the position used for shadow map rendering which
  11768. * is by default {@link positionWorld}, the vertex position
  11769. * in world space.
  11770. *
  11771. * @type {?Node<float>}
  11772. * @default null
  11773. */
  11774. this.shadowPositionNode = null;
  11775. /**
  11776. * This node can be used to influence how an object using this node material
  11777. * receive shadows.
  11778. *
  11779. * ```js
  11780. * const totalShadows = float( 1 ).toVar();
  11781. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11782. * totalShadows.mulAssign( shadow );
  11783. * //return float( 1 ); // bypass received shadows
  11784. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11785. * } );
  11786. *
  11787. * @type {?(Function|FunctionNode<vec4>)}
  11788. * @default null
  11789. */
  11790. this.receivedShadowNode = null;
  11791. /**
  11792. * This node can be used to influence how an object using this node material
  11793. * casts shadows. To apply a color to shadows, you can simply do:
  11794. *
  11795. * ```js
  11796. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11797. * ```
  11798. *
  11799. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11800. * is also common to use the property with `Fn` function so checks are performed
  11801. * per fragment.
  11802. *
  11803. * ```js
  11804. * materialCustomShadow.castShadowNode = Fn( () => {
  11805. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11806. * return materialColor;
  11807. * } )();
  11808. * ```
  11809. *
  11810. * @type {?Node<vec4>}
  11811. * @default null
  11812. */
  11813. this.castShadowNode = null;
  11814. /**
  11815. * This node can be used to define the final output of the material.
  11816. *
  11817. * TODO: Explain the differences to `fragmentNode`.
  11818. *
  11819. * @type {?Node<vec4>}
  11820. * @default null
  11821. */
  11822. this.outputNode = null;
  11823. /**
  11824. * MRT configuration is done on renderer or pass level. This node allows to
  11825. * overwrite what values are written into MRT targets on material level. This
  11826. * can be useful for implementing selective FX features that should only affect
  11827. * specific objects.
  11828. *
  11829. * @type {?MRTNode}
  11830. * @default null
  11831. */
  11832. this.mrtNode = null;
  11833. /**
  11834. * This node property can be used if you need complete freedom in implementing
  11835. * the fragment shader. Assigning a node will replace the built-in material
  11836. * logic used in the fragment stage.
  11837. *
  11838. * @type {?Node<vec4>}
  11839. * @default null
  11840. */
  11841. this.fragmentNode = null;
  11842. /**
  11843. * This node property can be used if you need complete freedom in implementing
  11844. * the vertex shader. Assigning a node will replace the built-in material logic
  11845. * used in the vertex stage.
  11846. *
  11847. * @type {?Node<vec4>}
  11848. * @default null
  11849. */
  11850. this.vertexNode = null;
  11851. }
  11852. /**
  11853. * Allows to define a custom cache key that influence the material key computation
  11854. * for render objects.
  11855. *
  11856. * @return {string} The custom cache key.
  11857. */
  11858. customProgramCacheKey() {
  11859. return this.type + getCacheKey$1( this );
  11860. }
  11861. /**
  11862. * Builds this material with the given node builder.
  11863. *
  11864. * @param {NodeBuilder} builder - The current node builder.
  11865. */
  11866. build( builder ) {
  11867. this.setup( builder );
  11868. }
  11869. /**
  11870. * Setups a node material observer with the given builder.
  11871. *
  11872. * @param {NodeBuilder} builder - The current node builder.
  11873. * @return {NodeMaterialObserver} The node material observer.
  11874. */
  11875. setupObserver( builder ) {
  11876. return new NodeMaterialObserver( builder );
  11877. }
  11878. /**
  11879. * Setups the vertex and fragment stage of this node material.
  11880. *
  11881. * @param {NodeBuilder} builder - The current node builder.
  11882. */
  11883. setup( builder ) {
  11884. builder.context.setupNormal = () => this.setupNormal( builder );
  11885. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11886. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11887. const renderer = builder.renderer;
  11888. const renderTarget = renderer.getRenderTarget();
  11889. // < VERTEX STAGE >
  11890. builder.addStack();
  11891. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11892. builder.stack.outputNode = vertexNode;
  11893. this.setupHardwareClipping( builder );
  11894. if ( this.geometryNode !== null ) {
  11895. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11896. }
  11897. builder.addFlow( 'vertex', builder.removeStack() );
  11898. // < FRAGMENT STAGE >
  11899. builder.addStack();
  11900. let resultNode;
  11901. const clippingNode = this.setupClipping( builder );
  11902. if ( this.depthWrite === true || this.depthTest === true ) {
  11903. // only write depth if depth buffer is configured
  11904. if ( renderTarget !== null ) {
  11905. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11906. } else {
  11907. if ( renderer.depth === true ) this.setupDepth( builder );
  11908. }
  11909. }
  11910. if ( this.fragmentNode === null ) {
  11911. this.setupDiffuseColor( builder );
  11912. this.setupVariants( builder );
  11913. const outgoingLightNode = this.setupLighting( builder );
  11914. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11915. // force unsigned floats - useful for RenderTargets
  11916. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11917. resultNode = this.setupOutput( builder, basicOutput );
  11918. // OUTPUT NODE
  11919. output.assign( resultNode );
  11920. //
  11921. const isCustomOutput = this.outputNode !== null;
  11922. if ( isCustomOutput ) resultNode = this.outputNode;
  11923. // MRT
  11924. if ( renderTarget !== null ) {
  11925. const mrt = renderer.getMRT();
  11926. const materialMRT = this.mrtNode;
  11927. if ( mrt !== null ) {
  11928. if ( isCustomOutput ) output.assign( resultNode );
  11929. resultNode = mrt;
  11930. if ( materialMRT !== null ) {
  11931. resultNode = mrt.merge( materialMRT );
  11932. }
  11933. } else if ( materialMRT !== null ) {
  11934. resultNode = materialMRT;
  11935. }
  11936. }
  11937. } else {
  11938. let fragmentNode = this.fragmentNode;
  11939. if ( fragmentNode.isOutputStructNode !== true ) {
  11940. fragmentNode = vec4( fragmentNode );
  11941. }
  11942. resultNode = this.setupOutput( builder, fragmentNode );
  11943. }
  11944. builder.stack.outputNode = resultNode;
  11945. builder.addFlow( 'fragment', builder.removeStack() );
  11946. // < OBSERVER >
  11947. builder.observer = this.setupObserver( builder );
  11948. }
  11949. /**
  11950. * Setups the clipping node.
  11951. *
  11952. * @param {NodeBuilder} builder - The current node builder.
  11953. * @return {ClippingNode} The clipping node.
  11954. */
  11955. setupClipping( builder ) {
  11956. if ( builder.clippingContext === null ) return null;
  11957. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11958. let result = null;
  11959. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11960. const samples = builder.renderer.samples;
  11961. if ( this.alphaToCoverage && samples > 1 ) {
  11962. // to be added to flow when the color/alpha value has been determined
  11963. result = clippingAlpha();
  11964. } else {
  11965. builder.stack.add( clipping() );
  11966. }
  11967. }
  11968. return result;
  11969. }
  11970. /**
  11971. * Setups the hardware clipping if available on the current device.
  11972. *
  11973. * @param {NodeBuilder} builder - The current node builder.
  11974. */
  11975. setupHardwareClipping( builder ) {
  11976. this.hardwareClipping = false;
  11977. if ( builder.clippingContext === null ) return;
  11978. const candidateCount = builder.clippingContext.unionPlanes.length;
  11979. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11980. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11981. builder.stack.add( hardwareClipping() );
  11982. this.hardwareClipping = true;
  11983. }
  11984. return;
  11985. }
  11986. /**
  11987. * Setups the depth of this material.
  11988. *
  11989. * @param {NodeBuilder} builder - The current node builder.
  11990. */
  11991. setupDepth( builder ) {
  11992. const { renderer, camera } = builder;
  11993. // Depth
  11994. let depthNode = this.depthNode;
  11995. if ( depthNode === null ) {
  11996. const mrt = renderer.getMRT();
  11997. if ( mrt && mrt.has( 'depth' ) ) {
  11998. depthNode = mrt.get( 'depth' );
  11999. } else if ( renderer.logarithmicDepthBuffer === true ) {
  12000. if ( camera.isPerspectiveCamera ) {
  12001. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  12002. } else {
  12003. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12004. }
  12005. }
  12006. }
  12007. if ( depthNode !== null ) {
  12008. depth.assign( depthNode ).append();
  12009. }
  12010. }
  12011. /**
  12012. * Setups the position node in view space. This method exists
  12013. * so derived node materials can modify the implementation e.g. sprite materials.
  12014. *
  12015. * @param {NodeBuilder} builder - The current node builder.
  12016. * @return {Node<vec3>} The position in view space.
  12017. */
  12018. setupPositionView( /*builder*/ ) {
  12019. return modelViewMatrix.mul( positionLocal ).xyz;
  12020. }
  12021. /**
  12022. * Setups the position in clip space.
  12023. *
  12024. * @param {NodeBuilder} builder - The current node builder.
  12025. * @return {Node<vec4>} The position in view space.
  12026. */
  12027. setupModelViewProjection( /*builder*/ ) {
  12028. return cameraProjectionMatrix.mul( positionView );
  12029. }
  12030. /**
  12031. * Setups the logic for the vertex stage.
  12032. *
  12033. * @param {NodeBuilder} builder - The current node builder.
  12034. * @return {Node<vec4>} The position in clip space.
  12035. */
  12036. setupVertex( builder ) {
  12037. builder.addStack();
  12038. this.setupPosition( builder );
  12039. builder.context.vertex = builder.removeStack();
  12040. return modelViewProjection;
  12041. }
  12042. /**
  12043. * Setups the computation of the position in local space.
  12044. *
  12045. * @param {NodeBuilder} builder - The current node builder.
  12046. * @return {Node<vec3>} The position in local space.
  12047. */
  12048. setupPosition( builder ) {
  12049. const { object, geometry } = builder;
  12050. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  12051. morphReference( object ).append();
  12052. }
  12053. if ( object.isSkinnedMesh === true ) {
  12054. skinningReference( object ).append();
  12055. }
  12056. if ( this.displacementMap ) {
  12057. const displacementMap = materialReference( 'displacementMap', 'texture' );
  12058. const displacementScale = materialReference( 'displacementScale', 'float' );
  12059. const displacementBias = materialReference( 'displacementBias', 'float' );
  12060. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  12061. }
  12062. if ( object.isBatchedMesh ) {
  12063. batch( object ).append();
  12064. }
  12065. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  12066. instancedMesh( object ).append();
  12067. }
  12068. if ( this.positionNode !== null ) {
  12069. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  12070. }
  12071. return positionLocal;
  12072. }
  12073. /**
  12074. * Setups the computation of the material's diffuse color.
  12075. *
  12076. * @param {NodeBuilder} builder - The current node builder.
  12077. * @param {BufferGeometry} geometry - The geometry.
  12078. */
  12079. setupDiffuseColor( { object, geometry } ) {
  12080. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  12081. // VERTEX COLORS
  12082. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  12083. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  12084. }
  12085. // Instanced colors
  12086. if ( object.instanceColor ) {
  12087. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  12088. colorNode = instanceColor.mul( colorNode );
  12089. }
  12090. if ( object.isBatchedMesh && object._colorsTexture ) {
  12091. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  12092. colorNode = batchColor.mul( colorNode );
  12093. }
  12094. // COLOR
  12095. diffuseColor.assign( colorNode );
  12096. // OPACITY
  12097. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12098. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  12099. // ALPHA TEST
  12100. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  12101. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  12102. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  12103. }
  12104. // ALPHA HASH
  12105. if ( this.alphaHash === true ) {
  12106. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  12107. }
  12108. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  12109. diffuseColor.a.assign( 1.0 );
  12110. }
  12111. }
  12112. /**
  12113. * Abstract interface method that can be implemented by derived materials
  12114. * to setup material-specific node variables.
  12115. *
  12116. * @abstract
  12117. * @param {NodeBuilder} builder - The current node builder.
  12118. */
  12119. setupVariants( /*builder*/ ) {
  12120. // Interface function.
  12121. }
  12122. /**
  12123. * Setups the outgoing light node variable
  12124. *
  12125. * @return {Node<vec3>} The outgoing light node.
  12126. */
  12127. setupOutgoingLight() {
  12128. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  12129. }
  12130. /**
  12131. * Setups the normal node from the material.
  12132. *
  12133. * @return {Node<vec3>} The normal node.
  12134. */
  12135. setupNormal() {
  12136. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  12137. }
  12138. /**
  12139. * Setups the environment node from the material.
  12140. *
  12141. * @param {NodeBuilder} builder - The current node builder.
  12142. * @return {Node<vec4>} The environment node.
  12143. */
  12144. setupEnvironment( /*builder*/ ) {
  12145. let node = null;
  12146. if ( this.envNode ) {
  12147. node = this.envNode;
  12148. } else if ( this.envMap ) {
  12149. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  12150. }
  12151. return node;
  12152. }
  12153. /**
  12154. * Setups the light map node from the material.
  12155. *
  12156. * @param {NodeBuilder} builder - The current node builder.
  12157. * @return {Node<vec3>} The light map node.
  12158. */
  12159. setupLightMap( builder ) {
  12160. let node = null;
  12161. if ( builder.material.lightMap ) {
  12162. node = new IrradianceNode( materialLightMap );
  12163. }
  12164. return node;
  12165. }
  12166. /**
  12167. * Setups the lights node based on the scene, environment and material.
  12168. *
  12169. * @param {NodeBuilder} builder - The current node builder.
  12170. * @return {LightsNode} The lights node.
  12171. */
  12172. setupLights( builder ) {
  12173. const materialLightsNode = [];
  12174. //
  12175. const envNode = this.setupEnvironment( builder );
  12176. if ( envNode && envNode.isLightingNode ) {
  12177. materialLightsNode.push( envNode );
  12178. }
  12179. const lightMapNode = this.setupLightMap( builder );
  12180. if ( lightMapNode && lightMapNode.isLightingNode ) {
  12181. materialLightsNode.push( lightMapNode );
  12182. }
  12183. if ( this.aoNode !== null || builder.material.aoMap ) {
  12184. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  12185. materialLightsNode.push( new AONode( aoNode ) );
  12186. }
  12187. let lightsN = this.lightsNode || builder.lightsNode;
  12188. if ( materialLightsNode.length > 0 ) {
  12189. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  12190. }
  12191. return lightsN;
  12192. }
  12193. /**
  12194. * This method should be implemented by most derived materials
  12195. * since it defines the material's lighting model.
  12196. *
  12197. * @abstract
  12198. * @param {NodeBuilder} builder - The current node builder.
  12199. * @return {LightingModel} The lighting model.
  12200. */
  12201. setupLightingModel( /*builder*/ ) {
  12202. // Interface function.
  12203. }
  12204. /**
  12205. * Setups the outgoing light node.
  12206. *
  12207. * @param {NodeBuilder} builder - The current node builder.
  12208. * @return {Node<vec3>} The outgoing light node.
  12209. */
  12210. setupLighting( builder ) {
  12211. const { material } = builder;
  12212. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  12213. // OUTGOING LIGHT
  12214. const lights = this.lights === true || this.lightsNode !== null;
  12215. const lightsNode = lights ? this.setupLights( builder ) : null;
  12216. let outgoingLightNode = this.setupOutgoingLight( builder );
  12217. if ( lightsNode && lightsNode.getScope().hasLights ) {
  12218. const lightingModel = this.setupLightingModel( builder ) || null;
  12219. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  12220. } else if ( backdropNode !== null ) {
  12221. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  12222. }
  12223. // EMISSIVE
  12224. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  12225. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  12226. outgoingLightNode = outgoingLightNode.add( emissive );
  12227. }
  12228. return outgoingLightNode;
  12229. }
  12230. /**
  12231. * Setup the fog.
  12232. *
  12233. * @param {NodeBuilder} builder - The current node builder.
  12234. * @param {Node<vec4>} outputNode - The existing output node.
  12235. * @return {Node<vec4>} The output node.
  12236. */
  12237. setupFog( builder, outputNode ) {
  12238. const fogNode = builder.fogNode;
  12239. if ( fogNode ) {
  12240. output.assign( outputNode );
  12241. outputNode = vec4( fogNode );
  12242. }
  12243. return outputNode;
  12244. }
  12245. /**
  12246. * Setups the output node.
  12247. *
  12248. * @param {NodeBuilder} builder - The current node builder.
  12249. * @param {Node<vec4>} outputNode - The existing output node.
  12250. * @return {Node<vec4>} The output node.
  12251. */
  12252. setupOutput( builder, outputNode ) {
  12253. // FOG
  12254. if ( this.fog === true ) {
  12255. outputNode = this.setupFog( builder, outputNode );
  12256. }
  12257. return outputNode;
  12258. }
  12259. /**
  12260. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  12261. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  12262. * defining all material properties of the classic type in the node type.
  12263. *
  12264. * @param {Material} material - The material to copy properties with their values to this node material.
  12265. */
  12266. setDefaultValues( material ) {
  12267. // This approach is to reuse the native refreshUniforms*
  12268. // and turn available the use of features like transmission and environment in core
  12269. for ( const property in material ) {
  12270. const value = material[ property ];
  12271. if ( this[ property ] === undefined ) {
  12272. this[ property ] = value;
  12273. if ( value && value.clone ) this[ property ] = value.clone();
  12274. }
  12275. }
  12276. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  12277. for ( const key in descriptors ) {
  12278. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  12279. descriptors[ key ].get !== undefined ) {
  12280. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  12281. }
  12282. }
  12283. }
  12284. /**
  12285. * Serializes this material to JSON.
  12286. *
  12287. * @param {?(Object|string)} meta - The meta information for serialization.
  12288. * @return {Object} The serialized node.
  12289. */
  12290. toJSON( meta ) {
  12291. const isRoot = ( meta === undefined || typeof meta === 'string' );
  12292. if ( isRoot ) {
  12293. meta = {
  12294. textures: {},
  12295. images: {},
  12296. nodes: {}
  12297. };
  12298. }
  12299. const data = Material.prototype.toJSON.call( this, meta );
  12300. const nodeChildren = getNodeChildren( this );
  12301. data.inputNodes = {};
  12302. for ( const { property, childNode } of nodeChildren ) {
  12303. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  12304. }
  12305. // TODO: Copied from Object3D.toJSON
  12306. function extractFromCache( cache ) {
  12307. const values = [];
  12308. for ( const key in cache ) {
  12309. const data = cache[ key ];
  12310. delete data.metadata;
  12311. values.push( data );
  12312. }
  12313. return values;
  12314. }
  12315. if ( isRoot ) {
  12316. const textures = extractFromCache( meta.textures );
  12317. const images = extractFromCache( meta.images );
  12318. const nodes = extractFromCache( meta.nodes );
  12319. if ( textures.length > 0 ) data.textures = textures;
  12320. if ( images.length > 0 ) data.images = images;
  12321. if ( nodes.length > 0 ) data.nodes = nodes;
  12322. }
  12323. return data;
  12324. }
  12325. /**
  12326. * Copies the properties of the given node material to this instance.
  12327. *
  12328. * @param {NodeMaterial} source - The material to copy.
  12329. * @return {NodeMaterial} A reference to this node material.
  12330. */
  12331. copy( source ) {
  12332. this.lightsNode = source.lightsNode;
  12333. this.envNode = source.envNode;
  12334. this.colorNode = source.colorNode;
  12335. this.normalNode = source.normalNode;
  12336. this.opacityNode = source.opacityNode;
  12337. this.backdropNode = source.backdropNode;
  12338. this.backdropAlphaNode = source.backdropAlphaNode;
  12339. this.alphaTestNode = source.alphaTestNode;
  12340. this.positionNode = source.positionNode;
  12341. this.geometryNode = source.geometryNode;
  12342. this.depthNode = source.depthNode;
  12343. this.shadowPositionNode = source.shadowPositionNode;
  12344. this.receivedShadowNode = source.receivedShadowNode;
  12345. this.castShadowNode = source.castShadowNode;
  12346. this.outputNode = source.outputNode;
  12347. this.mrtNode = source.mrtNode;
  12348. this.fragmentNode = source.fragmentNode;
  12349. this.vertexNode = source.vertexNode;
  12350. return super.copy( source );
  12351. }
  12352. }
  12353. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  12354. /**
  12355. * Node material version of {@link LineBasicMaterial}.
  12356. *
  12357. * @augments NodeMaterial
  12358. */
  12359. class LineBasicNodeMaterial extends NodeMaterial {
  12360. static get type() {
  12361. return 'LineBasicNodeMaterial';
  12362. }
  12363. /**
  12364. * Constructs a new line basic node material.
  12365. *
  12366. * @param {Object} [parameters] - The configuration parameter.
  12367. */
  12368. constructor( parameters ) {
  12369. super();
  12370. /**
  12371. * This flag can be used for type testing.
  12372. *
  12373. * @type {boolean}
  12374. * @readonly
  12375. * @default true
  12376. */
  12377. this.isLineBasicNodeMaterial = true;
  12378. this.setDefaultValues( _defaultValues$d );
  12379. this.setValues( parameters );
  12380. }
  12381. }
  12382. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  12383. /**
  12384. * Node material version of {@link LineDashedMaterial}.
  12385. *
  12386. * @augments NodeMaterial
  12387. */
  12388. class LineDashedNodeMaterial extends NodeMaterial {
  12389. static get type() {
  12390. return 'LineDashedNodeMaterial';
  12391. }
  12392. /**
  12393. * Constructs a new line dashed node material.
  12394. *
  12395. * @param {Object} [parameters] - The configuration parameter.
  12396. */
  12397. constructor( parameters ) {
  12398. super();
  12399. /**
  12400. * This flag can be used for type testing.
  12401. *
  12402. * @type {boolean}
  12403. * @readonly
  12404. * @default true
  12405. */
  12406. this.isLineDashedNodeMaterial = true;
  12407. this.setDefaultValues( _defaultValues$c );
  12408. /**
  12409. * The dash offset.
  12410. *
  12411. * @type {number}
  12412. * @default 0
  12413. */
  12414. this.dashOffset = 0;
  12415. /**
  12416. * The offset of dash materials is by default inferred from the `dashOffset`
  12417. * property. This node property allows to overwrite the default
  12418. * and define the offset with a node instead.
  12419. *
  12420. * If you don't want to overwrite the offset but modify the existing
  12421. * value instead, use {@link materialLineDashOffset}.
  12422. *
  12423. * @type {?Node<float>}
  12424. * @default null
  12425. */
  12426. this.offsetNode = null;
  12427. /**
  12428. * The scale of dash materials is by default inferred from the `scale`
  12429. * property. This node property allows to overwrite the default
  12430. * and define the scale with a node instead.
  12431. *
  12432. * If you don't want to overwrite the scale but modify the existing
  12433. * value instead, use {@link materialLineScale}.
  12434. *
  12435. * @type {?Node<float>}
  12436. * @default null
  12437. */
  12438. this.dashScaleNode = null;
  12439. /**
  12440. * The dash size of dash materials is by default inferred from the `dashSize`
  12441. * property. This node property allows to overwrite the default
  12442. * and define the dash size with a node instead.
  12443. *
  12444. * If you don't want to overwrite the dash size but modify the existing
  12445. * value instead, use {@link materialLineDashSize}.
  12446. *
  12447. * @type {?Node<float>}
  12448. * @default null
  12449. */
  12450. this.dashSizeNode = null;
  12451. /**
  12452. * The gap size of dash materials is by default inferred from the `gapSize`
  12453. * property. This node property allows to overwrite the default
  12454. * and define the gap size with a node instead.
  12455. *
  12456. * If you don't want to overwrite the gap size but modify the existing
  12457. * value instead, use {@link materialLineGapSize}.
  12458. *
  12459. * @type {?Node<float>}
  12460. * @default null
  12461. */
  12462. this.gapSizeNode = null;
  12463. this.setValues( parameters );
  12464. }
  12465. /**
  12466. * Setups the dash specific node variables.
  12467. *
  12468. * @param {NodeBuilder} builder - The current node builder.
  12469. */
  12470. setupVariants( /* builder */ ) {
  12471. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12472. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12473. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12474. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12475. dashSize.assign( dashSizeNode );
  12476. gapSize.assign( gapSizeNode );
  12477. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  12478. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  12479. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  12480. }
  12481. }
  12482. let _sharedFramebuffer = null;
  12483. /**
  12484. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  12485. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  12486. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  12487. *
  12488. * @augments ViewportTextureNode
  12489. */
  12490. class ViewportSharedTextureNode extends ViewportTextureNode {
  12491. static get type() {
  12492. return 'ViewportSharedTextureNode';
  12493. }
  12494. /**
  12495. * Constructs a new viewport shared texture node.
  12496. *
  12497. * @param {Node} [uvNode=screenUV] - The uv node.
  12498. * @param {?Node} [levelNode=null] - The level node.
  12499. */
  12500. constructor( uvNode = screenUV, levelNode = null ) {
  12501. if ( _sharedFramebuffer === null ) {
  12502. _sharedFramebuffer = new FramebufferTexture();
  12503. }
  12504. super( uvNode, levelNode, _sharedFramebuffer );
  12505. }
  12506. updateReference() {
  12507. return this;
  12508. }
  12509. }
  12510. /**
  12511. * TSL function for creating a shared viewport texture node.
  12512. *
  12513. * @tsl
  12514. * @function
  12515. * @param {Node} [uvNode=screenUV] - The uv node.
  12516. * @param {?Node} [levelNode=null] - The level node.
  12517. * @returns {ViewportSharedTextureNode}
  12518. */
  12519. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  12520. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  12521. /**
  12522. * This node material can be used to render lines with a size larger than one
  12523. * by representing them as instanced meshes.
  12524. *
  12525. * @augments NodeMaterial
  12526. */
  12527. class Line2NodeMaterial extends NodeMaterial {
  12528. static get type() {
  12529. return 'Line2NodeMaterial';
  12530. }
  12531. /**
  12532. * Constructs a new node material for wide line rendering.
  12533. *
  12534. * @param {Object} [parameters={}] - The configuration parameter.
  12535. */
  12536. constructor( parameters = {} ) {
  12537. super();
  12538. /**
  12539. * This flag can be used for type testing.
  12540. *
  12541. * @type {boolean}
  12542. * @readonly
  12543. * @default true
  12544. */
  12545. this.isLine2NodeMaterial = true;
  12546. this.setDefaultValues( _defaultValues$b );
  12547. /**
  12548. * Whether vertex colors should be used or not.
  12549. *
  12550. * @type {boolean}
  12551. * @default false
  12552. */
  12553. this.useColor = parameters.vertexColors;
  12554. /**
  12555. * The dash offset.
  12556. *
  12557. * @type {number}
  12558. * @default 0
  12559. */
  12560. this.dashOffset = 0;
  12561. /**
  12562. * The line width.
  12563. *
  12564. * @type {number}
  12565. * @default 0
  12566. */
  12567. this.lineWidth = 1;
  12568. /**
  12569. * Defines the lines color.
  12570. *
  12571. * @type {?Node<vec3>}
  12572. * @default null
  12573. */
  12574. this.lineColorNode = null;
  12575. /**
  12576. * Defines the offset.
  12577. *
  12578. * @type {?Node<float>}
  12579. * @default null
  12580. */
  12581. this.offsetNode = null;
  12582. /**
  12583. * Defines the dash scale.
  12584. *
  12585. * @type {?Node<float>}
  12586. * @default null
  12587. */
  12588. this.dashScaleNode = null;
  12589. /**
  12590. * Defines the dash size.
  12591. *
  12592. * @type {?Node<float>}
  12593. * @default null
  12594. */
  12595. this.dashSizeNode = null;
  12596. /**
  12597. * Defines the gap size.
  12598. *
  12599. * @type {?Node<float>}
  12600. * @default null
  12601. */
  12602. this.gapSizeNode = null;
  12603. /**
  12604. * Blending is set to `NoBlending` since transparency
  12605. * is not supported, yet.
  12606. *
  12607. * @type {number}
  12608. * @default 0
  12609. */
  12610. this.blending = NoBlending;
  12611. this._useDash = parameters.dashed;
  12612. this._useAlphaToCoverage = true;
  12613. this._useWorldUnits = false;
  12614. this.setValues( parameters );
  12615. }
  12616. /**
  12617. * Setups the vertex and fragment stage of this node material.
  12618. *
  12619. * @param {NodeBuilder} builder - The current node builder.
  12620. */
  12621. setup( builder ) {
  12622. const { renderer } = builder;
  12623. const useAlphaToCoverage = this._useAlphaToCoverage;
  12624. const useColor = this.useColor;
  12625. const useDash = this._useDash;
  12626. const useWorldUnits = this._useWorldUnits;
  12627. const trimSegment = Fn( ( { start, end } ) => {
  12628. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12629. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12630. const nearEstimate = b.mul( - 0.5 ).div( a );
  12631. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12632. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12633. } ).setLayout( {
  12634. name: 'trimSegment',
  12635. type: 'vec4',
  12636. inputs: [
  12637. { name: 'start', type: 'vec4' },
  12638. { name: 'end', type: 'vec4' }
  12639. ]
  12640. } );
  12641. this.vertexNode = Fn( () => {
  12642. const instanceStart = attribute( 'instanceStart' );
  12643. const instanceEnd = attribute( 'instanceEnd' );
  12644. // camera space
  12645. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12646. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12647. if ( useDash ) {
  12648. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12649. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12650. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12651. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12652. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12653. lineDistance = lineDistance.add( offsetNode );
  12654. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12655. }
  12656. if ( useWorldUnits ) {
  12657. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12658. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12659. }
  12660. const aspect = viewport.z.div( viewport.w );
  12661. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12662. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12663. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12664. // perhaps there is a more elegant solution -- WestLangley
  12665. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12666. If( perspective, () => {
  12667. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12668. end.assign( trimSegment( { start: start, end: end } ) );
  12669. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12670. start.assign( trimSegment( { start: end, end: start } ) );
  12671. } );
  12672. } );
  12673. // clip space
  12674. const clipStart = cameraProjectionMatrix.mul( start );
  12675. const clipEnd = cameraProjectionMatrix.mul( end );
  12676. // ndc space
  12677. const ndcStart = clipStart.xyz.div( clipStart.w );
  12678. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12679. // direction
  12680. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12681. // account for clip-space aspect ratio
  12682. dir.x.assign( dir.x.mul( aspect ) );
  12683. dir.assign( dir.normalize() );
  12684. const clip = vec4().toVar();
  12685. if ( useWorldUnits ) {
  12686. // get the offset direction as perpendicular to the view vector
  12687. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12688. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12689. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12690. const worldFwd = worldDir.cross( worldUp );
  12691. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12692. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12693. // height offset
  12694. const hw = materialLineWidth.mul( 0.5 );
  12695. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12696. // don't extend the line if we're rendering dashes because we
  12697. // won't be rendering the endcaps
  12698. if ( ! useDash ) {
  12699. // cap extension
  12700. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12701. // add width to the box
  12702. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12703. // endcaps
  12704. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12705. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12706. } );
  12707. }
  12708. // project the worldpos
  12709. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12710. // shift the depth of the projected points so the line
  12711. // segments overlap neatly
  12712. const clipPose = vec3().toVar();
  12713. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12714. clip.z.assign( clipPose.z.mul( clip.w ) );
  12715. } else {
  12716. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12717. // undo aspect ratio adjustment
  12718. dir.x.assign( dir.x.div( aspect ) );
  12719. offset.x.assign( offset.x.div( aspect ) );
  12720. // sign flip
  12721. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12722. // endcaps
  12723. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12724. offset.assign( offset.sub( dir ) );
  12725. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12726. offset.assign( offset.add( dir ) );
  12727. } );
  12728. // adjust for linewidth
  12729. offset.assign( offset.mul( materialLineWidth ) );
  12730. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12731. offset.assign( offset.div( viewport.w ) );
  12732. // select end
  12733. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12734. // back to clip space
  12735. offset.assign( offset.mul( clip.w ) );
  12736. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12737. }
  12738. return clip;
  12739. } )();
  12740. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12741. const p13 = p1.sub( p3 );
  12742. const p43 = p4.sub( p3 );
  12743. const p21 = p2.sub( p1 );
  12744. const d1343 = p13.dot( p43 );
  12745. const d4321 = p43.dot( p21 );
  12746. const d1321 = p13.dot( p21 );
  12747. const d4343 = p43.dot( p43 );
  12748. const d2121 = p21.dot( p21 );
  12749. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12750. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12751. const mua = numer.div( denom ).clamp();
  12752. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12753. return vec2( mua, mub );
  12754. } );
  12755. this.colorNode = Fn( () => {
  12756. const vUv = uv();
  12757. if ( useDash ) {
  12758. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12759. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12760. dashSize.assign( dashSizeNode );
  12761. gapSize.assign( gapSizeNode );
  12762. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12763. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12764. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12765. }
  12766. const alpha = float( 1 ).toVar( 'alpha' );
  12767. if ( useWorldUnits ) {
  12768. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12769. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12770. // Find the closest points on the view ray and the line segment
  12771. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12772. const lineDir = worldEnd.sub( worldStart );
  12773. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12774. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12775. const p2 = rayEnd.mul( params.y );
  12776. const delta = p1.sub( p2 );
  12777. const len = delta.length();
  12778. const norm = len.div( materialLineWidth );
  12779. if ( ! useDash ) {
  12780. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12781. const dnorm = norm.fwidth();
  12782. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12783. } else {
  12784. norm.greaterThan( 0.5 ).discard();
  12785. }
  12786. }
  12787. } else {
  12788. // round endcaps
  12789. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12790. const a = vUv.x;
  12791. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12792. const len2 = a.mul( a ).add( b.mul( b ) );
  12793. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12794. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12795. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12796. } );
  12797. } else {
  12798. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12799. const a = vUv.x;
  12800. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12801. const len2 = a.mul( a ).add( b.mul( b ) );
  12802. len2.greaterThan( 1.0 ).discard();
  12803. } );
  12804. }
  12805. }
  12806. let lineColorNode;
  12807. if ( this.lineColorNode ) {
  12808. lineColorNode = this.lineColorNode;
  12809. } else {
  12810. if ( useColor ) {
  12811. const instanceColorStart = attribute( 'instanceColorStart' );
  12812. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12813. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12814. lineColorNode = instanceColor.mul( materialColor );
  12815. } else {
  12816. lineColorNode = materialColor;
  12817. }
  12818. }
  12819. return vec4( lineColorNode, alpha );
  12820. } )();
  12821. if ( this.transparent ) {
  12822. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12823. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12824. }
  12825. super.setup( builder );
  12826. }
  12827. /**
  12828. * Whether the lines should sized in world units or not.
  12829. * When set to `false` the unit is pixel.
  12830. *
  12831. * @type {boolean}
  12832. * @default false
  12833. */
  12834. get worldUnits() {
  12835. return this._useWorldUnits;
  12836. }
  12837. set worldUnits( value ) {
  12838. if ( this._useWorldUnits !== value ) {
  12839. this._useWorldUnits = value;
  12840. this.needsUpdate = true;
  12841. }
  12842. }
  12843. /**
  12844. * Whether the lines should be dashed or not.
  12845. *
  12846. * @type {boolean}
  12847. * @default false
  12848. */
  12849. get dashed() {
  12850. return this._useDash;
  12851. }
  12852. set dashed( value ) {
  12853. if ( this._useDash !== value ) {
  12854. this._useDash = value;
  12855. this.needsUpdate = true;
  12856. }
  12857. }
  12858. /**
  12859. * Whether alpha to coverage should be used or not.
  12860. *
  12861. * @type {boolean}
  12862. * @default true
  12863. */
  12864. get alphaToCoverage() {
  12865. return this._useAlphaToCoverage;
  12866. }
  12867. set alphaToCoverage( value ) {
  12868. if ( this._useAlphaToCoverage !== value ) {
  12869. this._useAlphaToCoverage = value;
  12870. this.needsUpdate = true;
  12871. }
  12872. }
  12873. }
  12874. /**
  12875. * Packs a direction vector into a color value.
  12876. *
  12877. * @tsl
  12878. * @function
  12879. * @param {Node<vec3>} node - The direction to pack.
  12880. * @return {Node<vec3>} The color.
  12881. */
  12882. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12883. /**
  12884. * Unpacks a color value into a direction vector.
  12885. *
  12886. * @tsl
  12887. * @function
  12888. * @param {Node<vec3>} node - The color to unpack.
  12889. * @return {Node<vec3>} The direction.
  12890. */
  12891. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12892. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12893. /**
  12894. * Node material version of {@link MeshNormalMaterial}.
  12895. *
  12896. * @augments NodeMaterial
  12897. */
  12898. class MeshNormalNodeMaterial extends NodeMaterial {
  12899. static get type() {
  12900. return 'MeshNormalNodeMaterial';
  12901. }
  12902. /**
  12903. * Constructs a new mesh normal node material.
  12904. *
  12905. * @param {Object} [parameters] - The configuration parameter.
  12906. */
  12907. constructor( parameters ) {
  12908. super();
  12909. /**
  12910. * This flag can be used for type testing.
  12911. *
  12912. * @type {boolean}
  12913. * @readonly
  12914. * @default true
  12915. */
  12916. this.isMeshNormalNodeMaterial = true;
  12917. this.setDefaultValues( _defaultValues$a );
  12918. this.setValues( parameters );
  12919. }
  12920. /**
  12921. * Overwrites the default implementation by computing the diffuse color
  12922. * based on the normal data.
  12923. */
  12924. setupDiffuseColor() {
  12925. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12926. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  12927. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( transformedNormalView ), opacityNode ), SRGBColorSpace ) );
  12928. }
  12929. }
  12930. /**
  12931. * Can be used to compute texture coordinates for projecting an
  12932. * equirectangular texture onto a mesh for using it as the scene's
  12933. * background.
  12934. *
  12935. * ```js
  12936. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12937. * ```
  12938. *
  12939. * @augments TempNode
  12940. */
  12941. class EquirectUVNode extends TempNode {
  12942. static get type() {
  12943. return 'EquirectUVNode';
  12944. }
  12945. /**
  12946. * Constructs a new equirect uv node.
  12947. *
  12948. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12949. */
  12950. constructor( dirNode = positionWorldDirection ) {
  12951. super( 'vec2' );
  12952. /**
  12953. * A direction vector for sampling why is by default `positionWorldDirection`.
  12954. *
  12955. * @type {Node<vec3>}
  12956. */
  12957. this.dirNode = dirNode;
  12958. }
  12959. setup() {
  12960. const dir = this.dirNode;
  12961. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12962. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12963. return vec2( u, v );
  12964. }
  12965. }
  12966. /**
  12967. * TSL function for creating an equirect uv node.
  12968. *
  12969. * @tsl
  12970. * @function
  12971. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12972. * @returns {EquirectUVNode}
  12973. */
  12974. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12975. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12976. /**
  12977. * This class represents a cube render target. It is a special version
  12978. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12979. *
  12980. * @augments WebGLCubeRenderTarget
  12981. */
  12982. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12983. /**
  12984. * Constructs a new cube render target.
  12985. *
  12986. * @param {number} [size=1] - The size of the render target.
  12987. * @param {RenderTarget~Options} [options] - The configuration object.
  12988. */
  12989. constructor( size = 1, options = {} ) {
  12990. super( size, options );
  12991. /**
  12992. * This flag can be used for type testing.
  12993. *
  12994. * @type {boolean}
  12995. * @readonly
  12996. * @default true
  12997. */
  12998. this.isCubeRenderTarget = true;
  12999. }
  13000. /**
  13001. * Converts the given equirectangular texture to a cube map.
  13002. *
  13003. * @param {Renderer} renderer - The renderer.
  13004. * @param {Texture} texture - The equirectangular texture.
  13005. * @return {CubeRenderTarget} A reference to this cube render target.
  13006. */
  13007. fromEquirectangularTexture( renderer, texture$1 ) {
  13008. const currentMinFilter = texture$1.minFilter;
  13009. const currentGenerateMipmaps = texture$1.generateMipmaps;
  13010. texture$1.generateMipmaps = true;
  13011. this.texture.type = texture$1.type;
  13012. this.texture.colorSpace = texture$1.colorSpace;
  13013. this.texture.generateMipmaps = texture$1.generateMipmaps;
  13014. this.texture.minFilter = texture$1.minFilter;
  13015. this.texture.magFilter = texture$1.magFilter;
  13016. const geometry = new BoxGeometry( 5, 5, 5 );
  13017. const uvNode = equirectUV( positionWorldDirection );
  13018. const material = new NodeMaterial();
  13019. material.colorNode = texture( texture$1, uvNode, 0 );
  13020. material.side = BackSide;
  13021. material.blending = NoBlending;
  13022. const mesh = new Mesh( geometry, material );
  13023. const scene = new Scene();
  13024. scene.add( mesh );
  13025. // Avoid blurred poles
  13026. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  13027. const camera = new CubeCamera( 1, 10, this );
  13028. const currentMRT = renderer.getMRT();
  13029. renderer.setMRT( null );
  13030. camera.update( renderer, scene );
  13031. renderer.setMRT( currentMRT );
  13032. texture$1.minFilter = currentMinFilter;
  13033. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  13034. mesh.geometry.dispose();
  13035. mesh.material.dispose();
  13036. return this;
  13037. }
  13038. }
  13039. const _cache$1 = new WeakMap();
  13040. /**
  13041. * This node can be used to automatically convert environment maps in the
  13042. * equirectangular format into the cube map format.
  13043. *
  13044. * @augments TempNode
  13045. */
  13046. class CubeMapNode extends TempNode {
  13047. static get type() {
  13048. return 'CubeMapNode';
  13049. }
  13050. /**
  13051. * Constructs a new cube map node.
  13052. *
  13053. * @param {Node} envNode - The node representing the environment map.
  13054. */
  13055. constructor( envNode ) {
  13056. super( 'vec3' );
  13057. /**
  13058. * The node representing the environment map.
  13059. *
  13060. * @type {Node}
  13061. */
  13062. this.envNode = envNode;
  13063. /**
  13064. * A reference to the internal cube texture.
  13065. *
  13066. * @private
  13067. * @type {?CubeTexture}
  13068. * @default null
  13069. */
  13070. this._cubeTexture = null;
  13071. /**
  13072. * A reference to the internal cube texture node.
  13073. *
  13074. * @private
  13075. * @type {CubeTextureNode}
  13076. */
  13077. this._cubeTextureNode = cubeTexture();
  13078. const defaultTexture = new CubeTexture();
  13079. defaultTexture.isRenderTargetTexture = true;
  13080. /**
  13081. * A default cube texture that acts as a placeholder.
  13082. * It is used when the conversion from equirectangular to cube
  13083. * map has not finished yet for a given texture.
  13084. *
  13085. * @private
  13086. * @type {CubeTexture}
  13087. */
  13088. this._defaultTexture = defaultTexture;
  13089. /**
  13090. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  13091. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  13092. *
  13093. * @type {string}
  13094. * @default 'render'
  13095. */
  13096. this.updateBeforeType = NodeUpdateType.RENDER;
  13097. }
  13098. updateBefore( frame ) {
  13099. const { renderer, material } = frame;
  13100. const envNode = this.envNode;
  13101. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  13102. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  13103. if ( texture && texture.isTexture ) {
  13104. const mapping = texture.mapping;
  13105. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  13106. // check for converted cubemap map
  13107. if ( _cache$1.has( texture ) ) {
  13108. const cubeMap = _cache$1.get( texture );
  13109. mapTextureMapping( cubeMap, texture.mapping );
  13110. this._cubeTexture = cubeMap;
  13111. } else {
  13112. // create cube map from equirectangular map
  13113. const image = texture.image;
  13114. if ( isEquirectangularMapReady$1( image ) ) {
  13115. const renderTarget = new CubeRenderTarget( image.height );
  13116. renderTarget.fromEquirectangularTexture( renderer, texture );
  13117. mapTextureMapping( renderTarget.texture, texture.mapping );
  13118. this._cubeTexture = renderTarget.texture;
  13119. _cache$1.set( texture, renderTarget.texture );
  13120. texture.addEventListener( 'dispose', onTextureDispose );
  13121. } else {
  13122. // default cube texture as fallback when equirectangular texture is not yet loaded
  13123. this._cubeTexture = this._defaultTexture;
  13124. }
  13125. }
  13126. //
  13127. this._cubeTextureNode.value = this._cubeTexture;
  13128. } else {
  13129. // envNode already refers to a cube map
  13130. this._cubeTextureNode = this.envNode;
  13131. }
  13132. }
  13133. }
  13134. }
  13135. setup( builder ) {
  13136. this.updateBefore( builder );
  13137. return this._cubeTextureNode;
  13138. }
  13139. }
  13140. /**
  13141. * Returns true if the given equirectangular image has been fully loaded
  13142. * and is ready for further processing.
  13143. *
  13144. * @private
  13145. * @param {Image} image - The equirectangular image to check.
  13146. * @return {boolean} Whether the image is ready or not.
  13147. */
  13148. function isEquirectangularMapReady$1( image ) {
  13149. if ( image === null || image === undefined ) return false;
  13150. return image.height > 0;
  13151. }
  13152. /**
  13153. * This function is executed when `dispose()` is called on the equirectangular
  13154. * texture. In this case, the generated cube map with its render target
  13155. * is deleted as well.
  13156. *
  13157. * @private
  13158. * @param {Object} event - The event object.
  13159. */
  13160. function onTextureDispose( event ) {
  13161. const texture = event.target;
  13162. texture.removeEventListener( 'dispose', onTextureDispose );
  13163. const renderTarget = _cache$1.get( texture );
  13164. if ( renderTarget !== undefined ) {
  13165. _cache$1.delete( texture );
  13166. renderTarget.dispose();
  13167. }
  13168. }
  13169. /**
  13170. * This function makes sure the generated cube map uses the correct
  13171. * texture mapping that corresponds to the equirectangular original.
  13172. *
  13173. * @private
  13174. * @param {Texture} texture - The cube texture.
  13175. * @param {number} mapping - The original texture mapping.
  13176. */
  13177. function mapTextureMapping( texture, mapping ) {
  13178. if ( mapping === EquirectangularReflectionMapping ) {
  13179. texture.mapping = CubeReflectionMapping;
  13180. } else if ( mapping === EquirectangularRefractionMapping ) {
  13181. texture.mapping = CubeRefractionMapping;
  13182. }
  13183. }
  13184. /**
  13185. * TSL function for creating a cube map node.
  13186. *
  13187. * @tsl
  13188. * @function
  13189. * @param {Node} envNode - The node representing the environment map.
  13190. * @returns {CubeMapNode}
  13191. */
  13192. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  13193. /**
  13194. * Represents a basic model for Image-based lighting (IBL). The environment
  13195. * is defined via environment maps in the equirectangular or cube map format.
  13196. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  13197. * or {@link MeshPhongNodeMaterial}.
  13198. *
  13199. * @augments LightingNode
  13200. */
  13201. class BasicEnvironmentNode extends LightingNode {
  13202. static get type() {
  13203. return 'BasicEnvironmentNode';
  13204. }
  13205. /**
  13206. * Constructs a new basic environment node.
  13207. *
  13208. * @param {Node} [envNode=null] - A node representing the environment.
  13209. */
  13210. constructor( envNode = null ) {
  13211. super();
  13212. /**
  13213. * A node representing the environment.
  13214. *
  13215. * @type {Node}
  13216. * @default null
  13217. */
  13218. this.envNode = envNode;
  13219. }
  13220. setup( builder ) {
  13221. // environment property is used in the finish() method of BasicLightingModel
  13222. builder.context.environment = cubeMapNode( this.envNode );
  13223. }
  13224. }
  13225. /**
  13226. * A specific version of {@link IrradianceNode} that is only relevant
  13227. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  13228. * requires a special scaling factor for the light map.
  13229. *
  13230. * @augments LightingNode
  13231. */
  13232. class BasicLightMapNode extends LightingNode {
  13233. static get type() {
  13234. return 'BasicLightMapNode';
  13235. }
  13236. /**
  13237. * Constructs a new basic light map node.
  13238. *
  13239. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  13240. */
  13241. constructor( lightMapNode = null ) {
  13242. super();
  13243. /**
  13244. * The light map node.
  13245. *
  13246. * @type {?Node<vec3>}
  13247. */
  13248. this.lightMapNode = lightMapNode;
  13249. }
  13250. setup( builder ) {
  13251. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  13252. const RECIPROCAL_PI = float( 1 / Math.PI );
  13253. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  13254. }
  13255. }
  13256. /**
  13257. * Abstract class for implementing lighting models. The module defines
  13258. * multiple methods that concrete lighting models can implement. These
  13259. * methods are executed at different points during the light evaluation
  13260. * process.
  13261. */
  13262. class LightingModel {
  13263. /**
  13264. * This method is intended for setting up lighting model and context data
  13265. * which are later used in the evaluation process.
  13266. *
  13267. * @abstract
  13268. * @param {NodeBuilder} builder - The current node builder.
  13269. */
  13270. start( builder ) {
  13271. // lights ( direct )
  13272. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  13273. // indirect
  13274. this.indirect( builder );
  13275. }
  13276. /**
  13277. * This method is intended for executing final tasks like final updates
  13278. * to the outgoing light.
  13279. *
  13280. * @abstract
  13281. * @param {NodeBuilder} builder - The current node builder.
  13282. */
  13283. finish( /*builder*/ ) { }
  13284. /**
  13285. * This method is intended for implementing the direct light term and
  13286. * executed during the build process of directional, point and spot light nodes.
  13287. *
  13288. * @abstract
  13289. * @param {Object} lightData - The light data.
  13290. * @param {NodeBuilder} builder - The current node builder.
  13291. */
  13292. direct( /*lightData, builder*/ ) { }
  13293. /**
  13294. * This method is intended for implementing the direct light term for
  13295. * rect area light nodes.
  13296. *
  13297. * @abstract
  13298. * @param {Object} lightData - The light data.
  13299. * @param {NodeBuilder} builder - The current node builder.
  13300. */
  13301. directRectArea( /*lightData, builder*/ ) {}
  13302. /**
  13303. * This method is intended for implementing the indirect light term.
  13304. *
  13305. * @abstract
  13306. * @param {NodeBuilder} builder - The current node builder.
  13307. */
  13308. indirect( /*builder*/ ) { }
  13309. /**
  13310. * This method is intended for implementing the ambient occlusion term.
  13311. * Unlike other methods, this method must be called manually by the lighting
  13312. * model in its indirect term.
  13313. *
  13314. * @abstract
  13315. * @param {NodeBuilder} builder - The current node builder.
  13316. */
  13317. ambientOcclusion( /*input, stack, builder*/ ) { }
  13318. }
  13319. /**
  13320. * Represents the lighting model for unlit materials. The only light contribution
  13321. * is baked indirect lighting modulated with ambient occlusion and the material's
  13322. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  13323. *
  13324. * @augments LightingModel
  13325. */
  13326. class BasicLightingModel extends LightingModel {
  13327. /**
  13328. * Constructs a new basic lighting model.
  13329. */
  13330. constructor() {
  13331. super();
  13332. }
  13333. /**
  13334. * Implements the baked indirect lighting with its modulation.
  13335. *
  13336. * @param {NodeBuilder} builder - The current node builder.
  13337. */
  13338. indirect( { context } ) {
  13339. const ambientOcclusion = context.ambientOcclusion;
  13340. const reflectedLight = context.reflectedLight;
  13341. const irradianceLightMap = context.irradianceLightMap;
  13342. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  13343. // accumulation (baked indirect lighting only)
  13344. if ( irradianceLightMap ) {
  13345. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  13346. } else {
  13347. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  13348. }
  13349. // modulation
  13350. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13351. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  13352. }
  13353. /**
  13354. * Implements the environment mapping.
  13355. *
  13356. * @param {NodeBuilder} builder - The current node builder.
  13357. */
  13358. finish( builder ) {
  13359. const { material, context } = builder;
  13360. const outgoingLight = context.outgoingLight;
  13361. const envNode = builder.context.environment;
  13362. if ( envNode ) {
  13363. switch ( material.combine ) {
  13364. case MultiplyOperation:
  13365. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  13366. break;
  13367. case MixOperation:
  13368. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  13369. break;
  13370. case AddOperation:
  13371. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  13372. break;
  13373. default:
  13374. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  13375. break;
  13376. }
  13377. }
  13378. }
  13379. }
  13380. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  13381. /**
  13382. * Node material version of {@link MeshBasicMaterial}.
  13383. *
  13384. * @augments NodeMaterial
  13385. */
  13386. class MeshBasicNodeMaterial extends NodeMaterial {
  13387. static get type() {
  13388. return 'MeshBasicNodeMaterial';
  13389. }
  13390. /**
  13391. * Constructs a new mesh basic node material.
  13392. *
  13393. * @param {Object} [parameters] - The configuration parameter.
  13394. */
  13395. constructor( parameters ) {
  13396. super();
  13397. /**
  13398. * This flag can be used for type testing.
  13399. *
  13400. * @type {boolean}
  13401. * @readonly
  13402. * @default true
  13403. */
  13404. this.isMeshBasicNodeMaterial = true;
  13405. /**
  13406. * Although the basic material is by definition unlit, we set
  13407. * this property to `true` since we use a lighting model to compute
  13408. * the outgoing light of the fragment shader.
  13409. *
  13410. * @type {boolean}
  13411. * @default true
  13412. */
  13413. this.lights = true;
  13414. this.setDefaultValues( _defaultValues$9 );
  13415. this.setValues( parameters );
  13416. }
  13417. /**
  13418. * Basic materials are not affected by normal and bump maps so we
  13419. * return by default {@link normalView}.
  13420. *
  13421. * @return {Node<vec3>} The normal node.
  13422. */
  13423. setupNormal() {
  13424. return normalView; // see #28839
  13425. }
  13426. /**
  13427. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13428. * to implement the default environment mapping.
  13429. *
  13430. * @param {NodeBuilder} builder - The current node builder.
  13431. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13432. */
  13433. setupEnvironment( builder ) {
  13434. const envNode = super.setupEnvironment( builder );
  13435. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13436. }
  13437. /**
  13438. * This method must be overwritten since light maps are evaluated
  13439. * with a special scaling factor for basic materials.
  13440. *
  13441. * @param {NodeBuilder} builder - The current node builder.
  13442. * @return {?BasicLightMapNode<vec3>} The light map node.
  13443. */
  13444. setupLightMap( builder ) {
  13445. let node = null;
  13446. if ( builder.material.lightMap ) {
  13447. node = new BasicLightMapNode( materialLightMap );
  13448. }
  13449. return node;
  13450. }
  13451. /**
  13452. * The material overwrites this method because `lights` is set to `true` but
  13453. * we still want to return the diffuse color as the outgoing light.
  13454. *
  13455. * @return {Node<vec3>} The outgoing light node.
  13456. */
  13457. setupOutgoingLight() {
  13458. return diffuseColor.rgb;
  13459. }
  13460. /**
  13461. * Setups the lighting model.
  13462. *
  13463. * @return {BasicLightingModel} The lighting model.
  13464. */
  13465. setupLightingModel() {
  13466. return new BasicLightingModel();
  13467. }
  13468. }
  13469. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  13470. // Original approximation by Christophe Schlick '94
  13471. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  13472. // Optimized variant (presented by Epic at SIGGRAPH '13)
  13473. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  13474. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  13475. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  13476. } ); // validated
  13477. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  13478. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  13479. } ); // validated
  13480. const G_BlinnPhong_Implicit = () => float( 0.25 );
  13481. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  13482. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  13483. } );
  13484. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13485. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13486. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13487. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13488. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  13489. const G = G_BlinnPhong_Implicit();
  13490. const D = D_BlinnPhong( { dotNH } );
  13491. return F.mul( G ).mul( D );
  13492. } );
  13493. /**
  13494. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  13495. *
  13496. * @augments BasicLightingModel
  13497. */
  13498. class PhongLightingModel extends BasicLightingModel {
  13499. /**
  13500. * Constructs a new phong lighting model.
  13501. *
  13502. * @param {boolean} [specular=true] - Whether specular is supported or not.
  13503. */
  13504. constructor( specular = true ) {
  13505. super();
  13506. /**
  13507. * Whether specular is supported or not. Set this to `false` if you are
  13508. * looking for a Lambert-like material meaning a material for non-shiny
  13509. * surfaces, without specular highlights.
  13510. *
  13511. * @type {boolean}
  13512. * @default true
  13513. */
  13514. this.specular = specular;
  13515. }
  13516. /**
  13517. * Implements the direct lighting. The specular portion is optional an can be controlled
  13518. * with the {@link PhongLightingModel#specular} flag.
  13519. *
  13520. * @param {Object} lightData - The light data.
  13521. */
  13522. direct( { lightDirection, lightColor, reflectedLight } ) {
  13523. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13524. const irradiance = dotNL.mul( lightColor );
  13525. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13526. if ( this.specular === true ) {
  13527. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  13528. }
  13529. }
  13530. /**
  13531. * Implements the indirect lighting.
  13532. *
  13533. * @param {NodeBuilder} builder - The current node builder.
  13534. */
  13535. indirect( builder ) {
  13536. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  13537. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13538. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13539. }
  13540. }
  13541. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  13542. /**
  13543. * Node material version of {@link MeshLambertMaterial}.
  13544. *
  13545. * @augments NodeMaterial
  13546. */
  13547. class MeshLambertNodeMaterial extends NodeMaterial {
  13548. static get type() {
  13549. return 'MeshLambertNodeMaterial';
  13550. }
  13551. /**
  13552. * Constructs a new mesh lambert node material.
  13553. *
  13554. * @param {Object} [parameters] - The configuration parameter.
  13555. */
  13556. constructor( parameters ) {
  13557. super();
  13558. /**
  13559. * This flag can be used for type testing.
  13560. *
  13561. * @type {boolean}
  13562. * @readonly
  13563. * @default true
  13564. */
  13565. this.isMeshLambertNodeMaterial = true;
  13566. /**
  13567. * Set to `true` because lambert materials react on lights.
  13568. *
  13569. * @type {boolean}
  13570. * @default true
  13571. */
  13572. this.lights = true;
  13573. this.setDefaultValues( _defaultValues$8 );
  13574. this.setValues( parameters );
  13575. }
  13576. /**
  13577. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13578. * to implement the default environment mapping.
  13579. *
  13580. * @param {NodeBuilder} builder - The current node builder.
  13581. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13582. */
  13583. setupEnvironment( builder ) {
  13584. const envNode = super.setupEnvironment( builder );
  13585. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13586. }
  13587. /**
  13588. * Setups the lighting model.
  13589. *
  13590. * @return {PhongLightingModel} The lighting model.
  13591. */
  13592. setupLightingModel( /*builder*/ ) {
  13593. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13594. }
  13595. }
  13596. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13597. /**
  13598. * Node material version of {@link MeshPhongMaterial}.
  13599. *
  13600. * @augments NodeMaterial
  13601. */
  13602. class MeshPhongNodeMaterial extends NodeMaterial {
  13603. static get type() {
  13604. return 'MeshPhongNodeMaterial';
  13605. }
  13606. /**
  13607. * Constructs a new mesh lambert node material.
  13608. *
  13609. * @param {Object} [parameters] - The configuration parameter.
  13610. */
  13611. constructor( parameters ) {
  13612. super();
  13613. /**
  13614. * This flag can be used for type testing.
  13615. *
  13616. * @type {boolean}
  13617. * @readonly
  13618. * @default true
  13619. */
  13620. this.isMeshPhongNodeMaterial = true;
  13621. /**
  13622. * Set to `true` because phong materials react on lights.
  13623. *
  13624. * @type {boolean}
  13625. * @default true
  13626. */
  13627. this.lights = true;
  13628. /**
  13629. * The shininess of phong materials is by default inferred from the `shininess`
  13630. * property. This node property allows to overwrite the default
  13631. * and define the shininess with a node instead.
  13632. *
  13633. * If you don't want to overwrite the shininess but modify the existing
  13634. * value instead, use {@link materialShininess}.
  13635. *
  13636. * @type {?Node<float>}
  13637. * @default null
  13638. */
  13639. this.shininessNode = null;
  13640. /**
  13641. * The specular color of phong materials is by default inferred from the
  13642. * `specular` property. This node property allows to overwrite the default
  13643. * and define the specular color with a node instead.
  13644. *
  13645. * If you don't want to overwrite the specular color but modify the existing
  13646. * value instead, use {@link materialSpecular}.
  13647. *
  13648. * @type {?Node<vec3>}
  13649. * @default null
  13650. */
  13651. this.specularNode = null;
  13652. this.setDefaultValues( _defaultValues$7 );
  13653. this.setValues( parameters );
  13654. }
  13655. /**
  13656. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13657. * to implement the default environment mapping.
  13658. *
  13659. * @param {NodeBuilder} builder - The current node builder.
  13660. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13661. */
  13662. setupEnvironment( builder ) {
  13663. const envNode = super.setupEnvironment( builder );
  13664. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13665. }
  13666. /**
  13667. * Setups the lighting model.
  13668. *
  13669. * @return {PhongLightingModel} The lighting model.
  13670. */
  13671. setupLightingModel( /*builder*/ ) {
  13672. return new PhongLightingModel();
  13673. }
  13674. /**
  13675. * Setups the phong specific node variables.
  13676. *
  13677. * @param {NodeBuilder} builder - The current node builder.
  13678. */
  13679. setupVariants( /*builder*/ ) {
  13680. // SHININESS
  13681. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13682. shininess.assign( shininessNode );
  13683. // SPECULAR COLOR
  13684. const specularNode = this.specularNode || materialSpecular;
  13685. specularColor.assign( specularNode );
  13686. }
  13687. copy( source ) {
  13688. this.shininessNode = source.shininessNode;
  13689. this.specularNode = source.specularNode;
  13690. return super.copy( source );
  13691. }
  13692. }
  13693. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13694. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13695. return float( 0 );
  13696. }
  13697. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13698. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13699. return geometryRoughness;
  13700. } );
  13701. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13702. const { roughness } = inputs;
  13703. const geometryRoughness = getGeometryRoughness();
  13704. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13705. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13706. roughnessFactor = roughnessFactor.min( 1.0 );
  13707. return roughnessFactor;
  13708. } );
  13709. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13710. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13711. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13712. const a2 = alpha.pow2();
  13713. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13714. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13715. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13716. } ).setLayout( {
  13717. name: 'V_GGX_SmithCorrelated',
  13718. type: 'float',
  13719. inputs: [
  13720. { name: 'alpha', type: 'float' },
  13721. { name: 'dotNL', type: 'float' },
  13722. { name: 'dotNV', type: 'float' }
  13723. ]
  13724. } ); // validated
  13725. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13726. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13727. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13728. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13729. const v = div( 0.5, gv.add( gl ) );
  13730. return v.saturate();
  13731. } ).setLayout( {
  13732. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13733. type: 'float',
  13734. inputs: [
  13735. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13736. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13737. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13738. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13739. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13740. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13741. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13742. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13743. ]
  13744. } );
  13745. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13746. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13747. // alpha is "roughness squared" in Disney’s reparameterization
  13748. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13749. const a2 = alpha.pow2();
  13750. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13751. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13752. } ).setLayout( {
  13753. name: 'D_GGX',
  13754. type: 'float',
  13755. inputs: [
  13756. { name: 'alpha', type: 'float' },
  13757. { name: 'dotNH', type: 'float' }
  13758. ]
  13759. } ); // validated
  13760. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13761. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13762. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13763. const a2 = alphaT.mul( alphaB );
  13764. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13765. const v2 = v.dot( v );
  13766. const w2 = a2.div( v2 );
  13767. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13768. } ).setLayout( {
  13769. name: 'D_GGX_Anisotropic',
  13770. type: 'float',
  13771. inputs: [
  13772. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13773. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13774. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13775. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13776. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13777. ]
  13778. } );
  13779. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13780. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13781. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13782. const normalView = inputs.normalView || transformedNormalView;
  13783. const alpha = roughness.pow2(); // UE4's roughness
  13784. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13785. const dotNL = normalView.dot( lightDirection ).clamp();
  13786. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13787. const dotNH = normalView.dot( halfDir ).clamp();
  13788. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13789. let F = F_Schlick( { f0, f90, dotVH } );
  13790. let V, D;
  13791. if ( defined( USE_IRIDESCENCE ) ) {
  13792. F = iridescence.mix( F, f );
  13793. }
  13794. if ( defined( USE_ANISOTROPY ) ) {
  13795. const dotTL = anisotropyT.dot( lightDirection );
  13796. const dotTV = anisotropyT.dot( positionViewDirection );
  13797. const dotTH = anisotropyT.dot( halfDir );
  13798. const dotBL = anisotropyB.dot( lightDirection );
  13799. const dotBV = anisotropyB.dot( positionViewDirection );
  13800. const dotBH = anisotropyB.dot( halfDir );
  13801. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13802. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13803. } else {
  13804. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13805. D = D_GGX( { alpha, dotNH } );
  13806. }
  13807. return F.mul( V ).mul( D );
  13808. } ); // validated
  13809. // Analytical approximation of the DFG LUT, one half of the
  13810. // split-sum approximation used in indirect specular lighting.
  13811. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13812. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13813. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13814. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13815. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13816. const r = roughness.mul( c0 ).add( c1 );
  13817. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13818. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13819. return fab;
  13820. } ).setLayout( {
  13821. name: 'DFGApprox',
  13822. type: 'vec2',
  13823. inputs: [
  13824. { name: 'roughness', type: 'float' },
  13825. { name: 'dotNV', type: 'vec3' }
  13826. ]
  13827. } );
  13828. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13829. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13830. const fab = DFGApprox( { dotNV, roughness } );
  13831. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13832. } );
  13833. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13834. const x = dotVH.oneMinus().saturate();
  13835. const x2 = x.mul( x );
  13836. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13837. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13838. } ).setLayout( {
  13839. name: 'Schlick_to_F0',
  13840. type: 'vec3',
  13841. inputs: [
  13842. { name: 'f', type: 'vec3' },
  13843. { name: 'f90', type: 'float' },
  13844. { name: 'dotVH', type: 'float' }
  13845. ]
  13846. } );
  13847. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13848. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13849. const alpha = roughness.pow2();
  13850. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13851. const invAlpha = float( 1.0 ).div( alpha );
  13852. const cos2h = dotNH.pow2();
  13853. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13854. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13855. } ).setLayout( {
  13856. name: 'D_Charlie',
  13857. type: 'float',
  13858. inputs: [
  13859. { name: 'roughness', type: 'float' },
  13860. { name: 'dotNH', type: 'float' }
  13861. ]
  13862. } );
  13863. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13864. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13865. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13866. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13867. } ).setLayout( {
  13868. name: 'V_Neubelt',
  13869. type: 'float',
  13870. inputs: [
  13871. { name: 'dotNV', type: 'float' },
  13872. { name: 'dotNL', type: 'float' }
  13873. ]
  13874. } );
  13875. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13876. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13877. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13878. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13879. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13880. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13881. const V = V_Neubelt( { dotNV, dotNL } );
  13882. return sheen.mul( D ).mul( V );
  13883. } );
  13884. // Rect Area Light
  13885. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13886. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13887. // code: https://github.com/selfshadow/ltc_code/
  13888. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13889. const LUT_SIZE = 64.0;
  13890. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13891. const LUT_BIAS = 0.5 / LUT_SIZE;
  13892. const dotNV = N.dot( V ).saturate();
  13893. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13894. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13895. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13896. return uv;
  13897. } ).setLayout( {
  13898. name: 'LTC_Uv',
  13899. type: 'vec2',
  13900. inputs: [
  13901. { name: 'N', type: 'vec3' },
  13902. { name: 'V', type: 'vec3' },
  13903. { name: 'roughness', type: 'float' }
  13904. ]
  13905. } );
  13906. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13907. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13908. // An approximation of the form factor of a horizon-clipped rectangle.
  13909. const l = f.length();
  13910. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13911. } ).setLayout( {
  13912. name: 'LTC_ClippedSphereFormFactor',
  13913. type: 'float',
  13914. inputs: [
  13915. { name: 'f', type: 'vec3' }
  13916. ]
  13917. } );
  13918. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13919. const x = v1.dot( v2 );
  13920. const y = x.abs().toVar();
  13921. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13922. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13923. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13924. const v = a.div( b );
  13925. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13926. return v1.cross( v2 ).mul( theta_sintheta );
  13927. } ).setLayout( {
  13928. name: 'LTC_EdgeVectorFormFactor',
  13929. type: 'vec3',
  13930. inputs: [
  13931. { name: 'v1', type: 'vec3' },
  13932. { name: 'v2', type: 'vec3' }
  13933. ]
  13934. } );
  13935. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13936. // bail if point is on back side of plane of light
  13937. // assumes ccw winding order of light vertices
  13938. const v1 = p1.sub( p0 ).toVar();
  13939. const v2 = p3.sub( p0 ).toVar();
  13940. const lightNormal = v1.cross( v2 );
  13941. const result = vec3().toVar();
  13942. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13943. // construct orthonormal basis around N
  13944. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13945. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13946. // compute transform
  13947. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13948. // transform rect
  13949. // & project rect onto sphere
  13950. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13951. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13952. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13953. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13954. // calculate vector form factor
  13955. const vectorFormFactor = vec3( 0 ).toVar();
  13956. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13957. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13958. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13959. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13960. // adjust for horizon clipping
  13961. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13962. } );
  13963. return result;
  13964. } ).setLayout( {
  13965. name: 'LTC_Evaluate',
  13966. type: 'vec3',
  13967. inputs: [
  13968. { name: 'N', type: 'vec3' },
  13969. { name: 'V', type: 'vec3' },
  13970. { name: 'P', type: 'vec3' },
  13971. { name: 'mInv', type: 'mat3' },
  13972. { name: 'p0', type: 'vec3' },
  13973. { name: 'p1', type: 'vec3' },
  13974. { name: 'p2', type: 'vec3' },
  13975. { name: 'p3', type: 'vec3' }
  13976. ]
  13977. } );
  13978. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  13979. // bail if point is on back side of plane of light
  13980. // assumes ccw winding order of light vertices
  13981. const v1 = p1.sub( p0 ).toVar();
  13982. const v2 = p3.sub( p0 ).toVar();
  13983. const lightNormal = v1.cross( v2 );
  13984. const result = vec3().toVar();
  13985. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13986. // transform rect
  13987. // & project rect onto sphere
  13988. const coords0 = p0.sub( P ).normalize().toVar();
  13989. const coords1 = p1.sub( P ).normalize().toVar();
  13990. const coords2 = p2.sub( P ).normalize().toVar();
  13991. const coords3 = p3.sub( P ).normalize().toVar();
  13992. // calculate vector form factor
  13993. const vectorFormFactor = vec3( 0 ).toVar();
  13994. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13995. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13996. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13997. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13998. // adjust for horizon clipping
  13999. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  14000. } );
  14001. return result;
  14002. } ).setLayout( {
  14003. name: 'LTC_Evaluate',
  14004. type: 'vec3',
  14005. inputs: [
  14006. { name: 'P', type: 'vec3' },
  14007. { name: 'p0', type: 'vec3' },
  14008. { name: 'p1', type: 'vec3' },
  14009. { name: 'p2', type: 'vec3' },
  14010. { name: 'p3', type: 'vec3' }
  14011. ]
  14012. } );
  14013. // Mipped Bicubic Texture Filtering by N8
  14014. // https://www.shadertoy.com/view/Dl2SDW
  14015. const bC = 1.0 / 6.0;
  14016. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  14017. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  14018. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  14019. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  14020. const g0 = ( a ) => w0( a ).add( w1( a ) );
  14021. const g1 = ( a ) => w2( a ).add( w3( a ) );
  14022. // h0 and h1 are the two offset functions
  14023. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  14024. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  14025. const bicubic = ( textureNode, texelSize, lod ) => {
  14026. const uv = textureNode.uvNode;
  14027. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  14028. const iuv = floor( uvScaled );
  14029. const fuv = fract( uvScaled );
  14030. const g0x = g0( fuv.x );
  14031. const g1x = g1( fuv.x );
  14032. const h0x = h0( fuv.x );
  14033. const h1x = h1( fuv.x );
  14034. const h0y = h0( fuv.y );
  14035. const h1y = h1( fuv.y );
  14036. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14037. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14038. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14039. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14040. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  14041. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  14042. return a.add( b );
  14043. };
  14044. /**
  14045. * Applies mipped bicubic texture filtering to the given texture node.
  14046. *
  14047. * @tsl
  14048. * @function
  14049. * @param {TextureNode} textureNode - The texture node that should be filtered.
  14050. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  14051. * @return {Node} The filtered texture sample.
  14052. */
  14053. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  14054. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  14055. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  14056. const fLodSizeInv = div( 1.0, fLodSize );
  14057. const cLodSizeInv = div( 1.0, cLodSize );
  14058. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  14059. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  14060. return fract( lodNode ).mix( fSample, cSample );
  14061. } );
  14062. //
  14063. // Transmission
  14064. //
  14065. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  14066. // Direction of refracted light.
  14067. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  14068. // Compute rotation-independent scaling of the model matrix.
  14069. const modelScale = vec3(
  14070. length( modelMatrix[ 0 ].xyz ),
  14071. length( modelMatrix[ 1 ].xyz ),
  14072. length( modelMatrix[ 2 ].xyz )
  14073. );
  14074. // The thickness is specified in local space.
  14075. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  14076. } ).setLayout( {
  14077. name: 'getVolumeTransmissionRay',
  14078. type: 'vec3',
  14079. inputs: [
  14080. { name: 'n', type: 'vec3' },
  14081. { name: 'v', type: 'vec3' },
  14082. { name: 'thickness', type: 'float' },
  14083. { name: 'ior', type: 'float' },
  14084. { name: 'modelMatrix', type: 'mat4' }
  14085. ]
  14086. } );
  14087. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  14088. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  14089. // an IOR of 1.5 results in the default amount of microfacet refraction.
  14090. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  14091. } ).setLayout( {
  14092. name: 'applyIorToRoughness',
  14093. type: 'float',
  14094. inputs: [
  14095. { name: 'roughness', type: 'float' },
  14096. { name: 'ior', type: 'float' }
  14097. ]
  14098. } );
  14099. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  14100. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  14101. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  14102. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  14103. const transmissionSample = vTexture.sample( fragCoord );
  14104. //const transmissionSample = viewportMipTexture( fragCoord );
  14105. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  14106. return textureBicubic( transmissionSample, lod );
  14107. } );
  14108. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  14109. If( attenuationDistance.notEqual( 0 ), () => {
  14110. // Compute light attenuation using Beer's law.
  14111. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  14112. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  14113. return transmittance;
  14114. } );
  14115. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  14116. return vec3( 1.0 );
  14117. } ).setLayout( {
  14118. name: 'volumeAttenuation',
  14119. type: 'vec3',
  14120. inputs: [
  14121. { name: 'transmissionDistance', type: 'float' },
  14122. { name: 'attenuationColor', type: 'vec3' },
  14123. { name: 'attenuationDistance', type: 'float' }
  14124. ]
  14125. } );
  14126. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  14127. let transmittedLight, transmittance;
  14128. if ( dispersion ) {
  14129. transmittedLight = vec4().toVar();
  14130. transmittance = vec3().toVar();
  14131. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  14132. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  14133. Loop( { start: 0, end: 3 }, ( { i } ) => {
  14134. const ior = iors.element( i );
  14135. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  14136. const refractedRayExit = position.add( transmissionRay );
  14137. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  14138. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  14139. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  14140. refractionCoords.addAssign( 1.0 );
  14141. refractionCoords.divAssign( 2.0 );
  14142. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  14143. // Sample framebuffer to get pixel the refracted ray hits.
  14144. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  14145. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  14146. transmittedLight.a.addAssign( transmissionSample.a );
  14147. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  14148. } );
  14149. transmittedLight.a.divAssign( 3.0 );
  14150. } else {
  14151. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  14152. const refractedRayExit = position.add( transmissionRay );
  14153. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  14154. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  14155. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  14156. refractionCoords.addAssign( 1.0 );
  14157. refractionCoords.divAssign( 2.0 );
  14158. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  14159. // Sample framebuffer to get pixel the refracted ray hits.
  14160. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  14161. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  14162. }
  14163. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  14164. const dotNV = n.dot( v ).clamp();
  14165. // Get the specular component.
  14166. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  14167. dotNV,
  14168. specularColor,
  14169. specularF90,
  14170. roughness
  14171. } ) );
  14172. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  14173. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  14174. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  14175. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  14176. } );
  14177. //
  14178. // Iridescence
  14179. //
  14180. // XYZ to linear-sRGB color space
  14181. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  14182. 3.2404542, - 0.9692660, 0.0556434,
  14183. - 1.5371385, 1.8760108, - 0.2040259,
  14184. - 0.4985314, 0.0415560, 1.0572252
  14185. );
  14186. // Assume air interface for top
  14187. // Note: We don't handle the case fresnel0 == 1
  14188. const Fresnel0ToIor = ( fresnel0 ) => {
  14189. const sqrtF0 = fresnel0.sqrt();
  14190. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  14191. };
  14192. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  14193. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  14194. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  14195. };
  14196. // Fresnel equations for dielectric/dielectric interfaces.
  14197. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  14198. // Evaluation XYZ sensitivity curves in Fourier space
  14199. const evalSensitivity = ( OPD, shift ) => {
  14200. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  14201. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  14202. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  14203. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  14204. 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( - 4.5282e+09 ).exp() );
  14205. 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() );
  14206. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  14207. const rgb = XYZ_TO_REC709.mul( xyz );
  14208. return rgb;
  14209. };
  14210. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  14211. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  14212. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  14213. // Evaluate the cosTheta on the base layer (Snell law)
  14214. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  14215. // Handle TIR:
  14216. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  14217. If( cosTheta2Sq.lessThan( 0 ), () => {
  14218. return vec3( 1.0 );
  14219. } );
  14220. const cosTheta2 = cosTheta2Sq.sqrt();
  14221. // First interface
  14222. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  14223. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  14224. //const R21 = R12;
  14225. const T121 = R12.oneMinus();
  14226. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  14227. const phi21 = float( Math.PI ).sub( phi12 );
  14228. // Second interface
  14229. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  14230. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  14231. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  14232. const phi23 = vec3(
  14233. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14234. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14235. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  14236. );
  14237. // Phase shift
  14238. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  14239. const phi = vec3( phi21 ).add( phi23 );
  14240. // Compound terms
  14241. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  14242. const r123 = R123.sqrt();
  14243. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  14244. // Reflectance term for m = 0 (DC term amplitude)
  14245. const C0 = R12.add( Rs );
  14246. const I = C0.toVar();
  14247. // Reflectance term for m > 0 (pairs of diracs)
  14248. const Cm = Rs.sub( T121 ).toVar();
  14249. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  14250. Cm.mulAssign( r123 );
  14251. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  14252. I.addAssign( Cm.mul( Sm ) );
  14253. } );
  14254. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  14255. return I.max( vec3( 0.0 ) );
  14256. } ).setLayout( {
  14257. name: 'evalIridescence',
  14258. type: 'vec3',
  14259. inputs: [
  14260. { name: 'outsideIOR', type: 'float' },
  14261. { name: 'eta2', type: 'float' },
  14262. { name: 'cosTheta1', type: 'float' },
  14263. { name: 'thinFilmThickness', type: 'float' },
  14264. { name: 'baseF0', type: 'vec3' }
  14265. ]
  14266. } );
  14267. //
  14268. // Sheen
  14269. //
  14270. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  14271. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  14272. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  14273. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  14274. const dotNV = normal.dot( viewDir ).saturate();
  14275. const r2 = roughness.pow2();
  14276. const a = select(
  14277. roughness.lessThan( 0.25 ),
  14278. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  14279. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  14280. );
  14281. const b = select(
  14282. roughness.lessThan( 0.25 ),
  14283. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  14284. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  14285. );
  14286. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  14287. return DG.mul( 1.0 / Math.PI ).saturate();
  14288. } );
  14289. const clearcoatF0 = vec3( 0.04 );
  14290. const clearcoatF90 = float( 1 );
  14291. /**
  14292. * Represents the lighting model for a PBR material.
  14293. *
  14294. * @augments LightingModel
  14295. */
  14296. class PhysicalLightingModel extends LightingModel {
  14297. /**
  14298. * Constructs a new physical lighting model.
  14299. *
  14300. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  14301. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  14302. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  14303. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  14304. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  14305. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  14306. */
  14307. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  14308. super();
  14309. /**
  14310. * Whether clearcoat is supported or not.
  14311. *
  14312. * @type {boolean}
  14313. * @default false
  14314. */
  14315. this.clearcoat = clearcoat;
  14316. /**
  14317. * Whether sheen is supported or not.
  14318. *
  14319. * @type {boolean}
  14320. * @default false
  14321. */
  14322. this.sheen = sheen;
  14323. /**
  14324. * Whether iridescence is supported or not.
  14325. *
  14326. * @type {boolean}
  14327. * @default false
  14328. */
  14329. this.iridescence = iridescence;
  14330. /**
  14331. * Whether anisotropy is supported or not.
  14332. *
  14333. * @type {boolean}
  14334. * @default false
  14335. */
  14336. this.anisotropy = anisotropy;
  14337. /**
  14338. * Whether transmission is supported or not.
  14339. *
  14340. * @type {boolean}
  14341. * @default false
  14342. */
  14343. this.transmission = transmission;
  14344. /**
  14345. * Whether dispersion is supported or not.
  14346. *
  14347. * @type {boolean}
  14348. * @default false
  14349. */
  14350. this.dispersion = dispersion;
  14351. /**
  14352. * The clear coat radiance.
  14353. *
  14354. * @type {?Node}
  14355. * @default null
  14356. */
  14357. this.clearcoatRadiance = null;
  14358. /**
  14359. * The clear coat specular direct.
  14360. *
  14361. * @type {?Node}
  14362. * @default null
  14363. */
  14364. this.clearcoatSpecularDirect = null;
  14365. /**
  14366. * The clear coat specular indirect.
  14367. *
  14368. * @type {?Node}
  14369. * @default null
  14370. */
  14371. this.clearcoatSpecularIndirect = null;
  14372. /**
  14373. * The sheen specular direct.
  14374. *
  14375. * @type {?Node}
  14376. * @default null
  14377. */
  14378. this.sheenSpecularDirect = null;
  14379. /**
  14380. * The sheen specular indirect.
  14381. *
  14382. * @type {?Node}
  14383. * @default null
  14384. */
  14385. this.sheenSpecularIndirect = null;
  14386. /**
  14387. * The iridescence Fresnel.
  14388. *
  14389. * @type {?Node}
  14390. * @default null
  14391. */
  14392. this.iridescenceFresnel = null;
  14393. /**
  14394. * The iridescence F0.
  14395. *
  14396. * @type {?Node}
  14397. * @default null
  14398. */
  14399. this.iridescenceF0 = null;
  14400. }
  14401. /**
  14402. * Depending on what features are requested, the method prepares certain node variables
  14403. * which are later used for lighting computations.
  14404. *
  14405. * @param {NodeBuilder} builder - The current node builder.
  14406. */
  14407. start( builder ) {
  14408. if ( this.clearcoat === true ) {
  14409. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  14410. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  14411. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  14412. }
  14413. if ( this.sheen === true ) {
  14414. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  14415. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  14416. }
  14417. if ( this.iridescence === true ) {
  14418. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  14419. this.iridescenceFresnel = evalIridescence( {
  14420. outsideIOR: float( 1.0 ),
  14421. eta2: iridescenceIOR,
  14422. cosTheta1: dotNVi,
  14423. thinFilmThickness: iridescenceThickness,
  14424. baseF0: specularColor
  14425. } );
  14426. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  14427. }
  14428. if ( this.transmission === true ) {
  14429. const position = positionWorld;
  14430. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  14431. const n = transformedNormalWorld;
  14432. const context = builder.context;
  14433. context.backdrop = getIBLVolumeRefraction(
  14434. n,
  14435. v,
  14436. roughness,
  14437. diffuseColor,
  14438. specularColor,
  14439. specularF90, // specularF90
  14440. position, // positionWorld
  14441. modelWorldMatrix, // modelMatrix
  14442. cameraViewMatrix, // viewMatrix
  14443. cameraProjectionMatrix, // projMatrix
  14444. ior,
  14445. thickness,
  14446. attenuationColor,
  14447. attenuationDistance,
  14448. this.dispersion ? dispersion : null
  14449. );
  14450. context.backdropAlpha = transmission;
  14451. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  14452. }
  14453. super.start( builder );
  14454. }
  14455. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  14456. // Approximates multi-scattering in order to preserve energy.
  14457. // http://www.jcgt.org/published/0008/01/03/
  14458. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  14459. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14460. const fab = DFGApprox( { roughness, dotNV } );
  14461. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  14462. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14463. const Ess = fab.x.add( fab.y );
  14464. const Ems = Ess.oneMinus();
  14465. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  14466. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  14467. singleScatter.addAssign( FssEss );
  14468. multiScatter.addAssign( Fms.mul( Ems ) );
  14469. }
  14470. /**
  14471. * Implements the direct light.
  14472. *
  14473. * @param {Object} lightData - The light data.
  14474. * @param {NodeBuilder} builder - The current node builder.
  14475. */
  14476. direct( { lightDirection, lightColor, reflectedLight } ) {
  14477. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14478. const irradiance = dotNL.mul( lightColor );
  14479. if ( this.sheen === true ) {
  14480. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  14481. }
  14482. if ( this.clearcoat === true ) {
  14483. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  14484. const ccIrradiance = dotNLcc.mul( lightColor );
  14485. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  14486. }
  14487. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14488. 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 } ) ) );
  14489. }
  14490. /**
  14491. * This method is intended for implementing the direct light term for
  14492. * rect area light nodes.
  14493. *
  14494. * @param {Object} input - The input data.
  14495. * @param {NodeBuilder} builder - The current node builder.
  14496. */
  14497. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  14498. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  14499. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  14500. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  14501. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  14502. const N = transformedNormalView;
  14503. const V = positionViewDirection;
  14504. const P = positionView.toVar();
  14505. const uv = LTC_Uv( { N, V, roughness } );
  14506. const t1 = ltc_1.sample( uv ).toVar();
  14507. const t2 = ltc_2.sample( uv ).toVar();
  14508. const mInv = mat3(
  14509. vec3( t1.x, 0, t1.y ),
  14510. vec3( 0, 1, 0 ),
  14511. vec3( t1.z, 0, t1.w )
  14512. ).toVar();
  14513. // LTC Fresnel Approximation by Stephen Hill
  14514. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  14515. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  14516. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  14517. 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 } ) ) );
  14518. }
  14519. /**
  14520. * Implements the indirect lighting.
  14521. *
  14522. * @param {NodeBuilder} builder - The current node builder.
  14523. */
  14524. indirect( builder ) {
  14525. this.indirectDiffuse( builder );
  14526. this.indirectSpecular( builder );
  14527. this.ambientOcclusion( builder );
  14528. }
  14529. /**
  14530. * Implements the indirect diffuse term.
  14531. *
  14532. * @param {NodeBuilder} builder - The current node builder.
  14533. */
  14534. indirectDiffuse( builder ) {
  14535. const { irradiance, reflectedLight } = builder.context;
  14536. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14537. }
  14538. /**
  14539. * Implements the indirect specular term.
  14540. *
  14541. * @param {NodeBuilder} builder - The current node builder.
  14542. */
  14543. indirectSpecular( builder ) {
  14544. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  14545. if ( this.sheen === true ) {
  14546. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  14547. sheen,
  14548. IBLSheenBRDF( {
  14549. normal: transformedNormalView,
  14550. viewDir: positionViewDirection,
  14551. roughness: sheenRoughness
  14552. } )
  14553. ) );
  14554. }
  14555. if ( this.clearcoat === true ) {
  14556. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14557. const clearcoatEnv = EnvironmentBRDF( {
  14558. dotNV: dotNVcc,
  14559. specularColor: clearcoatF0,
  14560. specularF90: clearcoatF90,
  14561. roughness: clearcoatRoughness
  14562. } );
  14563. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  14564. }
  14565. // Both indirect specular and indirect diffuse light accumulate here
  14566. const singleScattering = vec3().toVar( 'singleScattering' );
  14567. const multiScattering = vec3().toVar( 'multiScattering' );
  14568. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  14569. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  14570. const totalScattering = singleScattering.add( multiScattering );
  14571. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  14572. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  14573. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  14574. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  14575. }
  14576. /**
  14577. * Implements the ambient occlusion term.
  14578. *
  14579. * @param {NodeBuilder} builder - The current node builder.
  14580. */
  14581. ambientOcclusion( builder ) {
  14582. const { ambientOcclusion, reflectedLight } = builder.context;
  14583. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14584. const aoNV = dotNV.add( ambientOcclusion );
  14585. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  14586. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  14587. if ( this.clearcoat === true ) {
  14588. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  14589. }
  14590. if ( this.sheen === true ) {
  14591. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  14592. }
  14593. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14594. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14595. }
  14596. /**
  14597. * Used for final lighting accumulations depending on the requested features.
  14598. *
  14599. * @param {NodeBuilder} builder - The current node builder.
  14600. */
  14601. finish( { context } ) {
  14602. const { outgoingLight } = context;
  14603. if ( this.clearcoat === true ) {
  14604. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14605. const Fcc = F_Schlick( {
  14606. dotVH: dotNVcc,
  14607. f0: clearcoatF0,
  14608. f90: clearcoatF90
  14609. } );
  14610. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14611. outgoingLight.assign( clearcoatLight );
  14612. }
  14613. if ( this.sheen === true ) {
  14614. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14615. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14616. outgoingLight.assign( sheenLight );
  14617. }
  14618. }
  14619. }
  14620. // These defines must match with PMREMGenerator
  14621. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14622. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  14623. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14624. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  14625. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14626. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14627. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14628. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14629. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14630. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14631. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14632. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14633. // These shader functions convert between the UV coordinates of a single face of
  14634. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14635. // sampling a textureCube (not generally normalized ).
  14636. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14637. const absDirection = vec3( abs( direction ) ).toVar();
  14638. const face = float( - 1.0 ).toVar();
  14639. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14640. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14641. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14642. } ).Else( () => {
  14643. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14644. } );
  14645. } ).Else( () => {
  14646. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14647. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14648. } ).Else( () => {
  14649. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14650. } );
  14651. } );
  14652. return face;
  14653. } ).setLayout( {
  14654. name: 'getFace',
  14655. type: 'float',
  14656. inputs: [
  14657. { name: 'direction', type: 'vec3' }
  14658. ]
  14659. } );
  14660. // RH coordinate system; PMREM face-indexing convention
  14661. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14662. const uv = vec2().toVar();
  14663. If( face.equal( 0.0 ), () => {
  14664. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14665. } ).ElseIf( face.equal( 1.0 ), () => {
  14666. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14667. } ).ElseIf( face.equal( 2.0 ), () => {
  14668. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14669. } ).ElseIf( face.equal( 3.0 ), () => {
  14670. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14671. } ).ElseIf( face.equal( 4.0 ), () => {
  14672. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14673. } ).Else( () => {
  14674. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14675. } );
  14676. return mul( 0.5, uv.add( 1.0 ) );
  14677. } ).setLayout( {
  14678. name: 'getUV',
  14679. type: 'vec2',
  14680. inputs: [
  14681. { name: 'direction', type: 'vec3' },
  14682. { name: 'face', type: 'float' }
  14683. ]
  14684. } );
  14685. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14686. const mip = float( 0.0 ).toVar();
  14687. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14688. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14689. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14690. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14691. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14692. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14693. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14694. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14695. } ).Else( () => {
  14696. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14697. } );
  14698. return mip;
  14699. } ).setLayout( {
  14700. name: 'roughnessToMip',
  14701. type: 'float',
  14702. inputs: [
  14703. { name: 'roughness', type: 'float' }
  14704. ]
  14705. } );
  14706. // RH coordinate system; PMREM face-indexing convention
  14707. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14708. const uv = uv_immutable.toVar();
  14709. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14710. const direction = vec3( uv, 1.0 ).toVar();
  14711. If( face.equal( 0.0 ), () => {
  14712. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14713. } ).ElseIf( face.equal( 1.0 ), () => {
  14714. direction.assign( direction.xzy );
  14715. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14716. } ).ElseIf( face.equal( 2.0 ), () => {
  14717. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14718. } ).ElseIf( face.equal( 3.0 ), () => {
  14719. direction.assign( direction.zyx );
  14720. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14721. } ).ElseIf( face.equal( 4.0 ), () => {
  14722. direction.assign( direction.xzy );
  14723. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14724. } ).ElseIf( face.equal( 5.0 ), () => {
  14725. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14726. } );
  14727. return direction;
  14728. } ).setLayout( {
  14729. name: 'getDirection',
  14730. type: 'vec3',
  14731. inputs: [
  14732. { name: 'uv', type: 'vec2' },
  14733. { name: 'face', type: 'float' }
  14734. ]
  14735. } );
  14736. //
  14737. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14738. const roughness = float( roughness_immutable );
  14739. const sampleDir = vec3( sampleDir_immutable );
  14740. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14741. const mipF = fract( mip );
  14742. const mipInt = floor( mip );
  14743. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14744. If( mipF.notEqual( 0.0 ), () => {
  14745. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14746. color0.assign( mix( color0, color1, mipF ) );
  14747. } );
  14748. return color0;
  14749. } );
  14750. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14751. const mipInt = float( mipInt_immutable ).toVar();
  14752. const direction = vec3( direction_immutable );
  14753. const face = float( getFace( direction ) ).toVar();
  14754. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14755. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14756. const faceSize = float( exp2( mipInt ) ).toVar();
  14757. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14758. If( face.greaterThan( 2.0 ), () => {
  14759. uv.y.addAssign( faceSize );
  14760. face.subAssign( 3.0 );
  14761. } );
  14762. uv.x.addAssign( face.mul( faceSize ) );
  14763. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14764. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14765. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14766. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14767. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14768. } );
  14769. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14770. const cosTheta = cos( theta );
  14771. // Rodrigues' axis-angle rotation
  14772. const sampleDirection = outputDirection.mul( cosTheta )
  14773. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14774. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14775. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14776. } );
  14777. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14778. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14779. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14780. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14781. } );
  14782. axis.assign( normalize( axis ) );
  14783. const gl_FragColor = vec3().toVar();
  14784. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14785. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14786. If( i.greaterThanEqual( samples ), () => {
  14787. Break();
  14788. } );
  14789. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14790. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14791. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14792. } );
  14793. return vec4( gl_FragColor, 1 );
  14794. } );
  14795. const LOD_MIN = 4;
  14796. // The standard deviations (radians) associated with the extra mips. These are
  14797. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14798. // geometric shadowing function. These sigma values squared must match the
  14799. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  14800. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  14801. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  14802. // samples and exit early, but not recompile the shader.
  14803. const MAX_SAMPLES = 20;
  14804. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14805. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  14806. const _clearColor$2 = /*@__PURE__*/ new Color();
  14807. let _oldTarget = null;
  14808. let _oldActiveCubeFace = 0;
  14809. let _oldActiveMipmapLevel = 0;
  14810. // Golden Ratio
  14811. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  14812. const INV_PHI = 1 / PHI;
  14813. // Vertices of a dodecahedron (except the opposites, which represent the
  14814. // same axis), used as axis directions evenly spread on a sphere.
  14815. const _axisDirections = [
  14816. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  14817. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  14818. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  14819. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  14820. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  14821. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  14822. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  14823. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  14824. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  14825. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  14826. ];
  14827. const _origin = /*@__PURE__*/ new Vector3();
  14828. // maps blur materials to their uniforms dictionary
  14829. const _uniformsMap = new WeakMap();
  14830. // WebGPU Face indices
  14831. const _faceLib = [
  14832. 3, 1, 5,
  14833. 0, 4, 2
  14834. ];
  14835. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  14836. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  14837. /**
  14838. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  14839. * (PMREM) from a cubeMap environment texture. This allows different levels of
  14840. * blur to be quickly accessed based on material roughness. It is packed into a
  14841. * special CubeUV format that allows us to perform custom interpolation so that
  14842. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  14843. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  14844. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  14845. * higher roughness levels. In this way we maintain resolution to smoothly
  14846. * interpolate diffuse lighting while limiting sampling computation.
  14847. *
  14848. * Paper: Fast, Accurate Image-Based Lighting:
  14849. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  14850. */
  14851. class PMREMGenerator {
  14852. /**
  14853. * Constructs a new PMREM generator.
  14854. *
  14855. * @param {Renderer} renderer - The renderer.
  14856. */
  14857. constructor( renderer ) {
  14858. this._renderer = renderer;
  14859. this._pingPongRenderTarget = null;
  14860. this._lodMax = 0;
  14861. this._cubeSize = 0;
  14862. this._lodPlanes = [];
  14863. this._sizeLods = [];
  14864. this._sigmas = [];
  14865. this._lodMeshes = [];
  14866. this._blurMaterial = null;
  14867. this._cubemapMaterial = null;
  14868. this._equirectMaterial = null;
  14869. this._backgroundBox = null;
  14870. }
  14871. get _hasInitialized() {
  14872. return this._renderer.hasInitialized();
  14873. }
  14874. /**
  14875. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14876. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14877. * in radians to be applied to the scene before PMREM generation. Optional near
  14878. * and far planes ensure the scene is rendered in its entirety.
  14879. *
  14880. * @param {Scene} scene - The scene to be captured.
  14881. * @param {number} [sigma=0] - The blur radius in radians.
  14882. * @param {number} [near=0.1] - The near plane distance.
  14883. * @param {number} [far=100] - The far plane distance.
  14884. * @param {Object} [options={}] - The configuration options.
  14885. * @param {number} [options.size=256] - The texture size of the PMREM.
  14886. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  14887. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  14888. * @return {RenderTarget} The resulting PMREM.
  14889. * @see {@link PMREMGenerator#fromSceneAsync}
  14890. */
  14891. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  14892. const {
  14893. size = 256,
  14894. position = _origin,
  14895. renderTarget = null,
  14896. } = options;
  14897. this._setSize( size );
  14898. if ( this._hasInitialized === false ) {
  14899. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  14900. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14901. options.renderTarget = cubeUVRenderTarget;
  14902. this.fromSceneAsync( scene, sigma, near, far, options );
  14903. return cubeUVRenderTarget;
  14904. }
  14905. _oldTarget = this._renderer.getRenderTarget();
  14906. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14907. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14908. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14909. cubeUVRenderTarget.depthBuffer = true;
  14910. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  14911. if ( sigma > 0 ) {
  14912. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  14913. }
  14914. this._applyPMREM( cubeUVRenderTarget );
  14915. this._cleanup( cubeUVRenderTarget );
  14916. return cubeUVRenderTarget;
  14917. }
  14918. /**
  14919. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14920. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14921. * in radians to be applied to the scene before PMREM generation. Optional near
  14922. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  14923. * is placed at the origin).
  14924. *
  14925. * @param {Scene} scene - The scene to be captured.
  14926. * @param {number} [sigma=0] - The blur radius in radians.
  14927. * @param {number} [near=0.1] - The near plane distance.
  14928. * @param {number} [far=100] - The far plane distance.
  14929. * @param {Object} [options={}] - The configuration options.
  14930. * @param {number} [options.size=256] - The texture size of the PMREM.
  14931. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  14932. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  14933. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  14934. * @see {@link PMREMGenerator#fromScene}
  14935. */
  14936. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  14937. if ( this._hasInitialized === false ) await this._renderer.init();
  14938. return this.fromScene( scene, sigma, near, far, options );
  14939. }
  14940. /**
  14941. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14942. * or HDR. The ideal input image size is 1k (1024 x 512),
  14943. * as this matches best with the 256 x 256 cubemap output.
  14944. *
  14945. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  14946. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  14947. * @return {RenderTarget} The resulting PMREM.
  14948. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  14949. */
  14950. fromEquirectangular( equirectangular, renderTarget = null ) {
  14951. if ( this._hasInitialized === false ) {
  14952. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  14953. this._setSizeFromTexture( equirectangular );
  14954. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14955. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  14956. return cubeUVRenderTarget;
  14957. }
  14958. return this._fromTexture( equirectangular, renderTarget );
  14959. }
  14960. /**
  14961. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14962. * or HDR. The ideal input image size is 1k (1024 x 512),
  14963. * as this matches best with the 256 x 256 cubemap output.
  14964. *
  14965. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  14966. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  14967. * @return {Promise<RenderTarget>} The resulting PMREM.
  14968. * @see {@link PMREMGenerator#fromEquirectangular}
  14969. */
  14970. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  14971. if ( this._hasInitialized === false ) await this._renderer.init();
  14972. return this._fromTexture( equirectangular, renderTarget );
  14973. }
  14974. /**
  14975. * Generates a PMREM from an cubemap texture, which can be either LDR
  14976. * or HDR. The ideal input cube size is 256 x 256,
  14977. * as this matches best with the 256 x 256 cubemap output.
  14978. *
  14979. * @param {Texture} cubemap - The cubemap texture to be converted.
  14980. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  14981. * @return {RenderTarget} The resulting PMREM.
  14982. * @see {@link PMREMGenerator#fromCubemapAsync}
  14983. */
  14984. fromCubemap( cubemap, renderTarget = null ) {
  14985. if ( this._hasInitialized === false ) {
  14986. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  14987. this._setSizeFromTexture( cubemap );
  14988. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14989. this.fromCubemapAsync( cubemap, renderTarget );
  14990. return cubeUVRenderTarget;
  14991. }
  14992. return this._fromTexture( cubemap, renderTarget );
  14993. }
  14994. /**
  14995. * Generates a PMREM from an cubemap texture, which can be either LDR
  14996. * or HDR. The ideal input cube size is 256 x 256,
  14997. * with the 256 x 256 cubemap output.
  14998. *
  14999. * @param {Texture} cubemap - The cubemap texture to be converted.
  15000. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15001. * @return {Promise<RenderTarget>} The resulting PMREM.
  15002. * @see {@link PMREMGenerator#fromCubemap}
  15003. */
  15004. async fromCubemapAsync( cubemap, renderTarget = null ) {
  15005. if ( this._hasInitialized === false ) await this._renderer.init();
  15006. return this._fromTexture( cubemap, renderTarget );
  15007. }
  15008. /**
  15009. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  15010. * your texture's network fetch for increased concurrency.
  15011. *
  15012. * @returns {Promise}
  15013. */
  15014. async compileCubemapShader() {
  15015. if ( this._cubemapMaterial === null ) {
  15016. this._cubemapMaterial = _getCubemapMaterial();
  15017. await this._compileMaterial( this._cubemapMaterial );
  15018. }
  15019. }
  15020. /**
  15021. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  15022. * your texture's network fetch for increased concurrency.
  15023. *
  15024. * @returns {Promise}
  15025. */
  15026. async compileEquirectangularShader() {
  15027. if ( this._equirectMaterial === null ) {
  15028. this._equirectMaterial = _getEquirectMaterial();
  15029. await this._compileMaterial( this._equirectMaterial );
  15030. }
  15031. }
  15032. /**
  15033. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  15034. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  15035. * one of them will cause any others to also become unusable.
  15036. */
  15037. dispose() {
  15038. this._dispose();
  15039. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  15040. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  15041. if ( this._backgroundBox !== null ) {
  15042. this._backgroundBox.geometry.dispose();
  15043. this._backgroundBox.material.dispose();
  15044. }
  15045. }
  15046. // private interface
  15047. _setSizeFromTexture( texture ) {
  15048. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  15049. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  15050. } else { // Equirectangular
  15051. this._setSize( texture.image.width / 4 );
  15052. }
  15053. }
  15054. _setSize( cubeSize ) {
  15055. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  15056. this._cubeSize = Math.pow( 2, this._lodMax );
  15057. }
  15058. _dispose() {
  15059. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  15060. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  15061. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  15062. this._lodPlanes[ i ].dispose();
  15063. }
  15064. }
  15065. _cleanup( outputTarget ) {
  15066. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  15067. outputTarget.scissorTest = false;
  15068. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  15069. }
  15070. _fromTexture( texture, renderTarget ) {
  15071. this._setSizeFromTexture( texture );
  15072. _oldTarget = this._renderer.getRenderTarget();
  15073. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15074. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15075. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15076. this._textureToCubeUV( texture, cubeUVRenderTarget );
  15077. this._applyPMREM( cubeUVRenderTarget );
  15078. this._cleanup( cubeUVRenderTarget );
  15079. return cubeUVRenderTarget;
  15080. }
  15081. _allocateTargets() {
  15082. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  15083. const height = 4 * this._cubeSize;
  15084. const params = {
  15085. magFilter: LinearFilter,
  15086. minFilter: LinearFilter,
  15087. generateMipmaps: false,
  15088. type: HalfFloatType,
  15089. format: RGBAFormat,
  15090. colorSpace: LinearSRGBColorSpace,
  15091. //depthBuffer: false
  15092. };
  15093. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  15094. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  15095. if ( this._pingPongRenderTarget !== null ) {
  15096. this._dispose();
  15097. }
  15098. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  15099. const { _lodMax } = this;
  15100. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  15101. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  15102. }
  15103. return cubeUVRenderTarget;
  15104. }
  15105. async _compileMaterial( material ) {
  15106. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  15107. await this._renderer.compile( tmpMesh, _flatCamera );
  15108. }
  15109. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  15110. const cubeCamera = _cubeCamera;
  15111. cubeCamera.near = near;
  15112. cubeCamera.far = far;
  15113. // px, py, pz, nx, ny, nz
  15114. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  15115. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  15116. const renderer = this._renderer;
  15117. const originalAutoClear = renderer.autoClear;
  15118. renderer.getClearColor( _clearColor$2 );
  15119. renderer.autoClear = false;
  15120. let backgroundBox = this._backgroundBox;
  15121. if ( backgroundBox === null ) {
  15122. const backgroundMaterial = new MeshBasicMaterial( {
  15123. name: 'PMREM.Background',
  15124. side: BackSide,
  15125. depthWrite: false,
  15126. depthTest: false
  15127. } );
  15128. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  15129. }
  15130. let useSolidColor = false;
  15131. const background = scene.background;
  15132. if ( background ) {
  15133. if ( background.isColor ) {
  15134. backgroundBox.material.color.copy( background );
  15135. scene.background = null;
  15136. useSolidColor = true;
  15137. }
  15138. } else {
  15139. backgroundBox.material.color.copy( _clearColor$2 );
  15140. useSolidColor = true;
  15141. }
  15142. renderer.setRenderTarget( cubeUVRenderTarget );
  15143. renderer.clear();
  15144. if ( useSolidColor ) {
  15145. renderer.render( backgroundBox, cubeCamera );
  15146. }
  15147. for ( let i = 0; i < 6; i ++ ) {
  15148. const col = i % 3;
  15149. if ( col === 0 ) {
  15150. cubeCamera.up.set( 0, upSign[ i ], 0 );
  15151. cubeCamera.position.set( position.x, position.y, position.z );
  15152. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  15153. } else if ( col === 1 ) {
  15154. cubeCamera.up.set( 0, 0, upSign[ i ] );
  15155. cubeCamera.position.set( position.x, position.y, position.z );
  15156. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  15157. } else {
  15158. cubeCamera.up.set( 0, upSign[ i ], 0 );
  15159. cubeCamera.position.set( position.x, position.y, position.z );
  15160. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  15161. }
  15162. const size = this._cubeSize;
  15163. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  15164. renderer.render( scene, cubeCamera );
  15165. }
  15166. renderer.autoClear = originalAutoClear;
  15167. scene.background = background;
  15168. }
  15169. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  15170. const renderer = this._renderer;
  15171. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  15172. if ( isCubeTexture ) {
  15173. if ( this._cubemapMaterial === null ) {
  15174. this._cubemapMaterial = _getCubemapMaterial( texture );
  15175. }
  15176. } else {
  15177. if ( this._equirectMaterial === null ) {
  15178. this._equirectMaterial = _getEquirectMaterial( texture );
  15179. }
  15180. }
  15181. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  15182. material.fragmentNode.value = texture;
  15183. const mesh = this._lodMeshes[ 0 ];
  15184. mesh.material = material;
  15185. const size = this._cubeSize;
  15186. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  15187. renderer.setRenderTarget( cubeUVRenderTarget );
  15188. renderer.render( mesh, _flatCamera );
  15189. }
  15190. _applyPMREM( cubeUVRenderTarget ) {
  15191. const renderer = this._renderer;
  15192. const autoClear = renderer.autoClear;
  15193. renderer.autoClear = false;
  15194. const n = this._lodPlanes.length;
  15195. for ( let i = 1; i < n; i ++ ) {
  15196. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  15197. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  15198. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  15199. }
  15200. renderer.autoClear = autoClear;
  15201. }
  15202. /**
  15203. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  15204. * vertically and horizontally, but this breaks down on a cube. Here we apply
  15205. * the blur latitudinally (around the poles), and then longitudinally (towards
  15206. * the poles) to approximate the orthogonally-separable blur. It is least
  15207. * accurate at the poles, but still does a decent job.
  15208. *
  15209. * @private
  15210. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  15211. * @param {number} lodIn - The input level-of-detail.
  15212. * @param {number} lodOut - The output level-of-detail.
  15213. * @param {number} sigma - The blur radius in radians.
  15214. * @param {Vector3} [poleAxis] - The pole axis.
  15215. */
  15216. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  15217. const pingPongRenderTarget = this._pingPongRenderTarget;
  15218. this._halfBlur(
  15219. cubeUVRenderTarget,
  15220. pingPongRenderTarget,
  15221. lodIn,
  15222. lodOut,
  15223. sigma,
  15224. 'latitudinal',
  15225. poleAxis );
  15226. this._halfBlur(
  15227. pingPongRenderTarget,
  15228. cubeUVRenderTarget,
  15229. lodOut,
  15230. lodOut,
  15231. sigma,
  15232. 'longitudinal',
  15233. poleAxis );
  15234. }
  15235. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  15236. const renderer = this._renderer;
  15237. const blurMaterial = this._blurMaterial;
  15238. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  15239. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  15240. }
  15241. // Number of standard deviations at which to cut off the discrete approximation.
  15242. const STANDARD_DEVIATIONS = 3;
  15243. const blurMesh = this._lodMeshes[ lodOut ];
  15244. blurMesh.material = blurMaterial;
  15245. const blurUniforms = _uniformsMap.get( blurMaterial );
  15246. const pixels = this._sizeLods[ lodIn ] - 1;
  15247. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  15248. const sigmaPixels = sigmaRadians / radiansPerPixel;
  15249. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  15250. if ( samples > MAX_SAMPLES ) {
  15251. console.warn( `sigmaRadians, ${
  15252. sigmaRadians}, is too large and will clip, as it requested ${
  15253. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  15254. }
  15255. const weights = [];
  15256. let sum = 0;
  15257. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  15258. const x = i / sigmaPixels;
  15259. const weight = Math.exp( - x * x / 2 );
  15260. weights.push( weight );
  15261. if ( i === 0 ) {
  15262. sum += weight;
  15263. } else if ( i < samples ) {
  15264. sum += 2 * weight;
  15265. }
  15266. }
  15267. for ( let i = 0; i < weights.length; i ++ ) {
  15268. weights[ i ] = weights[ i ] / sum;
  15269. }
  15270. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  15271. blurUniforms.envMap.value = targetIn.texture;
  15272. blurUniforms.samples.value = samples;
  15273. blurUniforms.weights.array = weights;
  15274. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  15275. if ( poleAxis ) {
  15276. blurUniforms.poleAxis.value = poleAxis;
  15277. }
  15278. const { _lodMax } = this;
  15279. blurUniforms.dTheta.value = radiansPerPixel;
  15280. blurUniforms.mipInt.value = _lodMax - lodIn;
  15281. const outputSize = this._sizeLods[ lodOut ];
  15282. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  15283. const y = 4 * ( this._cubeSize - outputSize );
  15284. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  15285. renderer.setRenderTarget( targetOut );
  15286. renderer.render( blurMesh, _flatCamera );
  15287. }
  15288. }
  15289. function _createPlanes( lodMax ) {
  15290. const lodPlanes = [];
  15291. const sizeLods = [];
  15292. const sigmas = [];
  15293. const lodMeshes = [];
  15294. let lod = lodMax;
  15295. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  15296. for ( let i = 0; i < totalLods; i ++ ) {
  15297. const sizeLod = Math.pow( 2, lod );
  15298. sizeLods.push( sizeLod );
  15299. let sigma = 1.0 / sizeLod;
  15300. if ( i > lodMax - LOD_MIN ) {
  15301. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  15302. } else if ( i === 0 ) {
  15303. sigma = 0;
  15304. }
  15305. sigmas.push( sigma );
  15306. const texelSize = 1.0 / ( sizeLod - 2 );
  15307. const min = - texelSize;
  15308. const max = 1 + texelSize;
  15309. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  15310. const cubeFaces = 6;
  15311. const vertices = 6;
  15312. const positionSize = 3;
  15313. const uvSize = 2;
  15314. const faceIndexSize = 1;
  15315. const position = new Float32Array( positionSize * vertices * cubeFaces );
  15316. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  15317. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  15318. for ( let face = 0; face < cubeFaces; face ++ ) {
  15319. const x = ( face % 3 ) * 2 / 3 - 1;
  15320. const y = face > 2 ? 0 : - 1;
  15321. const coordinates = [
  15322. x, y, 0,
  15323. x + 2 / 3, y, 0,
  15324. x + 2 / 3, y + 1, 0,
  15325. x, y, 0,
  15326. x + 2 / 3, y + 1, 0,
  15327. x, y + 1, 0
  15328. ];
  15329. const faceIdx = _faceLib[ face ];
  15330. position.set( coordinates, positionSize * vertices * faceIdx );
  15331. uv.set( uv1, uvSize * vertices * faceIdx );
  15332. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  15333. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  15334. }
  15335. const planes = new BufferGeometry();
  15336. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  15337. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  15338. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  15339. lodPlanes.push( planes );
  15340. lodMeshes.push( new Mesh( planes, null ) );
  15341. if ( lod > LOD_MIN ) {
  15342. lod --;
  15343. }
  15344. }
  15345. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  15346. }
  15347. function _createRenderTarget( width, height, params ) {
  15348. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  15349. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  15350. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  15351. cubeUVRenderTarget.texture.isPMREMTexture = true;
  15352. cubeUVRenderTarget.scissorTest = true;
  15353. return cubeUVRenderTarget;
  15354. }
  15355. function _setViewport( target, x, y, width, height ) {
  15356. target.viewport.set( x, y, width, height );
  15357. target.scissor.set( x, y, width, height );
  15358. }
  15359. function _getMaterial( type ) {
  15360. const material = new NodeMaterial();
  15361. material.depthTest = false;
  15362. material.depthWrite = false;
  15363. material.blending = NoBlending;
  15364. material.name = `PMREM_${ type }`;
  15365. return material;
  15366. }
  15367. function _getBlurShader( lodMax, width, height ) {
  15368. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  15369. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  15370. const dTheta = uniform( 0 );
  15371. const n = float( MAX_SAMPLES );
  15372. const latitudinal = uniform( 0 ); // false, bool
  15373. const samples = uniform( 1 ); // int
  15374. const envMap = texture( null );
  15375. const mipInt = uniform( 0 ); // int
  15376. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  15377. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  15378. const CUBEUV_MAX_MIP = float( lodMax );
  15379. const materialUniforms = {
  15380. n,
  15381. latitudinal,
  15382. weights,
  15383. poleAxis,
  15384. outputDirection: _outputDirection,
  15385. dTheta,
  15386. samples,
  15387. envMap,
  15388. mipInt,
  15389. CUBEUV_TEXEL_WIDTH,
  15390. CUBEUV_TEXEL_HEIGHT,
  15391. CUBEUV_MAX_MIP
  15392. };
  15393. const material = _getMaterial( 'blur' );
  15394. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  15395. _uniformsMap.set( material, materialUniforms );
  15396. return material;
  15397. }
  15398. function _getCubemapMaterial( envTexture ) {
  15399. const material = _getMaterial( 'cubemap' );
  15400. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  15401. return material;
  15402. }
  15403. function _getEquirectMaterial( envTexture ) {
  15404. const material = _getMaterial( 'equirect' );
  15405. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  15406. return material;
  15407. }
  15408. const _cache = new WeakMap();
  15409. /**
  15410. * Generates the cubeUV size based on the given image height.
  15411. *
  15412. * @private
  15413. * @param {number} imageHeight - The image height.
  15414. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  15415. */
  15416. function _generateCubeUVSize( imageHeight ) {
  15417. const maxMip = Math.log2( imageHeight ) - 2;
  15418. const texelHeight = 1.0 / imageHeight;
  15419. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  15420. return { texelWidth, texelHeight, maxMip };
  15421. }
  15422. /**
  15423. * Generates a PMREM from the given texture.
  15424. *
  15425. * @private
  15426. * @param {Texture} texture - The texture to create the PMREM for.
  15427. * @param {Renderer} renderer - The renderer.
  15428. * @param {PMREMGenerator} generator - The PMREM generator.
  15429. * @return {?Texture} The PMREM.
  15430. */
  15431. function _getPMREMFromTexture( texture, renderer, generator ) {
  15432. const cache = _getCache( renderer );
  15433. let cacheTexture = cache.get( texture );
  15434. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  15435. if ( pmremVersion !== texture.pmremVersion ) {
  15436. const image = texture.image;
  15437. if ( texture.isCubeTexture ) {
  15438. if ( isCubeMapReady( image ) ) {
  15439. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  15440. } else {
  15441. return null;
  15442. }
  15443. } else {
  15444. if ( isEquirectangularMapReady( image ) ) {
  15445. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  15446. } else {
  15447. return null;
  15448. }
  15449. }
  15450. cacheTexture.pmremVersion = texture.pmremVersion;
  15451. cache.set( texture, cacheTexture );
  15452. }
  15453. return cacheTexture.texture;
  15454. }
  15455. /**
  15456. * Returns a cache that stores generated PMREMs for the respective textures.
  15457. * A cache must be maintained per renderer since PMREMs are render target textures
  15458. * which can't be shared across render contexts.
  15459. *
  15460. * @private
  15461. * @param {Renderer} renderer - The renderer.
  15462. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  15463. */
  15464. function _getCache( renderer ) {
  15465. let rendererCache = _cache.get( renderer );
  15466. if ( rendererCache === undefined ) {
  15467. rendererCache = new WeakMap();
  15468. _cache.set( renderer, rendererCache );
  15469. }
  15470. return rendererCache;
  15471. }
  15472. /**
  15473. * This node represents a PMREM which is a special type of preprocessed
  15474. * environment map intended for PBR materials.
  15475. *
  15476. * ```js
  15477. * const material = new MeshStandardNodeMaterial();
  15478. * material.envNode = pmremTexture( envMap );
  15479. * ```
  15480. *
  15481. * @augments TempNode
  15482. */
  15483. class PMREMNode extends TempNode {
  15484. static get type() {
  15485. return 'PMREMNode';
  15486. }
  15487. /**
  15488. * Constructs a new function overloading node.
  15489. *
  15490. * @param {Texture} value - The input texture.
  15491. * @param {Node<vec2>} [uvNode=null] - The uv node.
  15492. * @param {Node<float>} [levelNode=null] - The level node.
  15493. */
  15494. constructor( value, uvNode = null, levelNode = null ) {
  15495. super( 'vec3' );
  15496. /**
  15497. * Reference to the input texture.
  15498. *
  15499. * @private
  15500. * @type {Texture}
  15501. */
  15502. this._value = value;
  15503. /**
  15504. * Reference to the generated PMREM.
  15505. *
  15506. * @private
  15507. * @type {Texture | null}
  15508. * @default null
  15509. */
  15510. this._pmrem = null;
  15511. /**
  15512. * The uv node.
  15513. *
  15514. * @type {Node<vec2>}
  15515. */
  15516. this.uvNode = uvNode;
  15517. /**
  15518. * The level node.
  15519. *
  15520. * @type {Node<float>}
  15521. */
  15522. this.levelNode = levelNode;
  15523. /**
  15524. * Reference to a PMREM generator.
  15525. *
  15526. * @private
  15527. * @type {?PMREMGenerator}
  15528. * @default null
  15529. */
  15530. this._generator = null;
  15531. const defaultTexture = new Texture();
  15532. defaultTexture.isRenderTargetTexture = true;
  15533. /**
  15534. * The texture node holding the generated PMREM.
  15535. *
  15536. * @private
  15537. * @type {TextureNode}
  15538. */
  15539. this._texture = texture( defaultTexture );
  15540. /**
  15541. * A uniform representing the PMREM's width.
  15542. *
  15543. * @private
  15544. * @type {UniformNode<float>}
  15545. */
  15546. this._width = uniform( 0 );
  15547. /**
  15548. * A uniform representing the PMREM's height.
  15549. *
  15550. * @private
  15551. * @type {UniformNode<float>}
  15552. */
  15553. this._height = uniform( 0 );
  15554. /**
  15555. * A uniform representing the PMREM's max Mip.
  15556. *
  15557. * @private
  15558. * @type {UniformNode<float>}
  15559. */
  15560. this._maxMip = uniform( 0 );
  15561. /**
  15562. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  15563. *
  15564. * @type {string}
  15565. * @default 'render'
  15566. */
  15567. this.updateBeforeType = NodeUpdateType.RENDER;
  15568. }
  15569. set value( value ) {
  15570. this._value = value;
  15571. this._pmrem = null;
  15572. }
  15573. /**
  15574. * The node's texture value.
  15575. *
  15576. * @type {Texture}
  15577. */
  15578. get value() {
  15579. return this._value;
  15580. }
  15581. /**
  15582. * Uses the given PMREM texture to update internal values.
  15583. *
  15584. * @param {Texture} texture - The PMREM texture.
  15585. */
  15586. updateFromTexture( texture ) {
  15587. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  15588. this._texture.value = texture;
  15589. this._width.value = cubeUVSize.texelWidth;
  15590. this._height.value = cubeUVSize.texelHeight;
  15591. this._maxMip.value = cubeUVSize.maxMip;
  15592. }
  15593. updateBefore( frame ) {
  15594. let pmrem = this._pmrem;
  15595. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  15596. const texture = this._value;
  15597. if ( pmremVersion !== texture.pmremVersion ) {
  15598. if ( texture.isPMREMTexture === true ) {
  15599. pmrem = texture;
  15600. } else {
  15601. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  15602. }
  15603. if ( pmrem !== null ) {
  15604. this._pmrem = pmrem;
  15605. this.updateFromTexture( pmrem );
  15606. }
  15607. }
  15608. }
  15609. setup( builder ) {
  15610. if ( this._generator === null ) {
  15611. this._generator = new PMREMGenerator( builder.renderer );
  15612. }
  15613. this.updateBefore( builder );
  15614. //
  15615. let uvNode = this.uvNode;
  15616. if ( uvNode === null && builder.context.getUV ) {
  15617. uvNode = builder.context.getUV( this );
  15618. }
  15619. //
  15620. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  15621. //
  15622. let levelNode = this.levelNode;
  15623. if ( levelNode === null && builder.context.getTextureLevel ) {
  15624. levelNode = builder.context.getTextureLevel( this );
  15625. }
  15626. //
  15627. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  15628. }
  15629. dispose() {
  15630. super.dispose();
  15631. if ( this._generator !== null ) this._generator.dispose();
  15632. }
  15633. }
  15634. /**
  15635. * Returns `true` if the given cube map image has been fully loaded.
  15636. *
  15637. * @private
  15638. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  15639. * @return {boolean} Whether the given cube map is ready or not.
  15640. */
  15641. function isCubeMapReady( image ) {
  15642. if ( image === null || image === undefined ) return false;
  15643. let count = 0;
  15644. const length = 6;
  15645. for ( let i = 0; i < length; i ++ ) {
  15646. if ( image[ i ] !== undefined ) count ++;
  15647. }
  15648. return count === length;
  15649. }
  15650. /**
  15651. * Returns `true` if the given equirectangular image has been fully loaded.
  15652. *
  15653. * @private
  15654. * @param {(Image|Object)} image - The equirectangular image.
  15655. * @return {boolean} Whether the given cube map is ready or not.
  15656. */
  15657. function isEquirectangularMapReady( image ) {
  15658. if ( image === null || image === undefined ) return false;
  15659. return image.height > 0;
  15660. }
  15661. /**
  15662. * TSL function for creating a PMREM node.
  15663. *
  15664. * @tsl
  15665. * @function
  15666. * @param {Texture} value - The input texture.
  15667. * @param {Node<vec2>} [uvNode=null] - The uv node.
  15668. * @param {Node<float>} [levelNode=null] - The level node.
  15669. * @returns {PMREMNode}
  15670. */
  15671. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  15672. const _envNodeCache = new WeakMap();
  15673. /**
  15674. * Represents a physical model for Image-based lighting (IBL). The environment
  15675. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  15676. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  15677. *
  15678. * @augments LightingNode
  15679. */
  15680. class EnvironmentNode extends LightingNode {
  15681. static get type() {
  15682. return 'EnvironmentNode';
  15683. }
  15684. /**
  15685. * Constructs a new environment node.
  15686. *
  15687. * @param {Node} [envNode=null] - A node representing the environment.
  15688. */
  15689. constructor( envNode = null ) {
  15690. super();
  15691. /**
  15692. * A node representing the environment.
  15693. *
  15694. * @type {?Node}
  15695. * @default null
  15696. */
  15697. this.envNode = envNode;
  15698. }
  15699. setup( builder ) {
  15700. const { material } = builder;
  15701. let envNode = this.envNode;
  15702. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15703. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15704. let cacheEnvNode = _envNodeCache.get( value );
  15705. if ( cacheEnvNode === undefined ) {
  15706. cacheEnvNode = pmremTexture( value );
  15707. _envNodeCache.set( value, cacheEnvNode );
  15708. }
  15709. envNode = cacheEnvNode;
  15710. }
  15711. //
  15712. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  15713. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  15714. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  15715. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  15716. const isolateRadiance = cache( radiance );
  15717. const isolateIrradiance = cache( irradiance );
  15718. //
  15719. builder.context.radiance.addAssign( isolateRadiance );
  15720. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  15721. //
  15722. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  15723. if ( clearcoatRadiance ) {
  15724. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( materialEnvIntensity );
  15725. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  15726. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  15727. }
  15728. }
  15729. }
  15730. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  15731. let reflectVec = null;
  15732. return {
  15733. getUV: () => {
  15734. if ( reflectVec === null ) {
  15735. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  15736. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  15737. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  15738. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  15739. }
  15740. return reflectVec;
  15741. },
  15742. getTextureLevel: () => {
  15743. return roughnessNode;
  15744. }
  15745. };
  15746. };
  15747. const createIrradianceContext = ( normalWorldNode ) => {
  15748. return {
  15749. getUV: () => {
  15750. return normalWorldNode;
  15751. },
  15752. getTextureLevel: () => {
  15753. return float( 1.0 );
  15754. }
  15755. };
  15756. };
  15757. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  15758. /**
  15759. * Node material version of {@link MeshStandardMaterial}.
  15760. *
  15761. * @augments NodeMaterial
  15762. */
  15763. class MeshStandardNodeMaterial extends NodeMaterial {
  15764. static get type() {
  15765. return 'MeshStandardNodeMaterial';
  15766. }
  15767. /**
  15768. * Constructs a new mesh standard node material.
  15769. *
  15770. * @param {Object} [parameters] - The configuration parameter.
  15771. */
  15772. constructor( parameters ) {
  15773. super();
  15774. /**
  15775. * This flag can be used for type testing.
  15776. *
  15777. * @type {boolean}
  15778. * @readonly
  15779. * @default true
  15780. */
  15781. this.isMeshStandardNodeMaterial = true;
  15782. /**
  15783. * Set to `true` because standard materials react on lights.
  15784. *
  15785. * @type {boolean}
  15786. * @default true
  15787. */
  15788. this.lights = true;
  15789. /**
  15790. * The emissive color of standard materials is by default inferred from the `emissive`,
  15791. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  15792. * overwrite the default and define the emissive color with a node instead.
  15793. *
  15794. * If you don't want to overwrite the emissive color but modify the existing
  15795. * value instead, use {@link materialEmissive}.
  15796. *
  15797. * @type {?Node<vec3>}
  15798. * @default null
  15799. */
  15800. this.emissiveNode = null;
  15801. /**
  15802. * The metalness of standard materials is by default inferred from the `metalness`,
  15803. * and `metalnessMap` properties. This node property allows to
  15804. * overwrite the default and define the metalness with a node instead.
  15805. *
  15806. * If you don't want to overwrite the metalness but modify the existing
  15807. * value instead, use {@link materialMetalness}.
  15808. *
  15809. * @type {?Node<float>}
  15810. * @default null
  15811. */
  15812. this.metalnessNode = null;
  15813. /**
  15814. * The roughness of standard materials is by default inferred from the `roughness`,
  15815. * and `roughnessMap` properties. This node property allows to
  15816. * overwrite the default and define the roughness with a node instead.
  15817. *
  15818. * If you don't want to overwrite the roughness but modify the existing
  15819. * value instead, use {@link materialRoughness}.
  15820. *
  15821. * @type {?Node<float>}
  15822. * @default null
  15823. */
  15824. this.roughnessNode = null;
  15825. this.setDefaultValues( _defaultValues$6 );
  15826. this.setValues( parameters );
  15827. }
  15828. /**
  15829. * Overwritten since this type of material uses {@link EnvironmentNode}
  15830. * to implement the PBR (PMREM based) environment mapping. Besides, the
  15831. * method honors `Scene.environment`.
  15832. *
  15833. * @param {NodeBuilder} builder - The current node builder.
  15834. * @return {?EnvironmentNode<vec3>} The environment node.
  15835. */
  15836. setupEnvironment( builder ) {
  15837. let envNode = super.setupEnvironment( builder );
  15838. if ( envNode === null && builder.environmentNode ) {
  15839. envNode = builder.environmentNode;
  15840. }
  15841. return envNode ? new EnvironmentNode( envNode ) : null;
  15842. }
  15843. /**
  15844. * Setups the lighting model.
  15845. *
  15846. * @return {PhysicalLightingModel} The lighting model.
  15847. */
  15848. setupLightingModel( /*builder*/ ) {
  15849. return new PhysicalLightingModel();
  15850. }
  15851. /**
  15852. * Setups the specular related node variables.
  15853. */
  15854. setupSpecular() {
  15855. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  15856. specularColor.assign( specularColorNode );
  15857. specularF90.assign( 1.0 );
  15858. }
  15859. /**
  15860. * Setups the standard specific node variables.
  15861. *
  15862. * @param {NodeBuilder} builder - The current node builder.
  15863. */
  15864. setupVariants() {
  15865. // METALNESS
  15866. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  15867. metalness.assign( metalnessNode );
  15868. // ROUGHNESS
  15869. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  15870. roughnessNode = getRoughness( { roughness: roughnessNode } );
  15871. roughness.assign( roughnessNode );
  15872. // SPECULAR COLOR
  15873. this.setupSpecular();
  15874. // DIFFUSE COLOR
  15875. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  15876. }
  15877. copy( source ) {
  15878. this.emissiveNode = source.emissiveNode;
  15879. this.metalnessNode = source.metalnessNode;
  15880. this.roughnessNode = source.roughnessNode;
  15881. return super.copy( source );
  15882. }
  15883. }
  15884. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  15885. /**
  15886. * Node material version of {@link MeshPhysicalMaterial}.
  15887. *
  15888. * @augments MeshStandardNodeMaterial
  15889. */
  15890. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  15891. static get type() {
  15892. return 'MeshPhysicalNodeMaterial';
  15893. }
  15894. /**
  15895. * Constructs a new mesh physical node material.
  15896. *
  15897. * @param {Object} [parameters] - The configuration parameter.
  15898. */
  15899. constructor( parameters ) {
  15900. super();
  15901. /**
  15902. * This flag can be used for type testing.
  15903. *
  15904. * @type {boolean}
  15905. * @readonly
  15906. * @default true
  15907. */
  15908. this.isMeshPhysicalNodeMaterial = true;
  15909. /**
  15910. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  15911. * and `clearcoatMap` properties. This node property allows to overwrite the default
  15912. * and define the clearcoat with a node instead.
  15913. *
  15914. * If you don't want to overwrite the clearcoat but modify the existing
  15915. * value instead, use {@link materialClearcoat}.
  15916. *
  15917. * @type {?Node<float>}
  15918. * @default null
  15919. */
  15920. this.clearcoatNode = null;
  15921. /**
  15922. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  15923. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  15924. * and define the clearcoat roughness with a node instead.
  15925. *
  15926. * If you don't want to overwrite the clearcoat roughness but modify the existing
  15927. * value instead, use {@link materialClearcoatRoughness}.
  15928. *
  15929. * @type {?Node<float>}
  15930. * @default null
  15931. */
  15932. this.clearcoatRoughnessNode = null;
  15933. /**
  15934. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  15935. * property. This node property allows to overwrite the default
  15936. * and define the clearcoat normal with a node instead.
  15937. *
  15938. * If you don't want to overwrite the clearcoat normal but modify the existing
  15939. * value instead, use {@link materialClearcoatNormal}.
  15940. *
  15941. * @type {?Node<vec3>}
  15942. * @default null
  15943. */
  15944. this.clearcoatNormalNode = null;
  15945. /**
  15946. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  15947. * and `sheenColorMap` properties. This node property allows to overwrite the default
  15948. * and define the sheen with a node instead.
  15949. *
  15950. * If you don't want to overwrite the sheen but modify the existing
  15951. * value instead, use {@link materialSheen}.
  15952. *
  15953. * @type {?Node<vec3>}
  15954. * @default null
  15955. */
  15956. this.sheenNode = null;
  15957. /**
  15958. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  15959. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  15960. * and define the sheen roughness with a node instead.
  15961. *
  15962. * If you don't want to overwrite the sheen roughness but modify the existing
  15963. * value instead, use {@link materialSheenRoughness}.
  15964. *
  15965. * @type {?Node<float>}
  15966. * @default null
  15967. */
  15968. this.sheenRoughnessNode = null;
  15969. /**
  15970. * The iridescence of physical materials is by default inferred from the `iridescence`
  15971. * property. This node property allows to overwrite the default
  15972. * and define the iridescence with a node instead.
  15973. *
  15974. * If you don't want to overwrite the iridescence but modify the existing
  15975. * value instead, use {@link materialIridescence}.
  15976. *
  15977. * @type {?Node<float>}
  15978. * @default null
  15979. */
  15980. this.iridescenceNode = null;
  15981. /**
  15982. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  15983. * property. This node property allows to overwrite the default
  15984. * and define the iridescence IOR with a node instead.
  15985. *
  15986. * If you don't want to overwrite the iridescence IOR but modify the existing
  15987. * value instead, use {@link materialIridescenceIOR}.
  15988. *
  15989. * @type {?Node<float>}
  15990. * @default null
  15991. */
  15992. this.iridescenceIORNode = null;
  15993. /**
  15994. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  15995. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  15996. * and define the iridescence thickness with a node instead.
  15997. *
  15998. * If you don't want to overwrite the iridescence thickness but modify the existing
  15999. * value instead, use {@link materialIridescenceThickness}.
  16000. *
  16001. * @type {?Node<float>}
  16002. * @default null
  16003. */
  16004. this.iridescenceThicknessNode = null;
  16005. /**
  16006. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  16007. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  16008. * and define the specular intensity with a node instead.
  16009. *
  16010. * If you don't want to overwrite the specular intensity but modify the existing
  16011. * value instead, use {@link materialSpecularIntensity}.
  16012. *
  16013. * @type {?Node<float>}
  16014. * @default null
  16015. */
  16016. this.specularIntensityNode = null;
  16017. /**
  16018. * The specular color of physical materials is by default inferred from the `specularColor`
  16019. * and `specularColorMap` properties. This node property allows to overwrite the default
  16020. * and define the specular color with a node instead.
  16021. *
  16022. * If you don't want to overwrite the specular color but modify the existing
  16023. * value instead, use {@link materialSpecularColor}.
  16024. *
  16025. * @type {?Node<vec3>}
  16026. * @default null
  16027. */
  16028. this.specularColorNode = null;
  16029. /**
  16030. * The ior of physical materials is by default inferred from the `ior`
  16031. * property. This node property allows to overwrite the default
  16032. * and define the ior with a node instead.
  16033. *
  16034. * If you don't want to overwrite the ior but modify the existing
  16035. * value instead, use {@link materialIOR}.
  16036. *
  16037. * @type {?Node<float>}
  16038. * @default null
  16039. */
  16040. this.iorNode = null;
  16041. /**
  16042. * The transmission of physical materials is by default inferred from the `transmission` and
  16043. * `transmissionMap` properties. This node property allows to overwrite the default
  16044. * and define the transmission with a node instead.
  16045. *
  16046. * If you don't want to overwrite the transmission but modify the existing
  16047. * value instead, use {@link materialTransmission}.
  16048. *
  16049. * @type {?Node<float>}
  16050. * @default null
  16051. */
  16052. this.transmissionNode = null;
  16053. /**
  16054. * The thickness of physical materials is by default inferred from the `thickness` and
  16055. * `thicknessMap` properties. This node property allows to overwrite the default
  16056. * and define the thickness with a node instead.
  16057. *
  16058. * If you don't want to overwrite the thickness but modify the existing
  16059. * value instead, use {@link materialThickness}.
  16060. *
  16061. * @type {?Node<float>}
  16062. * @default null
  16063. */
  16064. this.thicknessNode = null;
  16065. /**
  16066. * The attenuation distance of physical materials is by default inferred from the
  16067. * `attenuationDistance` property. This node property allows to overwrite the default
  16068. * and define the attenuation distance with a node instead.
  16069. *
  16070. * If you don't want to overwrite the attenuation distance but modify the existing
  16071. * value instead, use {@link materialAttenuationDistance}.
  16072. *
  16073. * @type {?Node<float>}
  16074. * @default null
  16075. */
  16076. this.attenuationDistanceNode = null;
  16077. /**
  16078. * The attenuation color of physical materials is by default inferred from the
  16079. * `attenuationColor` property. This node property allows to overwrite the default
  16080. * and define the attenuation color with a node instead.
  16081. *
  16082. * If you don't want to overwrite the attenuation color but modify the existing
  16083. * value instead, use {@link materialAttenuationColor}.
  16084. *
  16085. * @type {?Node<vec3>}
  16086. * @default null
  16087. */
  16088. this.attenuationColorNode = null;
  16089. /**
  16090. * The dispersion of physical materials is by default inferred from the
  16091. * `dispersion` property. This node property allows to overwrite the default
  16092. * and define the dispersion with a node instead.
  16093. *
  16094. * If you don't want to overwrite the dispersion but modify the existing
  16095. * value instead, use {@link materialDispersion}.
  16096. *
  16097. * @type {?Node<float>}
  16098. * @default null
  16099. */
  16100. this.dispersionNode = null;
  16101. /**
  16102. * The anisotropy of physical materials is by default inferred from the
  16103. * `anisotropy` property. This node property allows to overwrite the default
  16104. * and define the anisotropy with a node instead.
  16105. *
  16106. * If you don't want to overwrite the anisotropy but modify the existing
  16107. * value instead, use {@link materialAnisotropy}.
  16108. *
  16109. * @type {?Node<float>}
  16110. * @default null
  16111. */
  16112. this.anisotropyNode = null;
  16113. this.setDefaultValues( _defaultValues$5 );
  16114. this.setValues( parameters );
  16115. }
  16116. /**
  16117. * Whether the lighting model should use clearcoat or not.
  16118. *
  16119. * @type {boolean}
  16120. * @default true
  16121. */
  16122. get useClearcoat() {
  16123. return this.clearcoat > 0 || this.clearcoatNode !== null;
  16124. }
  16125. /**
  16126. * Whether the lighting model should use iridescence or not.
  16127. *
  16128. * @type {boolean}
  16129. * @default true
  16130. */
  16131. get useIridescence() {
  16132. return this.iridescence > 0 || this.iridescenceNode !== null;
  16133. }
  16134. /**
  16135. * Whether the lighting model should use sheen or not.
  16136. *
  16137. * @type {boolean}
  16138. * @default true
  16139. */
  16140. get useSheen() {
  16141. return this.sheen > 0 || this.sheenNode !== null;
  16142. }
  16143. /**
  16144. * Whether the lighting model should use anisotropy or not.
  16145. *
  16146. * @type {boolean}
  16147. * @default true
  16148. */
  16149. get useAnisotropy() {
  16150. return this.anisotropy > 0 || this.anisotropyNode !== null;
  16151. }
  16152. /**
  16153. * Whether the lighting model should use transmission or not.
  16154. *
  16155. * @type {boolean}
  16156. * @default true
  16157. */
  16158. get useTransmission() {
  16159. return this.transmission > 0 || this.transmissionNode !== null;
  16160. }
  16161. /**
  16162. * Whether the lighting model should use dispersion or not.
  16163. *
  16164. * @type {boolean}
  16165. * @default true
  16166. */
  16167. get useDispersion() {
  16168. return this.dispersion > 0 || this.dispersionNode !== null;
  16169. }
  16170. /**
  16171. * Setups the specular related node variables.
  16172. */
  16173. setupSpecular() {
  16174. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  16175. ior.assign( iorNode );
  16176. 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 ) );
  16177. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  16178. }
  16179. /**
  16180. * Setups the lighting model.
  16181. *
  16182. * @return {PhysicalLightingModel} The lighting model.
  16183. */
  16184. setupLightingModel( /*builder*/ ) {
  16185. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  16186. }
  16187. /**
  16188. * Setups the physical specific node variables.
  16189. *
  16190. * @param {NodeBuilder} builder - The current node builder.
  16191. */
  16192. setupVariants( builder ) {
  16193. super.setupVariants( builder );
  16194. // CLEARCOAT
  16195. if ( this.useClearcoat ) {
  16196. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  16197. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  16198. clearcoat.assign( clearcoatNode );
  16199. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  16200. }
  16201. // SHEEN
  16202. if ( this.useSheen ) {
  16203. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  16204. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  16205. sheen.assign( sheenNode );
  16206. sheenRoughness.assign( sheenRoughnessNode );
  16207. }
  16208. // IRIDESCENCE
  16209. if ( this.useIridescence ) {
  16210. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  16211. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  16212. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  16213. iridescence.assign( iridescenceNode );
  16214. iridescenceIOR.assign( iridescenceIORNode );
  16215. iridescenceThickness.assign( iridescenceThicknessNode );
  16216. }
  16217. // ANISOTROPY
  16218. if ( this.useAnisotropy ) {
  16219. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  16220. anisotropy.assign( anisotropyV.length() );
  16221. If( anisotropy.equal( 0.0 ), () => {
  16222. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  16223. } ).Else( () => {
  16224. anisotropyV.divAssign( vec2( anisotropy ) );
  16225. anisotropy.assign( anisotropy.saturate() );
  16226. } );
  16227. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  16228. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  16229. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  16230. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  16231. }
  16232. // TRANSMISSION
  16233. if ( this.useTransmission ) {
  16234. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  16235. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  16236. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  16237. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  16238. transmission.assign( transmissionNode );
  16239. thickness.assign( thicknessNode );
  16240. attenuationDistance.assign( attenuationDistanceNode );
  16241. attenuationColor.assign( attenuationColorNode );
  16242. if ( this.useDispersion ) {
  16243. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  16244. dispersion.assign( dispersionNode );
  16245. }
  16246. }
  16247. }
  16248. /**
  16249. * Setups the clearcoat normal node.
  16250. *
  16251. * @return {Node<vec3>} The clearcoat normal.
  16252. */
  16253. setupClearcoatNormal() {
  16254. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  16255. }
  16256. setup( builder ) {
  16257. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  16258. super.setup( builder );
  16259. }
  16260. copy( source ) {
  16261. this.clearcoatNode = source.clearcoatNode;
  16262. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  16263. this.clearcoatNormalNode = source.clearcoatNormalNode;
  16264. this.sheenNode = source.sheenNode;
  16265. this.sheenRoughnessNode = source.sheenRoughnessNode;
  16266. this.iridescenceNode = source.iridescenceNode;
  16267. this.iridescenceIORNode = source.iridescenceIORNode;
  16268. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  16269. this.specularIntensityNode = source.specularIntensityNode;
  16270. this.specularColorNode = source.specularColorNode;
  16271. this.transmissionNode = source.transmissionNode;
  16272. this.thicknessNode = source.thicknessNode;
  16273. this.attenuationDistanceNode = source.attenuationDistanceNode;
  16274. this.attenuationColorNode = source.attenuationColorNode;
  16275. this.dispersionNode = source.dispersionNode;
  16276. this.anisotropyNode = source.anisotropyNode;
  16277. return super.copy( source );
  16278. }
  16279. }
  16280. /**
  16281. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  16282. *
  16283. * @augments PhysicalLightingModel
  16284. */
  16285. class SSSLightingModel extends PhysicalLightingModel {
  16286. /**
  16287. * Constructs a new physical lighting model.
  16288. *
  16289. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16290. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16291. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16292. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16293. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16294. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16295. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  16296. */
  16297. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  16298. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  16299. /**
  16300. * Whether the lighting model should use SSS or not.
  16301. *
  16302. * @type {boolean}
  16303. * @default false
  16304. */
  16305. this.useSSS = sss;
  16306. }
  16307. /**
  16308. * Extends the default implementation with a SSS term.
  16309. *
  16310. * 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/}
  16311. *
  16312. * @param {Object} input - The input data.
  16313. * @param {NodeBuilder} builder - The current node builder.
  16314. */
  16315. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  16316. if ( this.useSSS === true ) {
  16317. const material = builder.material;
  16318. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  16319. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  16320. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  16321. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  16322. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  16323. }
  16324. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  16325. }
  16326. }
  16327. /**
  16328. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  16329. * that implements a Subsurface scattering (SSS) term.
  16330. *
  16331. * @augments MeshPhysicalNodeMaterial
  16332. */
  16333. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  16334. static get type() {
  16335. return 'MeshSSSNodeMaterial';
  16336. }
  16337. /**
  16338. * Constructs a new mesh SSS node material.
  16339. *
  16340. * @param {Object} [parameters] - The configuration parameter.
  16341. */
  16342. constructor( parameters ) {
  16343. super( parameters );
  16344. /**
  16345. * Represents the thickness color.
  16346. *
  16347. * @type {?Node<vec3>}
  16348. * @default null
  16349. */
  16350. this.thicknessColorNode = null;
  16351. /**
  16352. * Represents the distortion factor.
  16353. *
  16354. * @type {?Node<float>}
  16355. */
  16356. this.thicknessDistortionNode = float( 0.1 );
  16357. /**
  16358. * Represents the thickness ambient factor.
  16359. *
  16360. * @type {?Node<float>}
  16361. */
  16362. this.thicknessAmbientNode = float( 0.0 );
  16363. /**
  16364. * Represents the thickness attenuation.
  16365. *
  16366. * @type {?Node<float>}
  16367. */
  16368. this.thicknessAttenuationNode = float( .1 );
  16369. /**
  16370. * Represents the thickness power.
  16371. *
  16372. * @type {?Node<float>}
  16373. */
  16374. this.thicknessPowerNode = float( 2.0 );
  16375. /**
  16376. * Represents the thickness scale.
  16377. *
  16378. * @type {?Node<float>}
  16379. */
  16380. this.thicknessScaleNode = float( 10.0 );
  16381. }
  16382. /**
  16383. * Whether the lighting model should use SSS or not.
  16384. *
  16385. * @type {boolean}
  16386. * @default true
  16387. */
  16388. get useSSS() {
  16389. return this.thicknessColorNode !== null;
  16390. }
  16391. /**
  16392. * Setups the lighting model.
  16393. *
  16394. * @return {SSSLightingModel} The lighting model.
  16395. */
  16396. setupLightingModel( /*builder*/ ) {
  16397. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  16398. }
  16399. copy( source ) {
  16400. this.thicknessColorNode = source.thicknessColorNode;
  16401. this.thicknessDistortionNode = source.thicknessDistortionNode;
  16402. this.thicknessAmbientNode = source.thicknessAmbientNode;
  16403. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  16404. this.thicknessPowerNode = source.thicknessPowerNode;
  16405. this.thicknessScaleNode = source.thicknessScaleNode;
  16406. return super.copy( source );
  16407. }
  16408. }
  16409. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  16410. // dotNL will be from -1.0 to 1.0
  16411. const dotNL = normal.dot( lightDirection );
  16412. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  16413. if ( builder.material.gradientMap ) {
  16414. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  16415. return vec3( gradientMap.r );
  16416. } else {
  16417. const fw = coord.fwidth().mul( 0.5 );
  16418. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  16419. }
  16420. } );
  16421. /**
  16422. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  16423. *
  16424. * @augments LightingModel
  16425. */
  16426. class ToonLightingModel extends LightingModel {
  16427. /**
  16428. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  16429. * reduced to a small number of discrete shades to create a comic-like, flat look.
  16430. *
  16431. * @param {Object} lightData - The light data.
  16432. * @param {NodeBuilder} builder - The current node builder.
  16433. */
  16434. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  16435. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  16436. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16437. }
  16438. /**
  16439. * Implements the indirect lighting.
  16440. *
  16441. * @param {NodeBuilder} builder - The current node builder.
  16442. */
  16443. indirect( builder ) {
  16444. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16445. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16446. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16447. }
  16448. }
  16449. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  16450. /**
  16451. * Node material version of {@link MeshToonMaterial}.
  16452. *
  16453. * @augments NodeMaterial
  16454. */
  16455. class MeshToonNodeMaterial extends NodeMaterial {
  16456. static get type() {
  16457. return 'MeshToonNodeMaterial';
  16458. }
  16459. /**
  16460. * Constructs a new mesh toon node material.
  16461. *
  16462. * @param {Object} [parameters] - The configuration parameter.
  16463. */
  16464. constructor( parameters ) {
  16465. super();
  16466. /**
  16467. * This flag can be used for type testing.
  16468. *
  16469. * @type {boolean}
  16470. * @readonly
  16471. * @default true
  16472. */
  16473. this.isMeshToonNodeMaterial = true;
  16474. /**
  16475. * Set to `true` because toon materials react on lights.
  16476. *
  16477. * @type {boolean}
  16478. * @default true
  16479. */
  16480. this.lights = true;
  16481. this.setDefaultValues( _defaultValues$4 );
  16482. this.setValues( parameters );
  16483. }
  16484. /**
  16485. * Setups the lighting model.
  16486. *
  16487. * @return {ToonLightingModel} The lighting model.
  16488. */
  16489. setupLightingModel( /*builder*/ ) {
  16490. return new ToonLightingModel();
  16491. }
  16492. }
  16493. /**
  16494. * Can be used to compute texture coordinates for projecting a
  16495. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  16496. *
  16497. * @augments TempNode
  16498. */
  16499. class MatcapUVNode extends TempNode {
  16500. static get type() {
  16501. return 'MatcapUVNode';
  16502. }
  16503. /**
  16504. * Constructs a new matcap uv node.
  16505. */
  16506. constructor() {
  16507. super( 'vec2' );
  16508. }
  16509. setup() {
  16510. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  16511. const y = positionViewDirection.cross( x );
  16512. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  16513. }
  16514. }
  16515. /**
  16516. * TSL function for creating a matcap uv node.
  16517. *
  16518. * @tsl
  16519. * @function
  16520. * @returns {MatcapUVNode}
  16521. */
  16522. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  16523. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  16524. /**
  16525. * Node material version of {@link MeshMatcapMaterial}.
  16526. *
  16527. * @augments NodeMaterial
  16528. */
  16529. class MeshMatcapNodeMaterial extends NodeMaterial {
  16530. static get type() {
  16531. return 'MeshMatcapNodeMaterial';
  16532. }
  16533. /**
  16534. * Constructs a new mesh normal node material.
  16535. *
  16536. * @param {Object} [parameters] - The configuration parameter.
  16537. */
  16538. constructor( parameters ) {
  16539. super();
  16540. /**
  16541. * This flag can be used for type testing.
  16542. *
  16543. * @type {boolean}
  16544. * @readonly
  16545. * @default true
  16546. */
  16547. this.isMeshMatcapNodeMaterial = true;
  16548. this.setDefaultValues( _defaultValues$3 );
  16549. this.setValues( parameters );
  16550. }
  16551. /**
  16552. * Setups the matcap specific node variables.
  16553. *
  16554. * @param {NodeBuilder} builder - The current node builder.
  16555. */
  16556. setupVariants( builder ) {
  16557. const uv = matcapUV;
  16558. let matcapColor;
  16559. if ( builder.material.matcap ) {
  16560. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  16561. } else {
  16562. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  16563. }
  16564. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  16565. }
  16566. }
  16567. /**
  16568. * Applies a rotation to the given position node.
  16569. *
  16570. * @augments TempNode
  16571. */
  16572. class RotateNode extends TempNode {
  16573. static get type() {
  16574. return 'RotateNode';
  16575. }
  16576. /**
  16577. * Constructs a new rotate node.
  16578. *
  16579. * @param {Node} positionNode - The position node.
  16580. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  16581. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  16582. */
  16583. constructor( positionNode, rotationNode ) {
  16584. super();
  16585. /**
  16586. * The position node.
  16587. *
  16588. * @type {Node}
  16589. */
  16590. this.positionNode = positionNode;
  16591. /**
  16592. * Represents the rotation that is applied to the position node.
  16593. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  16594. *
  16595. * @type {Node}
  16596. */
  16597. this.rotationNode = rotationNode;
  16598. }
  16599. /**
  16600. * The type of the {@link RotateNode#positionNode} defines the node's type.
  16601. *
  16602. * @param {NodeBuilder} builder - The current node builder.
  16603. * @return {string} The node's type.
  16604. */
  16605. getNodeType( builder ) {
  16606. return this.positionNode.getNodeType( builder );
  16607. }
  16608. setup( builder ) {
  16609. const { rotationNode, positionNode } = this;
  16610. const nodeType = this.getNodeType( builder );
  16611. if ( nodeType === 'vec2' ) {
  16612. const cosAngle = rotationNode.cos();
  16613. const sinAngle = rotationNode.sin();
  16614. const rotationMatrix = mat2(
  16615. cosAngle, sinAngle,
  16616. sinAngle.negate(), cosAngle
  16617. );
  16618. return rotationMatrix.mul( positionNode );
  16619. } else {
  16620. const rotation = rotationNode;
  16621. 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 ) );
  16622. 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 ) );
  16623. 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 ) );
  16624. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  16625. }
  16626. }
  16627. }
  16628. /**
  16629. * TSL function for creating a rotate node.
  16630. *
  16631. * @tsl
  16632. * @function
  16633. * @param {Node} positionNode - The position node.
  16634. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  16635. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  16636. * @returns {RotateNode}
  16637. */
  16638. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  16639. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  16640. /**
  16641. * Node material version of {@link SpriteMaterial}.
  16642. *
  16643. * @augments NodeMaterial
  16644. */
  16645. class SpriteNodeMaterial extends NodeMaterial {
  16646. static get type() {
  16647. return 'SpriteNodeMaterial';
  16648. }
  16649. /**
  16650. * Constructs a new sprite node material.
  16651. *
  16652. * @param {Object} [parameters] - The configuration parameter.
  16653. */
  16654. constructor( parameters ) {
  16655. super();
  16656. /**
  16657. * This flag can be used for type testing.
  16658. *
  16659. * @type {boolean}
  16660. * @readonly
  16661. * @default true
  16662. */
  16663. this.isSpriteNodeMaterial = true;
  16664. this._useSizeAttenuation = true;
  16665. /**
  16666. * This property makes it possible to define the position of the sprite with a
  16667. * node. That can be useful when the material is used with instanced rendering
  16668. * and node data are defined with an instanced attribute node:
  16669. * ```js
  16670. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  16671. * material.positionNode = instancedBufferAttribute( positionAttribute );
  16672. * ```
  16673. * Another possibility is to compute the instanced data with a compute shader:
  16674. * ```js
  16675. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  16676. * particleMaterial.positionNode = positionBuffer.toAttribute();
  16677. * ```
  16678. *
  16679. * @type {?Node<vec2>}
  16680. * @default null
  16681. */
  16682. this.positionNode = null;
  16683. /**
  16684. * The rotation of sprite materials is by default inferred from the `rotation`,
  16685. * property. This node property allows to overwrite the default and define
  16686. * the rotation with a node instead.
  16687. *
  16688. * If you don't want to overwrite the rotation but modify the existing
  16689. * value instead, use {@link materialRotation}.
  16690. *
  16691. * @type {?Node<float>}
  16692. * @default null
  16693. */
  16694. this.rotationNode = null;
  16695. /**
  16696. * This node property provides an additional way to scale sprites next to
  16697. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  16698. * is multiplied with the scale value of this node in the vertex shader.
  16699. *
  16700. * @type {?Node<vec2>}
  16701. * @default null
  16702. */
  16703. this.scaleNode = null;
  16704. /**
  16705. * In Sprites, the transparent property is enabled by default.
  16706. *
  16707. * @type {boolean}
  16708. * @default true
  16709. */
  16710. this.transparent = true;
  16711. this.setDefaultValues( _defaultValues$2 );
  16712. this.setValues( parameters );
  16713. }
  16714. /**
  16715. * Setups the position node in view space. This method implements
  16716. * the sprite specific vertex shader.
  16717. *
  16718. * @param {NodeBuilder} builder - The current node builder.
  16719. * @return {Node<vec3>} The position in view space.
  16720. */
  16721. setupPositionView( builder ) {
  16722. const { object, camera } = builder;
  16723. const sizeAttenuation = this.sizeAttenuation;
  16724. const { positionNode, rotationNode, scaleNode } = this;
  16725. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  16726. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  16727. if ( scaleNode !== null ) {
  16728. scale = scale.mul( vec2( scaleNode ) );
  16729. }
  16730. if ( sizeAttenuation === false ) {
  16731. if ( camera.isPerspectiveCamera ) {
  16732. scale = scale.mul( mvPosition.z.negate() );
  16733. } else {
  16734. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  16735. scale = scale.mul( orthoScale.mul( 2 ) );
  16736. }
  16737. }
  16738. let alignedPosition = positionGeometry.xy;
  16739. if ( object.center && object.center.isVector2 === true ) {
  16740. const center = reference$1( 'center', 'vec2', object );
  16741. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  16742. }
  16743. alignedPosition = alignedPosition.mul( scale );
  16744. const rotation = float( rotationNode || materialRotation );
  16745. const rotatedPosition = rotate( alignedPosition, rotation );
  16746. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  16747. }
  16748. copy( source ) {
  16749. this.positionNode = source.positionNode;
  16750. this.rotationNode = source.rotationNode;
  16751. this.scaleNode = source.scaleNode;
  16752. return super.copy( source );
  16753. }
  16754. /**
  16755. * Whether to use size attenuation or not.
  16756. *
  16757. * @type {boolean}
  16758. * @default true
  16759. */
  16760. get sizeAttenuation() {
  16761. return this._useSizeAttenuation;
  16762. }
  16763. set sizeAttenuation( value ) {
  16764. if ( this._useSizeAttenuation !== value ) {
  16765. this._useSizeAttenuation = value;
  16766. this.needsUpdate = true;
  16767. }
  16768. }
  16769. }
  16770. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  16771. /**
  16772. * Node material version of {@link PointsMaterial}.
  16773. *
  16774. * @augments SpriteNodeMaterial
  16775. */
  16776. class PointsNodeMaterial extends SpriteNodeMaterial {
  16777. static get type() {
  16778. return 'PointsNodeMaterial';
  16779. }
  16780. /**
  16781. * Constructs a new points node material.
  16782. *
  16783. * @param {Object} [parameters] - The configuration parameter.
  16784. */
  16785. constructor( parameters ) {
  16786. super();
  16787. /**
  16788. * This node property provides an additional way to set the point size.
  16789. *
  16790. * @type {?Node<vec2>}
  16791. * @default null
  16792. */
  16793. this.sizeNode = null;
  16794. /**
  16795. * This flag can be used for type testing.
  16796. *
  16797. * @type {boolean}
  16798. * @readonly
  16799. * @default true
  16800. */
  16801. this.isPointsNodeMaterial = true;
  16802. this.setDefaultValues( _defaultValues$1 );
  16803. this.setValues( parameters );
  16804. }
  16805. setupPositionView() {
  16806. const { positionNode } = this;
  16807. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  16808. }
  16809. setupVertex( builder ) {
  16810. const mvp = super.setupVertex( builder );
  16811. // skip further processing if the material is not a node material
  16812. if ( builder.material.isNodeMaterial !== true ) {
  16813. return mvp;
  16814. }
  16815. // ndc space
  16816. const { rotationNode, scaleNode, sizeNode } = this;
  16817. const alignedPosition = positionGeometry.xy.toVar();
  16818. const aspect = viewport.z.div( viewport.w );
  16819. // rotation
  16820. if ( rotationNode && rotationNode.isNode ) {
  16821. const rotation = float( rotationNode );
  16822. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  16823. }
  16824. // point size
  16825. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  16826. if ( this.sizeAttenuation === true ) {
  16827. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  16828. }
  16829. // scale
  16830. if ( scaleNode && scaleNode.isNode ) {
  16831. pointSize = pointSize.mul( vec2( scaleNode ) );
  16832. }
  16833. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  16834. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  16835. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  16836. // back to clip space
  16837. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  16838. //clipPos.xy += offset;
  16839. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  16840. return mvp;
  16841. }
  16842. /**
  16843. * Whether alpha to coverage should be used or not.
  16844. *
  16845. * @type {boolean}
  16846. * @default true
  16847. */
  16848. get alphaToCoverage() {
  16849. return this._useAlphaToCoverage;
  16850. }
  16851. set alphaToCoverage( value ) {
  16852. if ( this._useAlphaToCoverage !== value ) {
  16853. this._useAlphaToCoverage = value;
  16854. this.needsUpdate = true;
  16855. }
  16856. }
  16857. }
  16858. /**
  16859. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  16860. *
  16861. * @augments LightingModel
  16862. */
  16863. class ShadowMaskModel extends LightingModel {
  16864. /**
  16865. * Constructs a new shadow mask model.
  16866. */
  16867. constructor() {
  16868. super();
  16869. /**
  16870. * The shadow mask node.
  16871. *
  16872. * @type {Node}
  16873. */
  16874. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  16875. }
  16876. /**
  16877. * Only used to save the shadow mask.
  16878. *
  16879. * @param {Object} input - The input data.
  16880. */
  16881. direct( { lightNode } ) {
  16882. this.shadowNode.mulAssign( lightNode.shadowNode );
  16883. }
  16884. /**
  16885. * Uses the shadow mask to produce the final color.
  16886. *
  16887. * @param {NodeBuilder} builder - The current node builder.
  16888. */
  16889. finish( { context } ) {
  16890. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  16891. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  16892. }
  16893. }
  16894. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  16895. /**
  16896. * Node material version of {@link ShadowMaterial}.
  16897. *
  16898. * @augments NodeMaterial
  16899. */
  16900. class ShadowNodeMaterial extends NodeMaterial {
  16901. static get type() {
  16902. return 'ShadowNodeMaterial';
  16903. }
  16904. /**
  16905. * Constructs a new shadow node material.
  16906. *
  16907. * @param {Object} [parameters] - The configuration parameter.
  16908. */
  16909. constructor( parameters ) {
  16910. super();
  16911. /**
  16912. * This flag can be used for type testing.
  16913. *
  16914. * @type {boolean}
  16915. * @readonly
  16916. * @default true
  16917. */
  16918. this.isShadowNodeMaterial = true;
  16919. /**
  16920. * Set to `true` because so it's possible to implement
  16921. * the shadow mask effect.
  16922. *
  16923. * @type {boolean}
  16924. * @default true
  16925. */
  16926. this.lights = true;
  16927. /**
  16928. * Overwritten since shadow materials are transparent
  16929. * by default.
  16930. *
  16931. * @type {boolean}
  16932. * @default true
  16933. */
  16934. this.transparent = true;
  16935. this.setDefaultValues( _defaultValues );
  16936. this.setValues( parameters );
  16937. }
  16938. /**
  16939. * Setups the lighting model.
  16940. *
  16941. * @return {ShadowMaskModel} The lighting model.
  16942. */
  16943. setupLightingModel( /*builder*/ ) {
  16944. return new ShadowMaskModel();
  16945. }
  16946. }
  16947. const scatteringDensity = property( 'vec3' );
  16948. const linearDepthRay = property( 'vec3' );
  16949. const outgoingRayLight = property( 'vec3' );
  16950. /**
  16951. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  16952. * This model calculates the scattering and transmittance of light through a volumetric medium.
  16953. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  16954. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  16955. *
  16956. * @augments LightingModel
  16957. */
  16958. class VolumetricLightingModel extends LightingModel {
  16959. constructor() {
  16960. super();
  16961. }
  16962. start( builder ) {
  16963. const { material, context } = builder;
  16964. const startPos = property( 'vec3' );
  16965. const endPos = property( 'vec3' );
  16966. // This approach dynamically changes the direction of the ray,
  16967. // prioritizing the ray from the camera to the object if it is inside the mesh, and from the object to the camera if it is far away.
  16968. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  16969. startPos.assign( cameraPosition );
  16970. endPos.assign( positionWorld );
  16971. } ).Else( () => {
  16972. startPos.assign( positionWorld );
  16973. endPos.assign( cameraPosition );
  16974. } );
  16975. //
  16976. const viewVector = endPos.sub( startPos );
  16977. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  16978. const stepSize = viewVector.length().div( steps ).toVar();
  16979. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  16980. const distTravelled = float( 0.0 ).toVar();
  16981. const transmittance = vec3( 1 ).toVar();
  16982. if ( material.offsetNode ) {
  16983. // reduce banding
  16984. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  16985. }
  16986. Loop( steps, () => {
  16987. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  16988. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  16989. if ( material.depthNode !== null ) {
  16990. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  16991. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  16992. }
  16993. context.positionWorld = positionRay;
  16994. context.shadowPositionWorld = positionRay;
  16995. context.positionView = positionViewRay;
  16996. scatteringDensity.assign( 0 );
  16997. let scatteringNode;
  16998. if ( material.scatteringNode ) {
  16999. scatteringNode = material.scatteringNode( {
  17000. positionRay
  17001. } );
  17002. }
  17003. super.start( builder );
  17004. if ( scatteringNode ) {
  17005. scatteringDensity.mulAssign( scatteringNode );
  17006. }
  17007. // beer's law
  17008. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  17009. transmittance.mulAssign( falloff );
  17010. // move along the ray
  17011. distTravelled.addAssign( stepSize );
  17012. } );
  17013. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  17014. }
  17015. scatteringLight( lightColor, builder ) {
  17016. const sceneDepthNode = builder.context.sceneDepthNode;
  17017. if ( sceneDepthNode ) {
  17018. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  17019. scatteringDensity.addAssign( lightColor );
  17020. } );
  17021. } else {
  17022. scatteringDensity.addAssign( lightColor );
  17023. }
  17024. }
  17025. direct( { lightNode, lightColor }, builder ) {
  17026. // Ignore lights with infinite distance
  17027. if ( lightNode.light.distance === undefined ) return;
  17028. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  17029. const directLight = lightColor.xyz.toVar();
  17030. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  17031. this.scatteringLight( directLight, builder );
  17032. }
  17033. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  17034. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17035. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17036. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17037. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17038. const P = builder.context.positionView;
  17039. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  17040. this.scatteringLight( directLight, builder );
  17041. }
  17042. finish( builder ) {
  17043. builder.context.outgoingLight.assign( outgoingRayLight );
  17044. }
  17045. }
  17046. /**
  17047. * Volume node material.
  17048. *
  17049. * @augments NodeMaterial
  17050. */
  17051. class VolumeNodeMaterial extends NodeMaterial {
  17052. static get type() {
  17053. return 'VolumeNodeMaterial';
  17054. }
  17055. /**
  17056. * Constructs a new volume node material.
  17057. *
  17058. * @param {Object} [parameters] - The configuration parameter.
  17059. */
  17060. constructor( parameters ) {
  17061. super();
  17062. /**
  17063. * This flag can be used for type testing.
  17064. *
  17065. * @type {boolean}
  17066. * @readonly
  17067. * @default true
  17068. */
  17069. this.isVolumeNodeMaterial = true;
  17070. /**
  17071. * Number of steps used for raymarching.
  17072. *
  17073. * @type {number}
  17074. * @default 25
  17075. */
  17076. this.steps = 25;
  17077. /**
  17078. * Offsets the distance a ray has been traveled through a volume.
  17079. * Can be used to implement dithering to reduce banding.
  17080. *
  17081. * @type {Node<float>}
  17082. * @default null
  17083. */
  17084. this.offsetNode = null;
  17085. /**
  17086. * Node used for scattering calculations.
  17087. *
  17088. * @type {Function|FunctionNode<vec4>}
  17089. * @default null
  17090. */
  17091. this.scatteringNode = null;
  17092. this.lights = true;
  17093. this.transparent = true;
  17094. this.side = BackSide;
  17095. this.depthTest = false;
  17096. this.depthWrite = false;
  17097. this.setValues( parameters );
  17098. }
  17099. setupLightingModel() {
  17100. return new VolumetricLightingModel();
  17101. }
  17102. }
  17103. /**
  17104. * This module manages the internal animation loop of the renderer.
  17105. *
  17106. * @private
  17107. */
  17108. class Animation {
  17109. /**
  17110. * Constructs a new animation loop management component.
  17111. *
  17112. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17113. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17114. */
  17115. constructor( nodes, info ) {
  17116. /**
  17117. * Renderer component for managing nodes related logic.
  17118. *
  17119. * @type {Nodes}
  17120. */
  17121. this.nodes = nodes;
  17122. /**
  17123. * Renderer component for managing metrics and monitoring data.
  17124. *
  17125. * @type {Info}
  17126. */
  17127. this.info = info;
  17128. /**
  17129. * A reference to the context from `requestAnimationFrame()` can
  17130. * be called (usually `window`).
  17131. *
  17132. * @type {Window|XRSession}
  17133. */
  17134. this._context = self;
  17135. /**
  17136. * The user-defined animation loop.
  17137. *
  17138. * @type {?Function}
  17139. * @default null
  17140. */
  17141. this._animationLoop = null;
  17142. /**
  17143. * The requestId which is returned from the `requestAnimationFrame()` call.
  17144. * Can be used to cancel the stop the animation loop.
  17145. *
  17146. * @type {?number}
  17147. * @default null
  17148. */
  17149. this._requestId = null;
  17150. }
  17151. /**
  17152. * Starts the internal animation loop.
  17153. */
  17154. start() {
  17155. const update = ( time, xrFrame ) => {
  17156. this._requestId = this._context.requestAnimationFrame( update );
  17157. if ( this.info.autoReset === true ) this.info.reset();
  17158. this.nodes.nodeFrame.update();
  17159. this.info.frame = this.nodes.nodeFrame.frameId;
  17160. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  17161. };
  17162. update();
  17163. }
  17164. /**
  17165. * Stops the internal animation loop.
  17166. */
  17167. stop() {
  17168. this._context.cancelAnimationFrame( this._requestId );
  17169. this._requestId = null;
  17170. }
  17171. /**
  17172. * Returns the user-level animation loop.
  17173. *
  17174. * @return {?Function} The animation loop.
  17175. */
  17176. getAnimationLoop() {
  17177. return this._animationLoop;
  17178. }
  17179. /**
  17180. * Defines the user-level animation loop.
  17181. *
  17182. * @param {?Function} callback - The animation loop.
  17183. */
  17184. setAnimationLoop( callback ) {
  17185. this._animationLoop = callback;
  17186. }
  17187. /**
  17188. * Returns the animation context.
  17189. *
  17190. * @return {Window|XRSession} The animation context.
  17191. */
  17192. getContext() {
  17193. return this._context;
  17194. }
  17195. /**
  17196. * Defines the context in which `requestAnimationFrame()` is executed.
  17197. *
  17198. * @param {Window|XRSession} context - The context to set.
  17199. */
  17200. setContext( context ) {
  17201. this._context = context;
  17202. }
  17203. /**
  17204. * Frees all internal resources and stops the animation loop.
  17205. */
  17206. dispose() {
  17207. this.stop();
  17208. }
  17209. }
  17210. /**
  17211. * Data structure for the renderer. It allows defining values
  17212. * with chained, hierarchical keys. Keys are meant to be
  17213. * objects since the module internally works with Weak Maps
  17214. * for performance reasons.
  17215. *
  17216. * @private
  17217. */
  17218. class ChainMap {
  17219. /**
  17220. * Constructs a new Chain Map.
  17221. */
  17222. constructor() {
  17223. /**
  17224. * The root Weak Map.
  17225. *
  17226. * @type {WeakMap}
  17227. */
  17228. this.weakMap = new WeakMap();
  17229. }
  17230. /**
  17231. * Returns the value for the given array of keys.
  17232. *
  17233. * @param {Array<Object>} keys - List of keys.
  17234. * @return {any} The value. Returns `undefined` if no value was found.
  17235. */
  17236. get( keys ) {
  17237. let map = this.weakMap;
  17238. for ( let i = 0; i < keys.length - 1; i ++ ) {
  17239. map = map.get( keys[ i ] );
  17240. if ( map === undefined ) return undefined;
  17241. }
  17242. return map.get( keys[ keys.length - 1 ] );
  17243. }
  17244. /**
  17245. * Sets the value for the given keys.
  17246. *
  17247. * @param {Array<Object>} keys - List of keys.
  17248. * @param {any} value - The value to set.
  17249. * @return {ChainMap} A reference to this Chain Map.
  17250. */
  17251. set( keys, value ) {
  17252. let map = this.weakMap;
  17253. for ( let i = 0; i < keys.length - 1; i ++ ) {
  17254. const key = keys[ i ];
  17255. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  17256. map = map.get( key );
  17257. }
  17258. map.set( keys[ keys.length - 1 ], value );
  17259. return this;
  17260. }
  17261. /**
  17262. * Deletes a value for the given keys.
  17263. *
  17264. * @param {Array<Object>} keys - The keys.
  17265. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  17266. */
  17267. delete( keys ) {
  17268. let map = this.weakMap;
  17269. for ( let i = 0; i < keys.length - 1; i ++ ) {
  17270. map = map.get( keys[ i ] );
  17271. if ( map === undefined ) return false;
  17272. }
  17273. return map.delete( keys[ keys.length - 1 ] );
  17274. }
  17275. }
  17276. let _id$9 = 0;
  17277. function getKeys( obj ) {
  17278. const keys = Object.keys( obj );
  17279. let proto = Object.getPrototypeOf( obj );
  17280. while ( proto ) {
  17281. const descriptors = Object.getOwnPropertyDescriptors( proto );
  17282. for ( const key in descriptors ) {
  17283. if ( descriptors[ key ] !== undefined ) {
  17284. const descriptor = descriptors[ key ];
  17285. if ( descriptor && typeof descriptor.get === 'function' ) {
  17286. keys.push( key );
  17287. }
  17288. }
  17289. }
  17290. proto = Object.getPrototypeOf( proto );
  17291. }
  17292. return keys;
  17293. }
  17294. /**
  17295. * A render object is the renderer's representation of single entity that gets drawn
  17296. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  17297. * scene since render objects also depend from the used material, the current render context
  17298. * and the current scene's lighting.
  17299. *
  17300. * In general, the basic process of the renderer is:
  17301. *
  17302. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  17303. * - Process the render lists by calling one or more render commands for each render item.
  17304. * - For each render command, request a render object and perform the draw.
  17305. *
  17306. * The module provides an interface to get data required for the draw command like the actual
  17307. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  17308. * creating render objects should only be done when necessary.
  17309. *
  17310. * @private
  17311. */
  17312. class RenderObject {
  17313. /**
  17314. * Constructs a new render object.
  17315. *
  17316. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17317. * @param {Geometries} geometries - Renderer component for managing geometries.
  17318. * @param {Renderer} renderer - The renderer.
  17319. * @param {Object3D} object - The 3D object.
  17320. * @param {Material} material - The 3D object's material.
  17321. * @param {Scene} scene - The scene the 3D object belongs to.
  17322. * @param {Camera} camera - The camera the object should be rendered with.
  17323. * @param {LightsNode} lightsNode - The lights node.
  17324. * @param {RenderContext} renderContext - The render context.
  17325. * @param {ClippingContext} clippingContext - The clipping context.
  17326. */
  17327. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  17328. this.id = _id$9 ++;
  17329. /**
  17330. * Renderer component for managing nodes related logic.
  17331. *
  17332. * @type {Nodes}
  17333. * @private
  17334. */
  17335. this._nodes = nodes;
  17336. /**
  17337. * Renderer component for managing geometries.
  17338. *
  17339. * @type {Geometries}
  17340. * @private
  17341. */
  17342. this._geometries = geometries;
  17343. /**
  17344. * The renderer.
  17345. *
  17346. * @type {Renderer}
  17347. */
  17348. this.renderer = renderer;
  17349. /**
  17350. * The 3D object.
  17351. *
  17352. * @type {Object3D}
  17353. */
  17354. this.object = object;
  17355. /**
  17356. * The 3D object's material.
  17357. *
  17358. * @type {Material}
  17359. */
  17360. this.material = material;
  17361. /**
  17362. * The scene the 3D object belongs to.
  17363. *
  17364. * @type {Scene}
  17365. */
  17366. this.scene = scene;
  17367. /**
  17368. * The camera the 3D object should be rendered with.
  17369. *
  17370. * @type {Camera}
  17371. */
  17372. this.camera = camera;
  17373. /**
  17374. * The lights node.
  17375. *
  17376. * @type {LightsNode}
  17377. */
  17378. this.lightsNode = lightsNode;
  17379. /**
  17380. * The render context.
  17381. *
  17382. * @type {RenderContext}
  17383. */
  17384. this.context = renderContext;
  17385. /**
  17386. * The 3D object's geometry.
  17387. *
  17388. * @type {BufferGeometry}
  17389. */
  17390. this.geometry = object.geometry;
  17391. /**
  17392. * The render object's version.
  17393. *
  17394. * @type {number}
  17395. */
  17396. this.version = material.version;
  17397. /**
  17398. * The draw range of the geometry.
  17399. *
  17400. * @type {?Object}
  17401. * @default null
  17402. */
  17403. this.drawRange = null;
  17404. /**
  17405. * An array holding the buffer attributes
  17406. * of the render object. This entails attribute
  17407. * definitions on geometry and node level.
  17408. *
  17409. * @type {?Array<BufferAttribute>}
  17410. * @default null
  17411. */
  17412. this.attributes = null;
  17413. /**
  17414. * A reference to a render pipeline the render
  17415. * object is processed with.
  17416. *
  17417. * @type {RenderPipeline}
  17418. * @default null
  17419. */
  17420. this.pipeline = null;
  17421. /**
  17422. * Only relevant for objects using
  17423. * multiple materials. This represents a group entry
  17424. * from the respective `BufferGeometry`.
  17425. *
  17426. * @type {?{start: number, count: number}}
  17427. * @default null
  17428. */
  17429. this.group = null;
  17430. /**
  17431. * An array holding the vertex buffers which can
  17432. * be buffer attributes but also interleaved buffers.
  17433. *
  17434. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  17435. * @default null
  17436. */
  17437. this.vertexBuffers = null;
  17438. /**
  17439. * The parameters for the draw command.
  17440. *
  17441. * @type {?Object}
  17442. * @default null
  17443. */
  17444. this.drawParams = null;
  17445. /**
  17446. * If this render object is used inside a render bundle,
  17447. * this property points to the respective bundle group.
  17448. *
  17449. * @type {?BundleGroup}
  17450. * @default null
  17451. */
  17452. this.bundle = null;
  17453. /**
  17454. * The clipping context.
  17455. *
  17456. * @type {ClippingContext}
  17457. */
  17458. this.clippingContext = clippingContext;
  17459. /**
  17460. * The clipping context's cache key.
  17461. *
  17462. * @type {string}
  17463. */
  17464. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  17465. /**
  17466. * The initial node cache key.
  17467. *
  17468. * @type {number}
  17469. */
  17470. this.initialNodesCacheKey = this.getDynamicCacheKey();
  17471. /**
  17472. * The initial cache key.
  17473. *
  17474. * @type {number}
  17475. */
  17476. this.initialCacheKey = this.getCacheKey();
  17477. /**
  17478. * The node builder state.
  17479. *
  17480. * @type {?NodeBuilderState}
  17481. * @private
  17482. * @default null
  17483. */
  17484. this._nodeBuilderState = null;
  17485. /**
  17486. * An array of bindings.
  17487. *
  17488. * @type {?Array<BindGroup>}
  17489. * @private
  17490. * @default null
  17491. */
  17492. this._bindings = null;
  17493. /**
  17494. * Reference to the node material observer.
  17495. *
  17496. * @type {?NodeMaterialObserver}
  17497. * @private
  17498. * @default null
  17499. */
  17500. this._monitor = null;
  17501. /**
  17502. * An event listener which is defined by `RenderObjects`. It performs
  17503. * clean up tasks when `dispose()` on this render object.
  17504. *
  17505. * @method
  17506. */
  17507. this.onDispose = null;
  17508. /**
  17509. * This flag can be used for type testing.
  17510. *
  17511. * @type {boolean}
  17512. * @readonly
  17513. * @default true
  17514. */
  17515. this.isRenderObject = true;
  17516. /**
  17517. * An event listener which is executed when `dispose()` is called on
  17518. * the render object's material.
  17519. *
  17520. * @method
  17521. */
  17522. this.onMaterialDispose = () => {
  17523. this.dispose();
  17524. };
  17525. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  17526. }
  17527. /**
  17528. * Updates the clipping context.
  17529. *
  17530. * @param {ClippingContext} context - The clipping context to set.
  17531. */
  17532. updateClipping( context ) {
  17533. this.clippingContext = context;
  17534. }
  17535. /**
  17536. * Whether the clipping requires an update or not.
  17537. *
  17538. * @type {boolean}
  17539. * @readonly
  17540. */
  17541. get clippingNeedsUpdate() {
  17542. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  17543. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  17544. return true;
  17545. }
  17546. /**
  17547. * The number of clipping planes defined in context of hardware clipping.
  17548. *
  17549. * @type {number}
  17550. * @readonly
  17551. */
  17552. get hardwareClippingPlanes() {
  17553. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  17554. }
  17555. /**
  17556. * Returns the node builder state of this render object.
  17557. *
  17558. * @return {NodeBuilderState} The node builder state.
  17559. */
  17560. getNodeBuilderState() {
  17561. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  17562. }
  17563. /**
  17564. * Returns the node material observer of this render object.
  17565. *
  17566. * @return {NodeMaterialObserver} The node material observer.
  17567. */
  17568. getMonitor() {
  17569. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  17570. }
  17571. /**
  17572. * Returns an array of bind groups of this render object.
  17573. *
  17574. * @return {Array<BindGroup>} The bindings.
  17575. */
  17576. getBindings() {
  17577. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  17578. }
  17579. /**
  17580. * Returns a binding group by group name of this render object.
  17581. *
  17582. * @param {string} name - The name of the binding group.
  17583. * @return {?BindGroup} The bindings.
  17584. */
  17585. getBindingGroup( name ) {
  17586. for ( const bindingGroup of this.getBindings() ) {
  17587. if ( bindingGroup.name === name ) {
  17588. return bindingGroup;
  17589. }
  17590. }
  17591. }
  17592. /**
  17593. * Returns the index of the render object's geometry.
  17594. *
  17595. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  17596. */
  17597. getIndex() {
  17598. return this._geometries.getIndex( this );
  17599. }
  17600. /**
  17601. * Returns the indirect buffer attribute.
  17602. *
  17603. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  17604. */
  17605. getIndirect() {
  17606. return this._geometries.getIndirect( this );
  17607. }
  17608. /**
  17609. * Returns an array that acts as a key for identifying the render object in a chain map.
  17610. *
  17611. * @return {Array<Object>} An array with object references.
  17612. */
  17613. getChainArray() {
  17614. return [ this.object, this.material, this.context, this.lightsNode ];
  17615. }
  17616. /**
  17617. * This method is used when the geometry of a 3D object has been exchanged and the
  17618. * respective render object now requires an update.
  17619. *
  17620. * @param {BufferGeometry} geometry - The geometry to set.
  17621. */
  17622. setGeometry( geometry ) {
  17623. this.geometry = geometry;
  17624. this.attributes = null;
  17625. }
  17626. /**
  17627. * Returns the buffer attributes of the render object. The returned array holds
  17628. * attribute definitions on geometry and node level.
  17629. *
  17630. * @return {Array<BufferAttribute>} An array with buffer attributes.
  17631. */
  17632. getAttributes() {
  17633. if ( this.attributes !== null ) return this.attributes;
  17634. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  17635. const geometry = this.geometry;
  17636. const attributes = [];
  17637. const vertexBuffers = new Set();
  17638. for ( const nodeAttribute of nodeAttributes ) {
  17639. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  17640. if ( attribute === undefined ) continue;
  17641. attributes.push( attribute );
  17642. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  17643. vertexBuffers.add( bufferAttribute );
  17644. }
  17645. this.attributes = attributes;
  17646. this.vertexBuffers = Array.from( vertexBuffers.values() );
  17647. return attributes;
  17648. }
  17649. /**
  17650. * Returns the vertex buffers of the render object.
  17651. *
  17652. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  17653. */
  17654. getVertexBuffers() {
  17655. if ( this.vertexBuffers === null ) this.getAttributes();
  17656. return this.vertexBuffers;
  17657. }
  17658. /**
  17659. * Returns the draw parameters for the render object.
  17660. *
  17661. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  17662. */
  17663. getDrawParameters() {
  17664. const { object, material, geometry, group, drawRange } = this;
  17665. const drawParams = this.drawParams || ( this.drawParams = {
  17666. vertexCount: 0,
  17667. firstVertex: 0,
  17668. instanceCount: 0,
  17669. firstInstance: 0
  17670. } );
  17671. const index = this.getIndex();
  17672. const hasIndex = ( index !== null );
  17673. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  17674. if ( instanceCount === 0 ) return null;
  17675. drawParams.instanceCount = instanceCount;
  17676. if ( object.isBatchedMesh === true ) return drawParams;
  17677. let rangeFactor = 1;
  17678. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  17679. rangeFactor = 2;
  17680. }
  17681. let firstVertex = drawRange.start * rangeFactor;
  17682. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  17683. if ( group !== null ) {
  17684. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  17685. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  17686. }
  17687. const position = geometry.attributes.position;
  17688. let itemCount = Infinity;
  17689. if ( hasIndex ) {
  17690. itemCount = index.count;
  17691. } else if ( position !== undefined && position !== null ) {
  17692. itemCount = position.count;
  17693. }
  17694. firstVertex = Math.max( firstVertex, 0 );
  17695. lastVertex = Math.min( lastVertex, itemCount );
  17696. const count = lastVertex - firstVertex;
  17697. if ( count < 0 || count === Infinity ) return null;
  17698. drawParams.vertexCount = count;
  17699. drawParams.firstVertex = firstVertex;
  17700. return drawParams;
  17701. }
  17702. /**
  17703. * Returns the render object's geometry cache key.
  17704. *
  17705. * The geometry cache key is part of the material cache key.
  17706. *
  17707. * @return {string} The geometry cache key.
  17708. */
  17709. getGeometryCacheKey() {
  17710. const { geometry } = this;
  17711. let cacheKey = '';
  17712. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  17713. const attribute = geometry.attributes[ name ];
  17714. cacheKey += name + ',';
  17715. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  17716. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  17717. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  17718. if ( attribute.normalized ) cacheKey += 'n,';
  17719. }
  17720. // structural equality isn't sufficient for morph targets since the
  17721. // data are maintained in textures. only if the targets are all equal
  17722. // the texture and thus the instance of `MorphNode` can be shared.
  17723. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  17724. const targets = geometry.morphAttributes[ name ];
  17725. cacheKey += 'morph-' + name + ',';
  17726. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  17727. const attribute = targets[ i ];
  17728. cacheKey += attribute.id + ',';
  17729. }
  17730. }
  17731. if ( geometry.index ) {
  17732. cacheKey += 'index,';
  17733. }
  17734. return cacheKey;
  17735. }
  17736. /**
  17737. * Returns the render object's material cache key.
  17738. *
  17739. * The material cache key is part of the render object cache key.
  17740. *
  17741. * @return {number} The material cache key.
  17742. */
  17743. getMaterialCacheKey() {
  17744. const { object, material } = this;
  17745. let cacheKey = material.customProgramCacheKey();
  17746. for ( const property of getKeys( material ) ) {
  17747. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  17748. const value = material[ property ];
  17749. let valueKey;
  17750. if ( value !== null ) {
  17751. // some material values require a formatting
  17752. const type = typeof value;
  17753. if ( type === 'number' ) {
  17754. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  17755. } else if ( type === 'object' ) {
  17756. valueKey = '{';
  17757. if ( value.isTexture ) {
  17758. valueKey += value.mapping;
  17759. }
  17760. valueKey += '}';
  17761. } else {
  17762. valueKey = String( value );
  17763. }
  17764. } else {
  17765. valueKey = String( value );
  17766. }
  17767. cacheKey += /*property + ':' +*/ valueKey + ',';
  17768. }
  17769. cacheKey += this.clippingContextCacheKey + ',';
  17770. if ( object.geometry ) {
  17771. cacheKey += this.getGeometryCacheKey();
  17772. }
  17773. if ( object.skeleton ) {
  17774. cacheKey += object.skeleton.bones.length + ',';
  17775. }
  17776. if ( object.isBatchedMesh ) {
  17777. cacheKey += object._matricesTexture.uuid + ',';
  17778. if ( object._colorsTexture !== null ) {
  17779. cacheKey += object._colorsTexture.uuid + ',';
  17780. }
  17781. }
  17782. if ( object.count > 1 ) {
  17783. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  17784. cacheKey += object.uuid + ',';
  17785. }
  17786. cacheKey += object.receiveShadow + ',';
  17787. return hashString( cacheKey );
  17788. }
  17789. /**
  17790. * Whether the geometry requires an update or not.
  17791. *
  17792. * @type {boolean}
  17793. * @readonly
  17794. */
  17795. get needsGeometryUpdate() {
  17796. return this.geometry.id !== this.object.geometry.id;
  17797. }
  17798. /**
  17799. * Whether the render object requires an update or not.
  17800. *
  17801. * Note: There are two distinct places where render objects are checked for an update.
  17802. *
  17803. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  17804. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  17805. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  17806. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  17807. * a need for a refresh due to material, geometry or object related value changes.
  17808. *
  17809. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  17810. * that performs the 'needsUpdate' check.
  17811. *
  17812. * @type {boolean}
  17813. * @readonly
  17814. */
  17815. get needsUpdate() {
  17816. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  17817. }
  17818. /**
  17819. * Returns the dynamic cache key which represents a key that is computed per draw command.
  17820. *
  17821. * @return {number} The cache key.
  17822. */
  17823. getDynamicCacheKey() {
  17824. let cacheKey = 0;
  17825. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  17826. // the renderer is inside a shadow pass.
  17827. if ( this.material.isShadowPassMaterial !== true ) {
  17828. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  17829. }
  17830. if ( this.camera.isArrayCamera ) {
  17831. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  17832. }
  17833. if ( this.object.receiveShadow ) {
  17834. cacheKey = hash$1( cacheKey, 1 );
  17835. }
  17836. return cacheKey;
  17837. }
  17838. /**
  17839. * Returns the render object's cache key.
  17840. *
  17841. * @return {number} The cache key.
  17842. */
  17843. getCacheKey() {
  17844. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  17845. }
  17846. /**
  17847. * Frees internal resources.
  17848. */
  17849. dispose() {
  17850. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  17851. this.onDispose();
  17852. }
  17853. }
  17854. const _chainKeys$5 = [];
  17855. /**
  17856. * This module manages the render objects of the renderer.
  17857. *
  17858. * @private
  17859. */
  17860. class RenderObjects {
  17861. /**
  17862. * Constructs a new render object management component.
  17863. *
  17864. * @param {Renderer} renderer - The renderer.
  17865. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17866. * @param {Geometries} geometries - Renderer component for managing geometries.
  17867. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17868. * @param {Bindings} bindings - Renderer component for managing bindings.
  17869. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17870. */
  17871. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  17872. /**
  17873. * The renderer.
  17874. *
  17875. * @type {Renderer}
  17876. */
  17877. this.renderer = renderer;
  17878. /**
  17879. * Renderer component for managing nodes related logic.
  17880. *
  17881. * @type {Nodes}
  17882. */
  17883. this.nodes = nodes;
  17884. /**
  17885. * Renderer component for managing geometries.
  17886. *
  17887. * @type {Geometries}
  17888. */
  17889. this.geometries = geometries;
  17890. /**
  17891. * Renderer component for managing pipelines.
  17892. *
  17893. * @type {Pipelines}
  17894. */
  17895. this.pipelines = pipelines;
  17896. /**
  17897. * Renderer component for managing bindings.
  17898. *
  17899. * @type {Bindings}
  17900. */
  17901. this.bindings = bindings;
  17902. /**
  17903. * Renderer component for managing metrics and monitoring data.
  17904. *
  17905. * @type {Info}
  17906. */
  17907. this.info = info;
  17908. /**
  17909. * A dictionary that manages render contexts in chain maps
  17910. * for each pass ID.
  17911. *
  17912. * @type {Object<string,ChainMap>}
  17913. */
  17914. this.chainMaps = {};
  17915. }
  17916. /**
  17917. * Returns a render object for the given object and state data.
  17918. *
  17919. * @param {Object3D} object - The 3D object.
  17920. * @param {Material} material - The 3D object's material.
  17921. * @param {Scene} scene - The scene the 3D object belongs to.
  17922. * @param {Camera} camera - The camera the 3D object should be rendered with.
  17923. * @param {LightsNode} lightsNode - The lights node.
  17924. * @param {RenderContext} renderContext - The render context.
  17925. * @param {ClippingContext} clippingContext - The clipping context.
  17926. * @param {string} [passId] - An optional ID for identifying the pass.
  17927. * @return {RenderObject} The render object.
  17928. */
  17929. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17930. const chainMap = this.getChainMap( passId );
  17931. // reuse chainArray
  17932. _chainKeys$5[ 0 ] = object;
  17933. _chainKeys$5[ 1 ] = material;
  17934. _chainKeys$5[ 2 ] = renderContext;
  17935. _chainKeys$5[ 3 ] = lightsNode;
  17936. let renderObject = chainMap.get( _chainKeys$5 );
  17937. if ( renderObject === undefined ) {
  17938. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17939. chainMap.set( _chainKeys$5, renderObject );
  17940. } else {
  17941. renderObject.updateClipping( clippingContext );
  17942. if ( renderObject.needsGeometryUpdate ) {
  17943. renderObject.setGeometry( object.geometry );
  17944. }
  17945. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  17946. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  17947. renderObject.dispose();
  17948. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17949. } else {
  17950. renderObject.version = material.version;
  17951. }
  17952. }
  17953. }
  17954. _chainKeys$5.length = 0;
  17955. return renderObject;
  17956. }
  17957. /**
  17958. * Returns a chain map for the given pass ID.
  17959. *
  17960. * @param {string} [passId='default'] - The pass ID.
  17961. * @return {ChainMap} The chain map.
  17962. */
  17963. getChainMap( passId = 'default' ) {
  17964. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  17965. }
  17966. /**
  17967. * Frees internal resources.
  17968. */
  17969. dispose() {
  17970. this.chainMaps = {};
  17971. }
  17972. /**
  17973. * Factory method for creating render objects with the given list of parameters.
  17974. *
  17975. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17976. * @param {Geometries} geometries - Renderer component for managing geometries.
  17977. * @param {Renderer} renderer - The renderer.
  17978. * @param {Object3D} object - The 3D object.
  17979. * @param {Material} material - The object's material.
  17980. * @param {Scene} scene - The scene the 3D object belongs to.
  17981. * @param {Camera} camera - The camera the object should be rendered with.
  17982. * @param {LightsNode} lightsNode - The lights node.
  17983. * @param {RenderContext} renderContext - The render context.
  17984. * @param {ClippingContext} clippingContext - The clipping context.
  17985. * @param {string} [passId] - An optional ID for identifying the pass.
  17986. * @return {RenderObject} The render object.
  17987. */
  17988. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17989. const chainMap = this.getChainMap( passId );
  17990. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  17991. renderObject.onDispose = () => {
  17992. this.pipelines.delete( renderObject );
  17993. this.bindings.delete( renderObject );
  17994. this.nodes.delete( renderObject );
  17995. chainMap.delete( renderObject.getChainArray() );
  17996. };
  17997. return renderObject;
  17998. }
  17999. }
  18000. /**
  18001. * Data structure for the renderer. It is intended to manage
  18002. * data of objects in dictionaries.
  18003. *
  18004. * @private
  18005. */
  18006. class DataMap {
  18007. /**
  18008. * Constructs a new data map.
  18009. */
  18010. constructor() {
  18011. /**
  18012. * `DataMap` internally uses a weak map
  18013. * to manage its data.
  18014. *
  18015. * @type {WeakMap}
  18016. */
  18017. this.data = new WeakMap();
  18018. }
  18019. /**
  18020. * Returns the dictionary for the given object.
  18021. *
  18022. * @param {Object} object - The object.
  18023. * @return {Object} The dictionary.
  18024. */
  18025. get( object ) {
  18026. let map = this.data.get( object );
  18027. if ( map === undefined ) {
  18028. map = {};
  18029. this.data.set( object, map );
  18030. }
  18031. return map;
  18032. }
  18033. /**
  18034. * Deletes the dictionary for the given object.
  18035. *
  18036. * @param {Object} object - The object.
  18037. * @return {?Object} The deleted dictionary.
  18038. */
  18039. delete( object ) {
  18040. let map = null;
  18041. if ( this.data.has( object ) ) {
  18042. map = this.data.get( object );
  18043. this.data.delete( object );
  18044. }
  18045. return map;
  18046. }
  18047. /**
  18048. * Returns `true` if the given object has a dictionary defined.
  18049. *
  18050. * @param {Object} object - The object to test.
  18051. * @return {boolean} Whether a dictionary is defined or not.
  18052. */
  18053. has( object ) {
  18054. return this.data.has( object );
  18055. }
  18056. /**
  18057. * Frees internal resources.
  18058. */
  18059. dispose() {
  18060. this.data = new WeakMap();
  18061. }
  18062. }
  18063. const AttributeType = {
  18064. VERTEX: 1,
  18065. INDEX: 2,
  18066. STORAGE: 3,
  18067. INDIRECT: 4
  18068. };
  18069. // size of a chunk in bytes (STD140 layout)
  18070. const GPU_CHUNK_BYTES = 16;
  18071. // @TODO: Move to src/constants.js
  18072. const BlendColorFactor = 211;
  18073. const OneMinusBlendColorFactor = 212;
  18074. /**
  18075. * This renderer module manages geometry attributes.
  18076. *
  18077. * @private
  18078. * @augments DataMap
  18079. */
  18080. class Attributes extends DataMap {
  18081. /**
  18082. * Constructs a new attribute management component.
  18083. *
  18084. * @param {Backend} backend - The renderer's backend.
  18085. */
  18086. constructor( backend ) {
  18087. super();
  18088. /**
  18089. * The renderer's backend.
  18090. *
  18091. * @type {Backend}
  18092. */
  18093. this.backend = backend;
  18094. }
  18095. /**
  18096. * Deletes the data for the given attribute.
  18097. *
  18098. * @param {BufferAttribute} attribute - The attribute.
  18099. * @return {Object|null} The deleted attribute data.
  18100. */
  18101. delete( attribute ) {
  18102. const attributeData = super.delete( attribute );
  18103. if ( attributeData !== null ) {
  18104. this.backend.destroyAttribute( attribute );
  18105. }
  18106. return attributeData;
  18107. }
  18108. /**
  18109. * Updates the given attribute. This method creates attribute buffers
  18110. * for new attributes and updates data for existing ones.
  18111. *
  18112. * @param {BufferAttribute} attribute - The attribute to update.
  18113. * @param {number} type - The attribute type.
  18114. */
  18115. update( attribute, type ) {
  18116. const data = this.get( attribute );
  18117. if ( data.version === undefined ) {
  18118. if ( type === AttributeType.VERTEX ) {
  18119. this.backend.createAttribute( attribute );
  18120. } else if ( type === AttributeType.INDEX ) {
  18121. this.backend.createIndexAttribute( attribute );
  18122. } else if ( type === AttributeType.STORAGE ) {
  18123. this.backend.createStorageAttribute( attribute );
  18124. } else if ( type === AttributeType.INDIRECT ) {
  18125. this.backend.createIndirectStorageAttribute( attribute );
  18126. }
  18127. data.version = this._getBufferAttribute( attribute ).version;
  18128. } else {
  18129. const bufferAttribute = this._getBufferAttribute( attribute );
  18130. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  18131. this.backend.updateAttribute( attribute );
  18132. data.version = bufferAttribute.version;
  18133. }
  18134. }
  18135. }
  18136. /**
  18137. * Utility method for handling interleaved buffer attributes correctly.
  18138. * To process them, their `InterleavedBuffer` is returned.
  18139. *
  18140. * @param {BufferAttribute} attribute - The attribute.
  18141. * @return {BufferAttribute|InterleavedBuffer}
  18142. */
  18143. _getBufferAttribute( attribute ) {
  18144. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  18145. return attribute;
  18146. }
  18147. }
  18148. /**
  18149. * Returns the wireframe version for the given geometry.
  18150. *
  18151. * @private
  18152. * @function
  18153. * @param {BufferGeometry} geometry - The geometry.
  18154. * @return {number} The version.
  18155. */
  18156. function getWireframeVersion( geometry ) {
  18157. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  18158. }
  18159. /**
  18160. * Returns a wireframe index attribute for the given geometry.
  18161. *
  18162. * @private
  18163. * @function
  18164. * @param {BufferGeometry} geometry - The geometry.
  18165. * @return {BufferAttribute} The wireframe index attribute.
  18166. */
  18167. function getWireframeIndex( geometry ) {
  18168. const indices = [];
  18169. const geometryIndex = geometry.index;
  18170. const geometryPosition = geometry.attributes.position;
  18171. if ( geometryIndex !== null ) {
  18172. const array = geometryIndex.array;
  18173. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  18174. const a = array[ i + 0 ];
  18175. const b = array[ i + 1 ];
  18176. const c = array[ i + 2 ];
  18177. indices.push( a, b, b, c, c, a );
  18178. }
  18179. } else {
  18180. const array = geometryPosition.array;
  18181. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  18182. const a = i + 0;
  18183. const b = i + 1;
  18184. const c = i + 2;
  18185. indices.push( a, b, b, c, c, a );
  18186. }
  18187. }
  18188. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  18189. attribute.version = getWireframeVersion( geometry );
  18190. return attribute;
  18191. }
  18192. /**
  18193. * This renderer module manages geometries.
  18194. *
  18195. * @private
  18196. * @augments DataMap
  18197. */
  18198. class Geometries extends DataMap {
  18199. /**
  18200. * Constructs a new geometry management component.
  18201. *
  18202. * @param {Attributes} attributes - Renderer component for managing attributes.
  18203. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18204. */
  18205. constructor( attributes, info ) {
  18206. super();
  18207. /**
  18208. * Renderer component for managing attributes.
  18209. *
  18210. * @type {Attributes}
  18211. */
  18212. this.attributes = attributes;
  18213. /**
  18214. * Renderer component for managing metrics and monitoring data.
  18215. *
  18216. * @type {Info}
  18217. */
  18218. this.info = info;
  18219. /**
  18220. * Weak Map for managing attributes for wireframe rendering.
  18221. *
  18222. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  18223. */
  18224. this.wireframes = new WeakMap();
  18225. /**
  18226. * This Weak Map is used to make sure buffer attributes are
  18227. * updated only once per render call.
  18228. *
  18229. * @type {WeakMap<BufferAttribute,number>}
  18230. */
  18231. this.attributeCall = new WeakMap();
  18232. }
  18233. /**
  18234. * Returns `true` if the given render object has an initialized geometry.
  18235. *
  18236. * @param {RenderObject} renderObject - The render object.
  18237. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  18238. */
  18239. has( renderObject ) {
  18240. const geometry = renderObject.geometry;
  18241. return super.has( geometry ) && this.get( geometry ).initialized === true;
  18242. }
  18243. /**
  18244. * Prepares the geometry of the given render object for rendering.
  18245. *
  18246. * @param {RenderObject} renderObject - The render object.
  18247. */
  18248. updateForRender( renderObject ) {
  18249. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  18250. this.updateAttributes( renderObject );
  18251. }
  18252. /**
  18253. * Initializes the geometry of the given render object.
  18254. *
  18255. * @param {RenderObject} renderObject - The render object.
  18256. */
  18257. initGeometry( renderObject ) {
  18258. const geometry = renderObject.geometry;
  18259. const geometryData = this.get( geometry );
  18260. geometryData.initialized = true;
  18261. this.info.memory.geometries ++;
  18262. const onDispose = () => {
  18263. this.info.memory.geometries --;
  18264. const index = geometry.index;
  18265. const geometryAttributes = renderObject.getAttributes();
  18266. if ( index !== null ) {
  18267. this.attributes.delete( index );
  18268. }
  18269. for ( const geometryAttribute of geometryAttributes ) {
  18270. this.attributes.delete( geometryAttribute );
  18271. }
  18272. const wireframeAttribute = this.wireframes.get( geometry );
  18273. if ( wireframeAttribute !== undefined ) {
  18274. this.attributes.delete( wireframeAttribute );
  18275. }
  18276. geometry.removeEventListener( 'dispose', onDispose );
  18277. };
  18278. geometry.addEventListener( 'dispose', onDispose );
  18279. }
  18280. /**
  18281. * Updates the geometry attributes of the given render object.
  18282. *
  18283. * @param {RenderObject} renderObject - The render object.
  18284. */
  18285. updateAttributes( renderObject ) {
  18286. // attributes
  18287. const attributes = renderObject.getAttributes();
  18288. for ( const attribute of attributes ) {
  18289. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18290. this.updateAttribute( attribute, AttributeType.STORAGE );
  18291. } else {
  18292. this.updateAttribute( attribute, AttributeType.VERTEX );
  18293. }
  18294. }
  18295. // indexes
  18296. const index = this.getIndex( renderObject );
  18297. if ( index !== null ) {
  18298. this.updateAttribute( index, AttributeType.INDEX );
  18299. }
  18300. // indirect
  18301. const indirect = renderObject.geometry.indirect;
  18302. if ( indirect !== null ) {
  18303. this.updateAttribute( indirect, AttributeType.INDIRECT );
  18304. }
  18305. }
  18306. /**
  18307. * Updates the given attribute.
  18308. *
  18309. * @param {BufferAttribute} attribute - The attribute to update.
  18310. * @param {number} type - The attribute type.
  18311. */
  18312. updateAttribute( attribute, type ) {
  18313. const callId = this.info.render.calls;
  18314. if ( ! attribute.isInterleavedBufferAttribute ) {
  18315. if ( this.attributeCall.get( attribute ) !== callId ) {
  18316. this.attributes.update( attribute, type );
  18317. this.attributeCall.set( attribute, callId );
  18318. }
  18319. } else {
  18320. if ( this.attributeCall.get( attribute ) === undefined ) {
  18321. this.attributes.update( attribute, type );
  18322. this.attributeCall.set( attribute, callId );
  18323. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  18324. this.attributes.update( attribute, type );
  18325. this.attributeCall.set( attribute.data, callId );
  18326. this.attributeCall.set( attribute, callId );
  18327. }
  18328. }
  18329. }
  18330. /**
  18331. * Returns the indirect buffer attribute of the given render object.
  18332. *
  18333. * @param {RenderObject} renderObject - The render object.
  18334. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  18335. */
  18336. getIndirect( renderObject ) {
  18337. return renderObject.geometry.indirect;
  18338. }
  18339. /**
  18340. * Returns the index of the given render object's geometry. This is implemented
  18341. * in a method to return a wireframe index if necessary.
  18342. *
  18343. * @param {RenderObject} renderObject - The render object.
  18344. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  18345. */
  18346. getIndex( renderObject ) {
  18347. const { geometry, material } = renderObject;
  18348. let index = geometry.index;
  18349. if ( material.wireframe === true ) {
  18350. const wireframes = this.wireframes;
  18351. let wireframeAttribute = wireframes.get( geometry );
  18352. if ( wireframeAttribute === undefined ) {
  18353. wireframeAttribute = getWireframeIndex( geometry );
  18354. wireframes.set( geometry, wireframeAttribute );
  18355. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  18356. this.attributes.delete( wireframeAttribute );
  18357. wireframeAttribute = getWireframeIndex( geometry );
  18358. wireframes.set( geometry, wireframeAttribute );
  18359. }
  18360. index = wireframeAttribute;
  18361. }
  18362. return index;
  18363. }
  18364. }
  18365. /**
  18366. * This renderer module provides a series of statistical information
  18367. * about the GPU memory and the rendering process. Useful for debugging
  18368. * and monitoring.
  18369. */
  18370. class Info {
  18371. /**
  18372. * Constructs a new info component.
  18373. */
  18374. constructor() {
  18375. /**
  18376. * Whether frame related metrics should automatically
  18377. * be resetted or not. This property should be set to `false`
  18378. * by apps which manage their own animation loop. They must
  18379. * then call `renderer.info.reset()` once per frame manually.
  18380. *
  18381. * @type {boolean}
  18382. * @default true
  18383. */
  18384. this.autoReset = true;
  18385. /**
  18386. * The current frame ID. This ID is managed
  18387. * by `NodeFrame`.
  18388. *
  18389. * @type {number}
  18390. * @readonly
  18391. * @default 0
  18392. */
  18393. this.frame = 0;
  18394. /**
  18395. * The number of render calls since the
  18396. * app has been started.
  18397. *
  18398. * @type {number}
  18399. * @readonly
  18400. * @default 0
  18401. */
  18402. this.calls = 0;
  18403. /**
  18404. * Render related metrics.
  18405. *
  18406. * @type {Object}
  18407. * @readonly
  18408. * @property {number} calls - The number of render calls since the app has been started.
  18409. * @property {number} frameCalls - The number of render calls of the current frame.
  18410. * @property {number} drawCalls - The number of draw calls of the current frame.
  18411. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  18412. * @property {number} points - The number of rendered point primitives of the current frame.
  18413. * @property {number} lines - The number of rendered line primitives of the current frame.
  18414. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  18415. */
  18416. this.render = {
  18417. calls: 0,
  18418. frameCalls: 0,
  18419. drawCalls: 0,
  18420. triangles: 0,
  18421. points: 0,
  18422. lines: 0,
  18423. timestamp: 0,
  18424. };
  18425. /**
  18426. * Compute related metrics.
  18427. *
  18428. * @type {Object}
  18429. * @readonly
  18430. * @property {number} calls - The number of compute calls since the app has been started.
  18431. * @property {number} frameCalls - The number of compute calls of the current frame.
  18432. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  18433. */
  18434. this.compute = {
  18435. calls: 0,
  18436. frameCalls: 0,
  18437. timestamp: 0
  18438. };
  18439. /**
  18440. * Memory related metrics.
  18441. *
  18442. * @type {Object}
  18443. * @readonly
  18444. * @property {number} geometries - The number of active geometries.
  18445. * @property {number} frameCalls - The number of active textures.
  18446. */
  18447. this.memory = {
  18448. geometries: 0,
  18449. textures: 0
  18450. };
  18451. }
  18452. /**
  18453. * This method should be executed per draw call and updates the corresponding metrics.
  18454. *
  18455. * @param {Object3D} object - The 3D object that is going to be rendered.
  18456. * @param {number} count - The vertex or index count.
  18457. * @param {number} instanceCount - The instance count.
  18458. */
  18459. update( object, count, instanceCount ) {
  18460. this.render.drawCalls ++;
  18461. if ( object.isMesh || object.isSprite ) {
  18462. this.render.triangles += instanceCount * ( count / 3 );
  18463. } else if ( object.isPoints ) {
  18464. this.render.points += instanceCount * count;
  18465. } else if ( object.isLineSegments ) {
  18466. this.render.lines += instanceCount * ( count / 2 );
  18467. } else if ( object.isLine ) {
  18468. this.render.lines += instanceCount * ( count - 1 );
  18469. } else {
  18470. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  18471. }
  18472. }
  18473. /**
  18474. * Resets frame related metrics.
  18475. */
  18476. reset() {
  18477. this.render.drawCalls = 0;
  18478. this.render.frameCalls = 0;
  18479. this.compute.frameCalls = 0;
  18480. this.render.triangles = 0;
  18481. this.render.points = 0;
  18482. this.render.lines = 0;
  18483. }
  18484. /**
  18485. * Performs a complete reset of the object.
  18486. */
  18487. dispose() {
  18488. this.reset();
  18489. this.calls = 0;
  18490. this.render.calls = 0;
  18491. this.compute.calls = 0;
  18492. this.render.timestamp = 0;
  18493. this.compute.timestamp = 0;
  18494. this.memory.geometries = 0;
  18495. this.memory.textures = 0;
  18496. }
  18497. }
  18498. /**
  18499. * Abstract class for representing pipelines.
  18500. *
  18501. * @private
  18502. * @abstract
  18503. */
  18504. class Pipeline {
  18505. /**
  18506. * Constructs a new pipeline.
  18507. *
  18508. * @param {string} cacheKey - The pipeline's cache key.
  18509. */
  18510. constructor( cacheKey ) {
  18511. /**
  18512. * The pipeline's cache key.
  18513. *
  18514. * @type {string}
  18515. */
  18516. this.cacheKey = cacheKey;
  18517. /**
  18518. * How often the pipeline is currently in use.
  18519. *
  18520. * @type {number}
  18521. * @default 0
  18522. */
  18523. this.usedTimes = 0;
  18524. }
  18525. }
  18526. /**
  18527. * Class for representing render pipelines.
  18528. *
  18529. * @private
  18530. * @augments Pipeline
  18531. */
  18532. class RenderPipeline extends Pipeline {
  18533. /**
  18534. * Constructs a new render pipeline.
  18535. *
  18536. * @param {string} cacheKey - The pipeline's cache key.
  18537. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  18538. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  18539. */
  18540. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  18541. super( cacheKey );
  18542. /**
  18543. * The pipeline's vertex shader.
  18544. *
  18545. * @type {ProgrammableStage}
  18546. */
  18547. this.vertexProgram = vertexProgram;
  18548. /**
  18549. * The pipeline's fragment shader.
  18550. *
  18551. * @type {ProgrammableStage}
  18552. */
  18553. this.fragmentProgram = fragmentProgram;
  18554. }
  18555. }
  18556. /**
  18557. * Class for representing compute pipelines.
  18558. *
  18559. * @private
  18560. * @augments Pipeline
  18561. */
  18562. class ComputePipeline extends Pipeline {
  18563. /**
  18564. * Constructs a new render pipeline.
  18565. *
  18566. * @param {string} cacheKey - The pipeline's cache key.
  18567. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  18568. */
  18569. constructor( cacheKey, computeProgram ) {
  18570. super( cacheKey );
  18571. /**
  18572. * The pipeline's compute shader.
  18573. *
  18574. * @type {ProgrammableStage}
  18575. */
  18576. this.computeProgram = computeProgram;
  18577. /**
  18578. * This flag can be used for type testing.
  18579. *
  18580. * @type {boolean}
  18581. * @readonly
  18582. * @default true
  18583. */
  18584. this.isComputePipeline = true;
  18585. }
  18586. }
  18587. let _id$8 = 0;
  18588. /**
  18589. * Class for representing programmable stages which are vertex,
  18590. * fragment or compute shaders. Unlike fixed-function states (like blending),
  18591. * they represent the programmable part of a pipeline.
  18592. *
  18593. * @private
  18594. */
  18595. class ProgrammableStage {
  18596. /**
  18597. * Constructs a new programmable stage.
  18598. *
  18599. * @param {string} code - The shader code.
  18600. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  18601. * @param {string} name - The name of the shader.
  18602. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18603. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18604. */
  18605. constructor( code, stage, name, transforms = null, attributes = null ) {
  18606. /**
  18607. * The id of the programmable stage.
  18608. *
  18609. * @type {number}
  18610. */
  18611. this.id = _id$8 ++;
  18612. /**
  18613. * The shader code.
  18614. *
  18615. * @type {string}
  18616. */
  18617. this.code = code;
  18618. /**
  18619. * The type of stage.
  18620. *
  18621. * @type {string}
  18622. */
  18623. this.stage = stage;
  18624. /**
  18625. * The name of the stage.
  18626. * This is used for debugging purposes.
  18627. *
  18628. * @type {string}
  18629. */
  18630. this.name = name;
  18631. /**
  18632. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18633. *
  18634. * @type {?Array<Object>}
  18635. */
  18636. this.transforms = transforms;
  18637. /**
  18638. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18639. *
  18640. * @type {?Array<Object>}
  18641. */
  18642. this.attributes = attributes;
  18643. /**
  18644. * How often the programmable stage is currently in use.
  18645. *
  18646. * @type {number}
  18647. * @default 0
  18648. */
  18649. this.usedTimes = 0;
  18650. }
  18651. }
  18652. /**
  18653. * This renderer module manages the pipelines of the renderer.
  18654. *
  18655. * @private
  18656. * @augments DataMap
  18657. */
  18658. class Pipelines extends DataMap {
  18659. /**
  18660. * Constructs a new pipeline management component.
  18661. *
  18662. * @param {Backend} backend - The renderer's backend.
  18663. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18664. */
  18665. constructor( backend, nodes ) {
  18666. super();
  18667. /**
  18668. * The renderer's backend.
  18669. *
  18670. * @type {Backend}
  18671. */
  18672. this.backend = backend;
  18673. /**
  18674. * Renderer component for managing nodes related logic.
  18675. *
  18676. * @type {Nodes}
  18677. */
  18678. this.nodes = nodes;
  18679. /**
  18680. * A references to the bindings management component.
  18681. * This reference will be set inside the `Bindings`
  18682. * constructor.
  18683. *
  18684. * @type {?Bindings}
  18685. * @default null
  18686. */
  18687. this.bindings = null;
  18688. /**
  18689. * Internal cache for maintaining pipelines.
  18690. * The key of the map is a cache key, the value the pipeline.
  18691. *
  18692. * @type {Map<string,Pipeline>}
  18693. */
  18694. this.caches = new Map();
  18695. /**
  18696. * This dictionary maintains for each shader stage type (vertex,
  18697. * fragment and compute) the programmable stage objects which
  18698. * represent the actual shader code.
  18699. *
  18700. * @type {Object<string,Map>}
  18701. */
  18702. this.programs = {
  18703. vertex: new Map(),
  18704. fragment: new Map(),
  18705. compute: new Map()
  18706. };
  18707. }
  18708. /**
  18709. * Returns a compute pipeline for the given compute node.
  18710. *
  18711. * @param {Node} computeNode - The compute node.
  18712. * @param {Array<BindGroup>} bindings - The bindings.
  18713. * @return {ComputePipeline} The compute pipeline.
  18714. */
  18715. getForCompute( computeNode, bindings ) {
  18716. const { backend } = this;
  18717. const data = this.get( computeNode );
  18718. if ( this._needsComputeUpdate( computeNode ) ) {
  18719. const previousPipeline = data.pipeline;
  18720. if ( previousPipeline ) {
  18721. previousPipeline.usedTimes --;
  18722. previousPipeline.computeProgram.usedTimes --;
  18723. }
  18724. // get shader
  18725. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  18726. // programmable stage
  18727. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  18728. if ( stageCompute === undefined ) {
  18729. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  18730. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  18731. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  18732. backend.createProgram( stageCompute );
  18733. }
  18734. // determine compute pipeline
  18735. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  18736. let pipeline = this.caches.get( cacheKey );
  18737. if ( pipeline === undefined ) {
  18738. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18739. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  18740. }
  18741. // keep track of all used times
  18742. pipeline.usedTimes ++;
  18743. stageCompute.usedTimes ++;
  18744. //
  18745. data.version = computeNode.version;
  18746. data.pipeline = pipeline;
  18747. }
  18748. return data.pipeline;
  18749. }
  18750. /**
  18751. * Returns a render pipeline for the given render object.
  18752. *
  18753. * @param {RenderObject} renderObject - The render object.
  18754. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18755. * @return {RenderPipeline} The render pipeline.
  18756. */
  18757. getForRender( renderObject, promises = null ) {
  18758. const { backend } = this;
  18759. const data = this.get( renderObject );
  18760. if ( this._needsRenderUpdate( renderObject ) ) {
  18761. const previousPipeline = data.pipeline;
  18762. if ( previousPipeline ) {
  18763. previousPipeline.usedTimes --;
  18764. previousPipeline.vertexProgram.usedTimes --;
  18765. previousPipeline.fragmentProgram.usedTimes --;
  18766. }
  18767. // get shader
  18768. const nodeBuilderState = renderObject.getNodeBuilderState();
  18769. const name = renderObject.material ? renderObject.material.name : '';
  18770. // programmable stages
  18771. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  18772. if ( stageVertex === undefined ) {
  18773. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  18774. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  18775. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  18776. backend.createProgram( stageVertex );
  18777. }
  18778. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  18779. if ( stageFragment === undefined ) {
  18780. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  18781. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  18782. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  18783. backend.createProgram( stageFragment );
  18784. }
  18785. // determine render pipeline
  18786. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18787. let pipeline = this.caches.get( cacheKey );
  18788. if ( pipeline === undefined ) {
  18789. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18790. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  18791. } else {
  18792. renderObject.pipeline = pipeline;
  18793. }
  18794. // keep track of all used times
  18795. pipeline.usedTimes ++;
  18796. stageVertex.usedTimes ++;
  18797. stageFragment.usedTimes ++;
  18798. //
  18799. data.pipeline = pipeline;
  18800. }
  18801. return data.pipeline;
  18802. }
  18803. /**
  18804. * Deletes the pipeline for the given render object.
  18805. *
  18806. * @param {RenderObject} object - The render object.
  18807. * @return {?Object} The deleted dictionary.
  18808. */
  18809. delete( object ) {
  18810. const pipeline = this.get( object ).pipeline;
  18811. if ( pipeline ) {
  18812. // pipeline
  18813. pipeline.usedTimes --;
  18814. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  18815. // programs
  18816. if ( pipeline.isComputePipeline ) {
  18817. pipeline.computeProgram.usedTimes --;
  18818. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  18819. } else {
  18820. pipeline.fragmentProgram.usedTimes --;
  18821. pipeline.vertexProgram.usedTimes --;
  18822. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  18823. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  18824. }
  18825. }
  18826. return super.delete( object );
  18827. }
  18828. /**
  18829. * Frees internal resources.
  18830. */
  18831. dispose() {
  18832. super.dispose();
  18833. this.caches = new Map();
  18834. this.programs = {
  18835. vertex: new Map(),
  18836. fragment: new Map(),
  18837. compute: new Map()
  18838. };
  18839. }
  18840. /**
  18841. * Updates the pipeline for the given render object.
  18842. *
  18843. * @param {RenderObject} renderObject - The render object.
  18844. */
  18845. updateForRender( renderObject ) {
  18846. this.getForRender( renderObject );
  18847. }
  18848. /**
  18849. * Returns a compute pipeline for the given parameters.
  18850. *
  18851. * @private
  18852. * @param {Node} computeNode - The compute node.
  18853. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18854. * @param {string} cacheKey - The cache key.
  18855. * @param {Array<BindGroup>} bindings - The bindings.
  18856. * @return {ComputePipeline} The compute pipeline.
  18857. */
  18858. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  18859. // check for existing pipeline
  18860. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  18861. let pipeline = this.caches.get( cacheKey );
  18862. if ( pipeline === undefined ) {
  18863. pipeline = new ComputePipeline( cacheKey, stageCompute );
  18864. this.caches.set( cacheKey, pipeline );
  18865. this.backend.createComputePipeline( pipeline, bindings );
  18866. }
  18867. return pipeline;
  18868. }
  18869. /**
  18870. * Returns a render pipeline for the given parameters.
  18871. *
  18872. * @private
  18873. * @param {RenderObject} renderObject - The render object.
  18874. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18875. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18876. * @param {string} cacheKey - The cache key.
  18877. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18878. * @return {ComputePipeline} The compute pipeline.
  18879. */
  18880. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  18881. // check for existing pipeline
  18882. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18883. let pipeline = this.caches.get( cacheKey );
  18884. if ( pipeline === undefined ) {
  18885. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  18886. this.caches.set( cacheKey, pipeline );
  18887. renderObject.pipeline = pipeline;
  18888. // The `promises` array is `null` by default and only set to an empty array when
  18889. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  18890. // pending promises that resolve when the render pipelines are ready for rendering.
  18891. this.backend.createRenderPipeline( renderObject, promises );
  18892. }
  18893. return pipeline;
  18894. }
  18895. /**
  18896. * Computes a cache key representing a compute pipeline.
  18897. *
  18898. * @private
  18899. * @param {Node} computeNode - The compute node.
  18900. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18901. * @return {string} The cache key.
  18902. */
  18903. _getComputeCacheKey( computeNode, stageCompute ) {
  18904. return computeNode.id + ',' + stageCompute.id;
  18905. }
  18906. /**
  18907. * Computes a cache key representing a render pipeline.
  18908. *
  18909. * @private
  18910. * @param {RenderObject} renderObject - The render object.
  18911. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18912. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18913. * @return {string} The cache key.
  18914. */
  18915. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  18916. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  18917. }
  18918. /**
  18919. * Releases the given pipeline.
  18920. *
  18921. * @private
  18922. * @param {Pipeline} pipeline - The pipeline to release.
  18923. */
  18924. _releasePipeline( pipeline ) {
  18925. this.caches.delete( pipeline.cacheKey );
  18926. }
  18927. /**
  18928. * Releases the shader program.
  18929. *
  18930. * @private
  18931. * @param {Object} program - The shader program to release.
  18932. */
  18933. _releaseProgram( program ) {
  18934. const code = program.code;
  18935. const stage = program.stage;
  18936. this.programs[ stage ].delete( code );
  18937. }
  18938. /**
  18939. * Returns `true` if the compute pipeline for the given compute node requires an update.
  18940. *
  18941. * @private
  18942. * @param {Node} computeNode - The compute node.
  18943. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  18944. */
  18945. _needsComputeUpdate( computeNode ) {
  18946. const data = this.get( computeNode );
  18947. return data.pipeline === undefined || data.version !== computeNode.version;
  18948. }
  18949. /**
  18950. * Returns `true` if the render pipeline for the given render object requires an update.
  18951. *
  18952. * @private
  18953. * @param {RenderObject} renderObject - The render object.
  18954. * @return {boolean} Whether the render object for the given render object requires an update or not.
  18955. */
  18956. _needsRenderUpdate( renderObject ) {
  18957. const data = this.get( renderObject );
  18958. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  18959. }
  18960. }
  18961. /**
  18962. * This renderer module manages the bindings of the renderer.
  18963. *
  18964. * @private
  18965. * @augments DataMap
  18966. */
  18967. class Bindings extends DataMap {
  18968. /**
  18969. * Constructs a new bindings management component.
  18970. *
  18971. * @param {Backend} backend - The renderer's backend.
  18972. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18973. * @param {Textures} textures - Renderer component for managing textures.
  18974. * @param {Attributes} attributes - Renderer component for managing attributes.
  18975. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18976. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18977. */
  18978. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  18979. super();
  18980. /**
  18981. * The renderer's backend.
  18982. *
  18983. * @type {Backend}
  18984. */
  18985. this.backend = backend;
  18986. /**
  18987. * Renderer component for managing textures.
  18988. *
  18989. * @type {Textures}
  18990. */
  18991. this.textures = textures;
  18992. /**
  18993. * Renderer component for managing pipelines.
  18994. *
  18995. * @type {Pipelines}
  18996. */
  18997. this.pipelines = pipelines;
  18998. /**
  18999. * Renderer component for managing attributes.
  19000. *
  19001. * @type {Attributes}
  19002. */
  19003. this.attributes = attributes;
  19004. /**
  19005. * Renderer component for managing nodes related logic.
  19006. *
  19007. * @type {Nodes}
  19008. */
  19009. this.nodes = nodes;
  19010. /**
  19011. * Renderer component for managing metrics and monitoring data.
  19012. *
  19013. * @type {Info}
  19014. */
  19015. this.info = info;
  19016. this.pipelines.bindings = this; // assign bindings to pipelines
  19017. }
  19018. /**
  19019. * Returns the bind groups for the given render object.
  19020. *
  19021. * @param {RenderObject} renderObject - The render object.
  19022. * @return {Array<BindGroup>} The bind groups.
  19023. */
  19024. getForRender( renderObject ) {
  19025. const bindings = renderObject.getBindings();
  19026. for ( const bindGroup of bindings ) {
  19027. const groupData = this.get( bindGroup );
  19028. if ( groupData.bindGroup === undefined ) {
  19029. // each object defines an array of bindings (ubos, textures, samplers etc.)
  19030. this._init( bindGroup );
  19031. this.backend.createBindings( bindGroup, bindings, 0 );
  19032. groupData.bindGroup = bindGroup;
  19033. }
  19034. }
  19035. return bindings;
  19036. }
  19037. /**
  19038. * Returns the bind groups for the given compute node.
  19039. *
  19040. * @param {Node} computeNode - The compute node.
  19041. * @return {Array<BindGroup>} The bind groups.
  19042. */
  19043. getForCompute( computeNode ) {
  19044. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  19045. for ( const bindGroup of bindings ) {
  19046. const groupData = this.get( bindGroup );
  19047. if ( groupData.bindGroup === undefined ) {
  19048. this._init( bindGroup );
  19049. this.backend.createBindings( bindGroup, bindings, 0 );
  19050. groupData.bindGroup = bindGroup;
  19051. }
  19052. }
  19053. return bindings;
  19054. }
  19055. /**
  19056. * Updates the bindings for the given compute node.
  19057. *
  19058. * @param {Node} computeNode - The compute node.
  19059. */
  19060. updateForCompute( computeNode ) {
  19061. this._updateBindings( this.getForCompute( computeNode ) );
  19062. }
  19063. /**
  19064. * Updates the bindings for the given render object.
  19065. *
  19066. * @param {RenderObject} renderObject - The render object.
  19067. */
  19068. updateForRender( renderObject ) {
  19069. this._updateBindings( this.getForRender( renderObject ) );
  19070. }
  19071. /**
  19072. * Updates the given array of bindings.
  19073. *
  19074. * @param {Array<BindGroup>} bindings - The bind groups.
  19075. */
  19076. _updateBindings( bindings ) {
  19077. for ( const bindGroup of bindings ) {
  19078. this._update( bindGroup, bindings );
  19079. }
  19080. }
  19081. /**
  19082. * Initializes the given bind group.
  19083. *
  19084. * @param {BindGroup} bindGroup - The bind group to initialize.
  19085. */
  19086. _init( bindGroup ) {
  19087. for ( const binding of bindGroup.bindings ) {
  19088. if ( binding.isSampledTexture ) {
  19089. this.textures.updateTexture( binding.texture );
  19090. } else if ( binding.isStorageBuffer ) {
  19091. const attribute = binding.attribute;
  19092. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  19093. this.attributes.update( attribute, attributeType );
  19094. }
  19095. }
  19096. }
  19097. /**
  19098. * Updates the given bind group.
  19099. *
  19100. * @param {BindGroup} bindGroup - The bind group to update.
  19101. * @param {Array<BindGroup>} bindings - The bind groups.
  19102. */
  19103. _update( bindGroup, bindings ) {
  19104. const { backend } = this;
  19105. let needsBindingsUpdate = false;
  19106. let cacheBindings = true;
  19107. let cacheIndex = 0;
  19108. let version = 0;
  19109. // iterate over all bindings and check if buffer updates or a new binding group is required
  19110. for ( const binding of bindGroup.bindings ) {
  19111. if ( binding.isNodeUniformsGroup ) {
  19112. const updated = this.nodes.updateGroup( binding );
  19113. // every uniforms group is a uniform buffer. So if no update is required,
  19114. // we move one with the next binding. Otherwise the next if block will update the group.
  19115. if ( updated === false ) continue;
  19116. }
  19117. if ( binding.isStorageBuffer ) {
  19118. const attribute = binding.attribute;
  19119. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  19120. this.attributes.update( attribute, attributeType );
  19121. }
  19122. if ( binding.isUniformBuffer ) {
  19123. const updated = binding.update();
  19124. if ( updated ) {
  19125. backend.updateBinding( binding );
  19126. }
  19127. } else if ( binding.isSampler ) {
  19128. binding.update();
  19129. } else if ( binding.isSampledTexture ) {
  19130. const texturesTextureData = this.textures.get( binding.texture );
  19131. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  19132. const updated = binding.update();
  19133. const texture = binding.texture;
  19134. if ( updated ) {
  19135. this.textures.updateTexture( texture );
  19136. }
  19137. const textureData = backend.get( texture );
  19138. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  19139. cacheBindings = false;
  19140. } else {
  19141. cacheIndex = cacheIndex * 10 + texture.id;
  19142. version += texture.version;
  19143. }
  19144. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  19145. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  19146. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  19147. this.textures.updateTexture( texture );
  19148. needsBindingsUpdate = true;
  19149. }
  19150. if ( texture.isStorageTexture === true ) {
  19151. const textureData = this.get( texture );
  19152. if ( binding.store === true ) {
  19153. textureData.needsMipmap = true;
  19154. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  19155. this.backend.generateMipmaps( texture );
  19156. textureData.needsMipmap = false;
  19157. }
  19158. }
  19159. }
  19160. }
  19161. if ( needsBindingsUpdate === true ) {
  19162. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  19163. }
  19164. }
  19165. }
  19166. /**
  19167. * Default sorting function for opaque render items.
  19168. *
  19169. * @private
  19170. * @function
  19171. * @param {Object} a - The first render item.
  19172. * @param {Object} b - The second render item.
  19173. * @return {number} A numeric value which defines the sort order.
  19174. */
  19175. function painterSortStable( a, b ) {
  19176. if ( a.groupOrder !== b.groupOrder ) {
  19177. return a.groupOrder - b.groupOrder;
  19178. } else if ( a.renderOrder !== b.renderOrder ) {
  19179. return a.renderOrder - b.renderOrder;
  19180. } else if ( a.material.id !== b.material.id ) {
  19181. return a.material.id - b.material.id;
  19182. } else if ( a.z !== b.z ) {
  19183. return a.z - b.z;
  19184. } else {
  19185. return a.id - b.id;
  19186. }
  19187. }
  19188. /**
  19189. * Default sorting function for transparent render items.
  19190. *
  19191. * @private
  19192. * @function
  19193. * @param {Object} a - The first render item.
  19194. * @param {Object} b - The second render item.
  19195. * @return {number} A numeric value which defines the sort order.
  19196. */
  19197. function reversePainterSortStable( a, b ) {
  19198. if ( a.groupOrder !== b.groupOrder ) {
  19199. return a.groupOrder - b.groupOrder;
  19200. } else if ( a.renderOrder !== b.renderOrder ) {
  19201. return a.renderOrder - b.renderOrder;
  19202. } else if ( a.z !== b.z ) {
  19203. return b.z - a.z;
  19204. } else {
  19205. return a.id - b.id;
  19206. }
  19207. }
  19208. /**
  19209. * Returns `true` if the given transparent material requires a double pass.
  19210. *
  19211. * @private
  19212. * @function
  19213. * @param {Material} material - The transparent material.
  19214. * @return {boolean} Whether the given material requires a double pass or not.
  19215. */
  19216. function needsDoublePass( material ) {
  19217. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  19218. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  19219. }
  19220. /**
  19221. * When the renderer analyzes the scene at the beginning of a render call,
  19222. * it stores 3D object for further processing in render lists. Depending on the
  19223. * properties of a 3D objects (like their transformation or material state), the
  19224. * objects are maintained in ordered lists for the actual rendering.
  19225. *
  19226. * Render lists are unique per scene and camera combination.
  19227. *
  19228. * @private
  19229. * @augments Pipeline
  19230. */
  19231. class RenderList {
  19232. /**
  19233. * Constructs a render list.
  19234. *
  19235. * @param {Lighting} lighting - The lighting management component.
  19236. * @param {Scene} scene - The scene.
  19237. * @param {Camera} camera - The camera the scene is rendered with.
  19238. */
  19239. constructor( lighting, scene, camera ) {
  19240. /**
  19241. * 3D objects are transformed into render items and stored in this array.
  19242. *
  19243. * @type {Array<Object>}
  19244. */
  19245. this.renderItems = [];
  19246. /**
  19247. * The current render items index.
  19248. *
  19249. * @type {number}
  19250. * @default 0
  19251. */
  19252. this.renderItemsIndex = 0;
  19253. /**
  19254. * A list with opaque render items.
  19255. *
  19256. * @type {Array<Object>}
  19257. */
  19258. this.opaque = [];
  19259. /**
  19260. * A list with transparent render items which require
  19261. * double pass rendering (e.g. transmissive objects).
  19262. *
  19263. * @type {Array<Object>}
  19264. */
  19265. this.transparentDoublePass = [];
  19266. /**
  19267. * A list with transparent render items.
  19268. *
  19269. * @type {Array<Object>}
  19270. */
  19271. this.transparent = [];
  19272. /**
  19273. * A list with transparent render bundle data.
  19274. *
  19275. * @type {Array<Object>}
  19276. */
  19277. this.bundles = [];
  19278. /**
  19279. * The render list's lights node. This node is later
  19280. * relevant for the actual analytical light nodes which
  19281. * compute the scene's lighting in the shader.
  19282. *
  19283. * @type {LightsNode}
  19284. */
  19285. this.lightsNode = lighting.getNode( scene, camera );
  19286. /**
  19287. * The scene's lights stored in an array. This array
  19288. * is used to setup the lights node.
  19289. *
  19290. * @type {Array<Light>}
  19291. */
  19292. this.lightsArray = [];
  19293. /**
  19294. * The scene.
  19295. *
  19296. * @type {Scene}
  19297. */
  19298. this.scene = scene;
  19299. /**
  19300. * The camera the scene is rendered with.
  19301. *
  19302. * @type {Camera}
  19303. */
  19304. this.camera = camera;
  19305. /**
  19306. * How many objects perform occlusion query tests.
  19307. *
  19308. * @type {number}
  19309. * @default 0
  19310. */
  19311. this.occlusionQueryCount = 0;
  19312. }
  19313. /**
  19314. * This method is called right at the beginning of a render call
  19315. * before the scene is analyzed. It prepares the internal data
  19316. * structures for the upcoming render lists generation.
  19317. *
  19318. * @return {RenderList} A reference to this render list.
  19319. */
  19320. begin() {
  19321. this.renderItemsIndex = 0;
  19322. this.opaque.length = 0;
  19323. this.transparentDoublePass.length = 0;
  19324. this.transparent.length = 0;
  19325. this.bundles.length = 0;
  19326. this.lightsArray.length = 0;
  19327. this.occlusionQueryCount = 0;
  19328. return this;
  19329. }
  19330. /**
  19331. * Returns a render item for the giving render item state. The state is defined
  19332. * by a series of object-related parameters.
  19333. *
  19334. * The method avoids object creation by holding render items and reusing them in
  19335. * subsequent render calls (just with different property values).
  19336. *
  19337. * @param {Object3D} object - The 3D object.
  19338. * @param {BufferGeometry} geometry - The 3D object's geometry.
  19339. * @param {Material} material - The 3D object's material.
  19340. * @param {number} groupOrder - The current group order.
  19341. * @param {number} z - Th 3D object's depth value (z value in clip space).
  19342. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  19343. * @param {ClippingContext} clippingContext - The current clipping context.
  19344. * @return {Object} The render item.
  19345. */
  19346. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  19347. let renderItem = this.renderItems[ this.renderItemsIndex ];
  19348. if ( renderItem === undefined ) {
  19349. renderItem = {
  19350. id: object.id,
  19351. object: object,
  19352. geometry: geometry,
  19353. material: material,
  19354. groupOrder: groupOrder,
  19355. renderOrder: object.renderOrder,
  19356. z: z,
  19357. group: group,
  19358. clippingContext: clippingContext
  19359. };
  19360. this.renderItems[ this.renderItemsIndex ] = renderItem;
  19361. } else {
  19362. renderItem.id = object.id;
  19363. renderItem.object = object;
  19364. renderItem.geometry = geometry;
  19365. renderItem.material = material;
  19366. renderItem.groupOrder = groupOrder;
  19367. renderItem.renderOrder = object.renderOrder;
  19368. renderItem.z = z;
  19369. renderItem.group = group;
  19370. renderItem.clippingContext = clippingContext;
  19371. }
  19372. this.renderItemsIndex ++;
  19373. return renderItem;
  19374. }
  19375. /**
  19376. * Pushes the given object as a render item to the internal render lists.
  19377. * The selected lists depend on the object properties.
  19378. *
  19379. * @param {Object3D} object - The 3D object.
  19380. * @param {BufferGeometry} geometry - The 3D object's geometry.
  19381. * @param {Material} material - The 3D object's material.
  19382. * @param {number} groupOrder - The current group order.
  19383. * @param {number} z - Th 3D object's depth value (z value in clip space).
  19384. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  19385. * @param {ClippingContext} clippingContext - The current clipping context.
  19386. */
  19387. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  19388. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  19389. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  19390. if ( material.transparent === true || material.transmission > 0 ) {
  19391. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  19392. this.transparent.push( renderItem );
  19393. } else {
  19394. this.opaque.push( renderItem );
  19395. }
  19396. }
  19397. /**
  19398. * Inserts the given object as a render item at the start of the internal render lists.
  19399. * The selected lists depend on the object properties.
  19400. *
  19401. * @param {Object3D} object - The 3D object.
  19402. * @param {BufferGeometry} geometry - The 3D object's geometry.
  19403. * @param {Material} material - The 3D object's material.
  19404. * @param {number} groupOrder - The current group order.
  19405. * @param {number} z - Th 3D object's depth value (z value in clip space).
  19406. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  19407. * @param {ClippingContext} clippingContext - The current clipping context.
  19408. */
  19409. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  19410. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  19411. if ( material.transparent === true || material.transmission > 0 ) {
  19412. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  19413. this.transparent.unshift( renderItem );
  19414. } else {
  19415. this.opaque.unshift( renderItem );
  19416. }
  19417. }
  19418. /**
  19419. * Pushes render bundle group data into the render list.
  19420. *
  19421. * @param {Object} group - Bundle group data.
  19422. */
  19423. pushBundle( group ) {
  19424. this.bundles.push( group );
  19425. }
  19426. /**
  19427. * Pushes a light into the render list.
  19428. *
  19429. * @param {Light} light - The light.
  19430. */
  19431. pushLight( light ) {
  19432. this.lightsArray.push( light );
  19433. }
  19434. /**
  19435. * Sorts the internal render lists.
  19436. *
  19437. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  19438. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  19439. */
  19440. sort( customOpaqueSort, customTransparentSort ) {
  19441. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  19442. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  19443. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  19444. }
  19445. /**
  19446. * This method performs finalizing tasks right after the render lists
  19447. * have been generated.
  19448. */
  19449. finish() {
  19450. // update lights
  19451. this.lightsNode.setLights( this.lightsArray );
  19452. // Clear references from inactive renderItems in the list
  19453. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  19454. const renderItem = this.renderItems[ i ];
  19455. if ( renderItem.id === null ) break;
  19456. renderItem.id = null;
  19457. renderItem.object = null;
  19458. renderItem.geometry = null;
  19459. renderItem.material = null;
  19460. renderItem.groupOrder = null;
  19461. renderItem.renderOrder = null;
  19462. renderItem.z = null;
  19463. renderItem.group = null;
  19464. renderItem.clippingContext = null;
  19465. }
  19466. }
  19467. }
  19468. const _chainKeys$4 = [];
  19469. /**
  19470. * This renderer module manages the render lists which are unique
  19471. * per scene and camera combination.
  19472. *
  19473. * @private
  19474. */
  19475. class RenderLists {
  19476. /**
  19477. * Constructs a render lists management component.
  19478. *
  19479. * @param {Lighting} lighting - The lighting management component.
  19480. */
  19481. constructor( lighting ) {
  19482. /**
  19483. * The lighting management component.
  19484. *
  19485. * @type {Lighting}
  19486. */
  19487. this.lighting = lighting;
  19488. /**
  19489. * The internal chain map which holds the render lists.
  19490. *
  19491. * @type {ChainMap}
  19492. */
  19493. this.lists = new ChainMap();
  19494. }
  19495. /**
  19496. * Returns a render list for the given scene and camera.
  19497. *
  19498. * @param {Scene} scene - The scene.
  19499. * @param {Camera} camera - The camera.
  19500. * @return {RenderList} The render list.
  19501. */
  19502. get( scene, camera ) {
  19503. const lists = this.lists;
  19504. _chainKeys$4[ 0 ] = scene;
  19505. _chainKeys$4[ 1 ] = camera;
  19506. let list = lists.get( _chainKeys$4 );
  19507. if ( list === undefined ) {
  19508. list = new RenderList( this.lighting, scene, camera );
  19509. lists.set( _chainKeys$4, list );
  19510. }
  19511. _chainKeys$4.length = 0;
  19512. return list;
  19513. }
  19514. /**
  19515. * Frees all internal resources.
  19516. */
  19517. dispose() {
  19518. this.lists = new ChainMap();
  19519. }
  19520. }
  19521. let _id$7 = 0;
  19522. /**
  19523. * Any render or compute command is executed in a specific context that defines
  19524. * the state of the renderer and its backend. Typical examples for such context
  19525. * data are the current clear values or data from the active framebuffer. This
  19526. * module is used to represent these contexts as objects.
  19527. *
  19528. * @private
  19529. */
  19530. class RenderContext {
  19531. /**
  19532. * Constructs a new render context.
  19533. */
  19534. constructor() {
  19535. /**
  19536. * The context's ID.
  19537. *
  19538. * @type {number}
  19539. */
  19540. this.id = _id$7 ++;
  19541. /**
  19542. * Whether the current active framebuffer has a color attachment.
  19543. *
  19544. * @type {boolean}
  19545. * @default true
  19546. */
  19547. this.color = true;
  19548. /**
  19549. * Whether the color attachment should be cleared or not.
  19550. *
  19551. * @type {boolean}
  19552. * @default true
  19553. */
  19554. this.clearColor = true;
  19555. /**
  19556. * The clear color value.
  19557. *
  19558. * @type {Object}
  19559. * @default true
  19560. */
  19561. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  19562. /**
  19563. * Whether the current active framebuffer has a depth attachment.
  19564. *
  19565. * @type {boolean}
  19566. * @default true
  19567. */
  19568. this.depth = true;
  19569. /**
  19570. * Whether the depth attachment should be cleared or not.
  19571. *
  19572. * @type {boolean}
  19573. * @default true
  19574. */
  19575. this.clearDepth = true;
  19576. /**
  19577. * The clear depth value.
  19578. *
  19579. * @type {number}
  19580. * @default 1
  19581. */
  19582. this.clearDepthValue = 1;
  19583. /**
  19584. * Whether the current active framebuffer has a stencil attachment.
  19585. *
  19586. * @type {boolean}
  19587. * @default false
  19588. */
  19589. this.stencil = false;
  19590. /**
  19591. * Whether the stencil attachment should be cleared or not.
  19592. *
  19593. * @type {boolean}
  19594. * @default true
  19595. */
  19596. this.clearStencil = true;
  19597. /**
  19598. * The clear stencil value.
  19599. *
  19600. * @type {number}
  19601. * @default 1
  19602. */
  19603. this.clearStencilValue = 1;
  19604. /**
  19605. * By default the viewport encloses the entire framebuffer If a smaller
  19606. * viewport is manually defined, this property is to `true` by the renderer.
  19607. *
  19608. * @type {boolean}
  19609. * @default false
  19610. */
  19611. this.viewport = false;
  19612. /**
  19613. * The viewport value. This value is in physical pixels meaning it incorporates
  19614. * the renderer's pixel ratio. The viewport property of render targets or
  19615. * the renderer is in logical pixels.
  19616. *
  19617. * @type {Vector4}
  19618. */
  19619. this.viewportValue = new Vector4();
  19620. /**
  19621. * When the scissor test is active and scissor rectangle smaller than the
  19622. * framebuffers dimensions, this property is to `true` by the renderer.
  19623. *
  19624. * @type {boolean}
  19625. * @default false
  19626. */
  19627. this.scissor = false;
  19628. /**
  19629. * The scissor rectangle.
  19630. *
  19631. * @type {Vector4}
  19632. */
  19633. this.scissorValue = new Vector4();
  19634. /**
  19635. * The active render target.
  19636. *
  19637. * @type {?RenderTarget}
  19638. * @default null
  19639. */
  19640. this.renderTarget = null;
  19641. /**
  19642. * The textures of the active render target.
  19643. * `null` when no render target is set.
  19644. *
  19645. * @type {?Array<Texture>}
  19646. * @default null
  19647. */
  19648. this.textures = null;
  19649. /**
  19650. * The depth texture of the active render target.
  19651. * `null` when no render target is set.
  19652. *
  19653. * @type {?DepthTexture}
  19654. * @default null
  19655. */
  19656. this.depthTexture = null;
  19657. /**
  19658. * The active cube face.
  19659. *
  19660. * @type {number}
  19661. * @default 0
  19662. */
  19663. this.activeCubeFace = 0;
  19664. /**
  19665. * The active mipmap level.
  19666. *
  19667. * @type {number}
  19668. * @default 0
  19669. */
  19670. this.activeMipmapLevel = 0;
  19671. /**
  19672. * The number of MSAA samples. This value is always `1` when
  19673. * MSAA isn't used.
  19674. *
  19675. * @type {number}
  19676. * @default 1
  19677. */
  19678. this.sampleCount = 1;
  19679. /**
  19680. * The active render target's width in physical pixels.
  19681. *
  19682. * @type {number}
  19683. * @default 0
  19684. */
  19685. this.width = 0;
  19686. /**
  19687. * The active render target's height in physical pixels.
  19688. *
  19689. * @type {number}
  19690. * @default 0
  19691. */
  19692. this.height = 0;
  19693. /**
  19694. * The occlusion query count.
  19695. *
  19696. * @type {number}
  19697. * @default 0
  19698. */
  19699. this.occlusionQueryCount = 0;
  19700. /**
  19701. * The current clipping context.
  19702. *
  19703. * @type {?ClippingContext}
  19704. * @default null
  19705. */
  19706. this.clippingContext = null;
  19707. /**
  19708. * This flag can be used for type testing.
  19709. *
  19710. * @type {boolean}
  19711. * @readonly
  19712. * @default true
  19713. */
  19714. this.isRenderContext = true;
  19715. }
  19716. /**
  19717. * Returns the cache key of this render context.
  19718. *
  19719. * @return {number} The cache key.
  19720. */
  19721. getCacheKey() {
  19722. return getCacheKey( this );
  19723. }
  19724. }
  19725. /**
  19726. * Computes a cache key for the given render context. This key
  19727. * should identify the render target state so it is possible to
  19728. * configure the correct attachments in the respective backend.
  19729. *
  19730. * @param {RenderContext} renderContext - The render context.
  19731. * @return {number} The cache key.
  19732. */
  19733. function getCacheKey( renderContext ) {
  19734. const { textures, activeCubeFace } = renderContext;
  19735. const values = [ activeCubeFace ];
  19736. for ( const texture of textures ) {
  19737. values.push( texture.id );
  19738. }
  19739. return hashArray( values );
  19740. }
  19741. const _chainKeys$3 = [];
  19742. const _defaultScene = /*@__PURE__*/ new Scene();
  19743. const _defaultCamera = /*@__PURE__*/ new Camera();
  19744. /**
  19745. * This module manages the render contexts of the renderer.
  19746. *
  19747. * @private
  19748. */
  19749. class RenderContexts {
  19750. /**
  19751. * Constructs a new render context management component.
  19752. */
  19753. constructor() {
  19754. /**
  19755. * A dictionary that manages render contexts in chain maps
  19756. * for each attachment state.
  19757. *
  19758. * @type {Object<string,ChainMap>}
  19759. */
  19760. this.chainMaps = {};
  19761. }
  19762. /**
  19763. * Returns a render context for the given scene, camera and render target.
  19764. *
  19765. * @param {Scene} scene - The scene.
  19766. * @param {Camera} camera - The camera that is used to render the scene.
  19767. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19768. * @return {RenderContext} The render context.
  19769. */
  19770. get( scene, camera, renderTarget = null ) {
  19771. _chainKeys$3[ 0 ] = scene;
  19772. _chainKeys$3[ 1 ] = camera;
  19773. let attachmentState;
  19774. if ( renderTarget === null ) {
  19775. attachmentState = 'default';
  19776. } else {
  19777. const format = renderTarget.texture.format;
  19778. const count = renderTarget.textures.length;
  19779. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  19780. }
  19781. const chainMap = this._getChainMap( attachmentState );
  19782. let renderState = chainMap.get( _chainKeys$3 );
  19783. if ( renderState === undefined ) {
  19784. renderState = new RenderContext();
  19785. chainMap.set( _chainKeys$3, renderState );
  19786. }
  19787. _chainKeys$3.length = 0;
  19788. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19789. return renderState;
  19790. }
  19791. /**
  19792. * Returns a render context intended for clear operations.
  19793. *
  19794. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19795. * @return {RenderContext} The render context.
  19796. */
  19797. getForClear( renderTarget = null ) {
  19798. return this.get( _defaultScene, _defaultCamera, renderTarget );
  19799. }
  19800. /**
  19801. * Returns a chain map for the given attachment state.
  19802. *
  19803. * @private
  19804. * @param {string} attachmentState - The attachment state.
  19805. * @return {ChainMap} The chain map.
  19806. */
  19807. _getChainMap( attachmentState ) {
  19808. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  19809. }
  19810. /**
  19811. * Frees internal resources.
  19812. */
  19813. dispose() {
  19814. this.chainMaps = {};
  19815. }
  19816. }
  19817. const _size$3 = /*@__PURE__*/ new Vector3();
  19818. /**
  19819. * This module manages the textures of the renderer.
  19820. *
  19821. * @private
  19822. * @augments DataMap
  19823. */
  19824. class Textures extends DataMap {
  19825. /**
  19826. * Constructs a new texture management component.
  19827. *
  19828. * @param {Renderer} renderer - The renderer.
  19829. * @param {Backend} backend - The renderer's backend.
  19830. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19831. */
  19832. constructor( renderer, backend, info ) {
  19833. super();
  19834. /**
  19835. * The renderer.
  19836. *
  19837. * @type {Renderer}
  19838. */
  19839. this.renderer = renderer;
  19840. /**
  19841. * The backend.
  19842. *
  19843. * @type {Backend}
  19844. */
  19845. this.backend = backend;
  19846. /**
  19847. * Renderer component for managing metrics and monitoring data.
  19848. *
  19849. * @type {Info}
  19850. */
  19851. this.info = info;
  19852. }
  19853. /**
  19854. * Updates the given render target. Based on the given render target configuration,
  19855. * it updates the texture states representing the attachments of the framebuffer.
  19856. *
  19857. * @param {RenderTarget} renderTarget - The render target to update.
  19858. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  19859. */
  19860. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  19861. const renderTargetData = this.get( renderTarget );
  19862. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19863. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  19864. const textures = renderTarget.textures;
  19865. const size = this.getSize( textures[ 0 ] );
  19866. const mipWidth = size.width >> activeMipmapLevel;
  19867. const mipHeight = size.height >> activeMipmapLevel;
  19868. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  19869. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  19870. let textureNeedsUpdate = false;
  19871. if ( depthTexture === undefined && useDepthTexture ) {
  19872. depthTexture = new DepthTexture();
  19873. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  19874. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  19875. depthTexture.image.width = mipWidth;
  19876. depthTexture.image.height = mipHeight;
  19877. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  19878. }
  19879. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  19880. textureNeedsUpdate = true;
  19881. if ( depthTexture ) {
  19882. depthTexture.needsUpdate = true;
  19883. depthTexture.image.width = mipWidth;
  19884. depthTexture.image.height = mipHeight;
  19885. }
  19886. }
  19887. renderTargetData.width = size.width;
  19888. renderTargetData.height = size.height;
  19889. renderTargetData.textures = textures;
  19890. renderTargetData.depthTexture = depthTexture || null;
  19891. renderTargetData.depth = renderTarget.depthBuffer;
  19892. renderTargetData.stencil = renderTarget.stencilBuffer;
  19893. renderTargetData.renderTarget = renderTarget;
  19894. if ( renderTargetData.sampleCount !== sampleCount ) {
  19895. textureNeedsUpdate = true;
  19896. if ( depthTexture ) {
  19897. depthTexture.needsUpdate = true;
  19898. }
  19899. renderTargetData.sampleCount = sampleCount;
  19900. }
  19901. //
  19902. const options = { sampleCount };
  19903. // XR render targets require no texture updates
  19904. if ( renderTarget.isXRRenderTarget !== true ) {
  19905. for ( let i = 0; i < textures.length; i ++ ) {
  19906. const texture = textures[ i ];
  19907. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  19908. this.updateTexture( texture, options );
  19909. }
  19910. if ( depthTexture ) {
  19911. this.updateTexture( depthTexture, options );
  19912. }
  19913. }
  19914. // dispose handler
  19915. if ( renderTargetData.initialized !== true ) {
  19916. renderTargetData.initialized = true;
  19917. // dispose
  19918. const onDispose = () => {
  19919. renderTarget.removeEventListener( 'dispose', onDispose );
  19920. for ( let i = 0; i < textures.length; i ++ ) {
  19921. this._destroyTexture( textures[ i ] );
  19922. }
  19923. if ( depthTexture ) {
  19924. this._destroyTexture( depthTexture );
  19925. }
  19926. this.delete( renderTarget );
  19927. };
  19928. renderTarget.addEventListener( 'dispose', onDispose );
  19929. }
  19930. }
  19931. /**
  19932. * Updates the given texture. Depending on the texture state, this method
  19933. * triggers the upload of texture data to the GPU memory. If the texture data are
  19934. * not yet ready for the upload, it uses default texture data for as a placeholder.
  19935. *
  19936. * @param {Texture} texture - The texture to update.
  19937. * @param {Object} [options={}] - The options.
  19938. */
  19939. updateTexture( texture, options = {} ) {
  19940. const textureData = this.get( texture );
  19941. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  19942. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  19943. const backend = this.backend;
  19944. if ( isRenderTarget && textureData.initialized === true ) {
  19945. // it's an update
  19946. backend.destroySampler( texture );
  19947. backend.destroyTexture( texture );
  19948. }
  19949. //
  19950. if ( texture.isFramebufferTexture ) {
  19951. const renderTarget = this.renderer.getRenderTarget();
  19952. if ( renderTarget ) {
  19953. texture.type = renderTarget.texture.type;
  19954. } else {
  19955. texture.type = UnsignedByteType;
  19956. }
  19957. }
  19958. //
  19959. const { width, height, depth } = this.getSize( texture );
  19960. options.width = width;
  19961. options.height = height;
  19962. options.depth = depth;
  19963. options.needsMipmaps = this.needsMipmaps( texture );
  19964. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  19965. //
  19966. if ( isRenderTarget || texture.isStorageTexture === true ) {
  19967. backend.createSampler( texture );
  19968. backend.createTexture( texture, options );
  19969. textureData.generation = texture.version;
  19970. } else {
  19971. const needsCreate = textureData.initialized !== true;
  19972. if ( needsCreate ) backend.createSampler( texture );
  19973. if ( texture.version > 0 ) {
  19974. const image = texture.image;
  19975. if ( image === undefined ) {
  19976. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  19977. } else if ( image.complete === false ) {
  19978. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  19979. } else {
  19980. if ( texture.images ) {
  19981. const images = [];
  19982. for ( const image of texture.images ) {
  19983. images.push( image );
  19984. }
  19985. options.images = images;
  19986. } else {
  19987. options.image = image;
  19988. }
  19989. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  19990. backend.createTexture( texture, options );
  19991. textureData.isDefaultTexture = false;
  19992. textureData.generation = texture.version;
  19993. }
  19994. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  19995. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  19996. }
  19997. } else {
  19998. // async update
  19999. backend.createDefaultTexture( texture );
  20000. textureData.isDefaultTexture = true;
  20001. textureData.generation = texture.version;
  20002. }
  20003. }
  20004. // dispose handler
  20005. if ( textureData.initialized !== true ) {
  20006. textureData.initialized = true;
  20007. textureData.generation = texture.version;
  20008. //
  20009. this.info.memory.textures ++;
  20010. // dispose
  20011. const onDispose = () => {
  20012. texture.removeEventListener( 'dispose', onDispose );
  20013. this._destroyTexture( texture );
  20014. this.info.memory.textures --;
  20015. };
  20016. texture.addEventListener( 'dispose', onDispose );
  20017. }
  20018. //
  20019. textureData.version = texture.version;
  20020. }
  20021. /**
  20022. * Computes the size of the given texture and writes the result
  20023. * into the target vector. This vector is also returned by the
  20024. * method.
  20025. *
  20026. * If no texture data are available for the compute yet, the method
  20027. * returns default size values.
  20028. *
  20029. * @param {Texture} texture - The texture to compute the size for.
  20030. * @param {Vector3} target - The target vector.
  20031. * @return {Vector3} The target vector.
  20032. */
  20033. getSize( texture, target = _size$3 ) {
  20034. let image = texture.images ? texture.images[ 0 ] : texture.image;
  20035. if ( image ) {
  20036. if ( image.image !== undefined ) image = image.image;
  20037. target.width = image.width || 1;
  20038. target.height = image.height || 1;
  20039. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  20040. } else {
  20041. target.width = target.height = target.depth = 1;
  20042. }
  20043. return target;
  20044. }
  20045. /**
  20046. * Computes the number of mipmap levels for the given texture.
  20047. *
  20048. * @param {Texture} texture - The texture.
  20049. * @param {number} width - The texture's width.
  20050. * @param {number} height - The texture's height.
  20051. * @return {number} The number of mipmap levels.
  20052. */
  20053. getMipLevels( texture, width, height ) {
  20054. let mipLevelCount;
  20055. if ( texture.isCompressedTexture ) {
  20056. if ( texture.mipmaps ) {
  20057. mipLevelCount = texture.mipmaps.length;
  20058. } else {
  20059. mipLevelCount = 1;
  20060. }
  20061. } else {
  20062. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  20063. }
  20064. return mipLevelCount;
  20065. }
  20066. /**
  20067. * Returns `true` if the given texture requires mipmaps.
  20068. *
  20069. * @param {Texture} texture - The texture.
  20070. * @return {boolean} Whether mipmaps are required or not.
  20071. */
  20072. needsMipmaps( texture ) {
  20073. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  20074. }
  20075. /**
  20076. * Returns `true` if the given texture is an environment map.
  20077. *
  20078. * @param {Texture} texture - The texture.
  20079. * @return {boolean} Whether the given texture is an environment map or not.
  20080. */
  20081. isEnvironmentTexture( texture ) {
  20082. const mapping = texture.mapping;
  20083. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  20084. }
  20085. /**
  20086. * Frees internal resource when the given texture isn't
  20087. * required anymore.
  20088. *
  20089. * @param {Texture} texture - The texture to destroy.
  20090. */
  20091. _destroyTexture( texture ) {
  20092. this.backend.destroySampler( texture );
  20093. this.backend.destroyTexture( texture );
  20094. this.delete( texture );
  20095. }
  20096. }
  20097. /**
  20098. * A four-component version of {@link Color} which is internally
  20099. * used by the renderer to represents clear color with alpha as
  20100. * one object.
  20101. *
  20102. * @private
  20103. * @augments Color
  20104. */
  20105. class Color4 extends Color {
  20106. /**
  20107. * Constructs a new four-component color.
  20108. * You can also pass a single THREE.Color, hex or
  20109. * string argument to this constructor.
  20110. *
  20111. * @param {number|string} [r=1] - The red value.
  20112. * @param {number} [g=1] - The green value.
  20113. * @param {number} [b=1] - The blue value.
  20114. * @param {number} [a=1] - The alpha value.
  20115. */
  20116. constructor( r, g, b, a = 1 ) {
  20117. super( r, g, b );
  20118. this.a = a;
  20119. }
  20120. /**
  20121. * Overwrites the default to honor alpha.
  20122. * You can also pass a single THREE.Color, hex or
  20123. * string argument to this method.
  20124. *
  20125. * @param {number|string|Color} r - The red value.
  20126. * @param {number} g - The green value.
  20127. * @param {number} b - The blue value.
  20128. * @param {number} [a=1] - The alpha value.
  20129. * @return {Color4} A reference to this object.
  20130. */
  20131. set( r, g, b, a = 1 ) {
  20132. this.a = a;
  20133. return super.set( r, g, b );
  20134. }
  20135. /**
  20136. * Overwrites the default to honor alpha.
  20137. *
  20138. * @param {Color4} color - The color to copy.
  20139. * @return {Color4} A reference to this object.
  20140. */
  20141. copy( color ) {
  20142. if ( color.a !== undefined ) this.a = color.a;
  20143. return super.copy( color );
  20144. }
  20145. /**
  20146. * Overwrites the default to honor alpha.
  20147. *
  20148. * @return {Color4} The cloned color.
  20149. */
  20150. clone() {
  20151. return new this.constructor( this.r, this.g, this.b, this.a );
  20152. }
  20153. }
  20154. /**
  20155. * Special version of {@link PropertyNode} which is used for parameters.
  20156. *
  20157. * @augments PropertyNode
  20158. */
  20159. class ParameterNode extends PropertyNode {
  20160. static get type() {
  20161. return 'ParameterNode';
  20162. }
  20163. /**
  20164. * Constructs a new parameter node.
  20165. *
  20166. * @param {string} nodeType - The type of the node.
  20167. * @param {?string} [name=null] - The name of the parameter in the shader.
  20168. */
  20169. constructor( nodeType, name = null ) {
  20170. super( nodeType, name );
  20171. /**
  20172. * This flag can be used for type testing.
  20173. *
  20174. * @type {boolean}
  20175. * @readonly
  20176. * @default true
  20177. */
  20178. this.isParameterNode = true;
  20179. }
  20180. getHash() {
  20181. return this.uuid;
  20182. }
  20183. generate() {
  20184. return this.name;
  20185. }
  20186. }
  20187. /**
  20188. * TSL function for creating a parameter node.
  20189. *
  20190. * @tsl
  20191. * @function
  20192. * @param {string} type - The type of the node.
  20193. * @param {?string} name - The name of the parameter in the shader.
  20194. * @returns {ParameterNode}
  20195. */
  20196. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  20197. /**
  20198. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  20199. * They are usually needed in cases like `If`, `Else`.
  20200. *
  20201. * @augments Node
  20202. */
  20203. class StackNode extends Node {
  20204. static get type() {
  20205. return 'StackNode';
  20206. }
  20207. /**
  20208. * Constructs a new stack node.
  20209. *
  20210. * @param {?StackNode} [parent=null] - The parent stack node.
  20211. */
  20212. constructor( parent = null ) {
  20213. super();
  20214. /**
  20215. * List of nodes.
  20216. *
  20217. * @type {Array<Node>}
  20218. */
  20219. this.nodes = [];
  20220. /**
  20221. * The output node.
  20222. *
  20223. * @type {?Node}
  20224. * @default null
  20225. */
  20226. this.outputNode = null;
  20227. /**
  20228. * The parent stack node.
  20229. *
  20230. * @type {?StackNode}
  20231. * @default null
  20232. */
  20233. this.parent = parent;
  20234. /**
  20235. * The current conditional node.
  20236. *
  20237. * @private
  20238. * @type {ConditionalNode}
  20239. * @default null
  20240. */
  20241. this._currentCond = null;
  20242. /**
  20243. * This flag can be used for type testing.
  20244. *
  20245. * @type {boolean}
  20246. * @readonly
  20247. * @default true
  20248. */
  20249. this.isStackNode = true;
  20250. }
  20251. getNodeType( builder ) {
  20252. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  20253. }
  20254. getMemberType( builder, name ) {
  20255. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  20256. }
  20257. /**
  20258. * Adds a node to this stack.
  20259. *
  20260. * @param {Node} node - The node to add.
  20261. * @return {StackNode} A reference to this stack node.
  20262. */
  20263. add( node ) {
  20264. this.nodes.push( node );
  20265. return this;
  20266. }
  20267. /**
  20268. * Represent an `if` statement in TSL.
  20269. *
  20270. * @param {Node} boolNode - Represents the condition.
  20271. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  20272. * @return {StackNode} A reference to this stack node.
  20273. */
  20274. If( boolNode, method ) {
  20275. const methodNode = new ShaderNode( method );
  20276. this._currentCond = select( boolNode, methodNode );
  20277. return this.add( this._currentCond );
  20278. }
  20279. /**
  20280. * Represent an `elseif` statement in TSL.
  20281. *
  20282. * @param {Node} boolNode - Represents the condition.
  20283. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  20284. * @return {StackNode} A reference to this stack node.
  20285. */
  20286. ElseIf( boolNode, method ) {
  20287. const methodNode = new ShaderNode( method );
  20288. const ifNode = select( boolNode, methodNode );
  20289. this._currentCond.elseNode = ifNode;
  20290. this._currentCond = ifNode;
  20291. return this;
  20292. }
  20293. /**
  20294. * Represent an `else` statement in TSL.
  20295. *
  20296. * @param {Function} method - TSL code which is executed in the `else` case.
  20297. * @return {StackNode} A reference to this stack node.
  20298. */
  20299. Else( method ) {
  20300. this._currentCond.elseNode = new ShaderNode( method );
  20301. return this;
  20302. }
  20303. build( builder, ...params ) {
  20304. const previousStack = getCurrentStack();
  20305. setCurrentStack( this );
  20306. for ( const node of this.nodes ) {
  20307. node.build( builder, 'void' );
  20308. }
  20309. setCurrentStack( previousStack );
  20310. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  20311. }
  20312. // Deprecated
  20313. /**
  20314. * @function
  20315. * @deprecated since r168. Use {@link StackNode#Else} instead.
  20316. *
  20317. * @param {...any} params
  20318. * @returns {StackNode}
  20319. */
  20320. else( ...params ) { // @deprecated, r168
  20321. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  20322. return this.Else( ...params );
  20323. }
  20324. /**
  20325. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  20326. *
  20327. * @param {...any} params
  20328. * @returns {StackNode}
  20329. */
  20330. elseif( ...params ) { // @deprecated, r168
  20331. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  20332. return this.ElseIf( ...params );
  20333. }
  20334. }
  20335. /**
  20336. * TSL function for creating a stack node.
  20337. *
  20338. * @tsl
  20339. * @function
  20340. * @param {?StackNode} [parent=null] - The parent stack node.
  20341. * @returns {StackNode}
  20342. */
  20343. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  20344. /**
  20345. * Generates a layout for struct members.
  20346. * This function takes an object representing struct members and returns an array of member layouts.
  20347. * Each member layout includes the member's name, type, and whether it is atomic.
  20348. *
  20349. * @param {Object.<string, string|Object>} members - An object where keys are member names and values are either types (as strings) or objects with type and atomic properties.
  20350. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  20351. */
  20352. function getMembersLayout( members ) {
  20353. return Object.entries( members ).map( ( [ name, value ] ) => {
  20354. if ( typeof value === 'string' ) {
  20355. return { name, type: value, atomic: false };
  20356. }
  20357. return { name, type: value.type, atomic: value.atomic || false };
  20358. } );
  20359. }
  20360. /**
  20361. * Represents a struct type node in the node-based system.
  20362. * This class is used to define and manage the layout and types of struct members.
  20363. * It extends the base Node class and provides methods to get the length of the struct,
  20364. * retrieve member types, and generate the struct type for a builder.
  20365. *
  20366. * @augments Node
  20367. */
  20368. class StructTypeNode extends Node {
  20369. static get type() {
  20370. return 'StructTypeNode';
  20371. }
  20372. /**
  20373. * Creates an instance of StructTypeNode.
  20374. *
  20375. * @param {Object} membersLayout - The layout of the members for the struct.
  20376. * @param {?string} [name=null] - The optional name of the struct.
  20377. */
  20378. constructor( membersLayout, name = null ) {
  20379. super( 'struct' );
  20380. /**
  20381. * The layout of the members for the struct
  20382. *
  20383. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  20384. */
  20385. this.membersLayout = getMembersLayout( membersLayout );
  20386. /**
  20387. * The name of the struct.
  20388. *
  20389. * @type {?string}
  20390. * @default null
  20391. */
  20392. this.name = name;
  20393. /**
  20394. * This flag can be used for type testing.
  20395. *
  20396. * @type {boolean}
  20397. * @readonly
  20398. * @default true
  20399. */
  20400. this.isStructLayoutNode = true;
  20401. }
  20402. /**
  20403. * Returns the length of the struct.
  20404. * The length is calculated by summing the lengths of the struct's members.
  20405. *
  20406. * @returns {number} The length of the struct.
  20407. */
  20408. getLength() {
  20409. let length = 0;
  20410. for ( const member of this.membersLayout ) {
  20411. length += getLengthFromType( member.type );
  20412. }
  20413. return length;
  20414. }
  20415. getMemberType( builder, name ) {
  20416. const member = this.membersLayout.find( m => m.name === name );
  20417. return member ? member.type : 'void';
  20418. }
  20419. getNodeType( builder ) {
  20420. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  20421. return structType.name;
  20422. }
  20423. setup( builder ) {
  20424. builder.addInclude( this );
  20425. }
  20426. generate( builder ) {
  20427. return this.getNodeType( builder );
  20428. }
  20429. }
  20430. /**
  20431. * StructNode allows to create custom structures with multiple members.
  20432. * This can also be used to define structures in attribute and uniform data.
  20433. *
  20434. * ```js
  20435. * // Define a custom struct
  20436. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  20437. *
  20438. * // Create a new instance of the struct
  20439. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  20440. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  20441. *
  20442. * // Access the struct members
  20443. * const min = bb.get( 'min' );
  20444. *
  20445. * // Assign a new value to a member
  20446. * min.assign( vec3() );
  20447. * ```
  20448. * @augments Node
  20449. */
  20450. class StructNode extends Node {
  20451. static get type() {
  20452. return 'StructNode';
  20453. }
  20454. constructor( structLayoutNode, values ) {
  20455. super( 'vec3' );
  20456. this.structLayoutNode = structLayoutNode;
  20457. this.values = values;
  20458. this.isStructNode = true;
  20459. }
  20460. getNodeType( builder ) {
  20461. return this.structLayoutNode.getNodeType( builder );
  20462. }
  20463. getMemberType( builder, name ) {
  20464. return this.structLayoutNode.getMemberType( builder, name );
  20465. }
  20466. generate( builder ) {
  20467. const nodeVar = builder.getVarFromNode( this );
  20468. const structType = nodeVar.type;
  20469. const propertyName = builder.getPropertyName( nodeVar );
  20470. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  20471. return nodeVar.name;
  20472. }
  20473. }
  20474. /**
  20475. * TSL function for creating a struct node.
  20476. *
  20477. * @tsl
  20478. * @function
  20479. * @param {Object} membersLayout - The layout of the struct members.
  20480. * @param {?string} [name=null] - The name of the struct.
  20481. * @returns {Function} The struct function.
  20482. */
  20483. const struct = ( membersLayout, name = null ) => {
  20484. const structLayout = new StructTypeNode( membersLayout, name );
  20485. const struct = ( ...params ) => {
  20486. let values = null;
  20487. if ( params.length > 0 ) {
  20488. if ( params[ 0 ].isNode ) {
  20489. values = {};
  20490. const names = Object.keys( membersLayout );
  20491. for ( let i = 0; i < params.length; i ++ ) {
  20492. values[ names[ i ] ] = params[ i ];
  20493. }
  20494. } else {
  20495. values = params[ 0 ];
  20496. }
  20497. }
  20498. return nodeObject( new StructNode( structLayout, values ) );
  20499. };
  20500. struct.layout = structLayout;
  20501. struct.isStruct = true;
  20502. return struct;
  20503. };
  20504. /**
  20505. * This node can be used to define multiple outputs in a shader programs.
  20506. *
  20507. * @augments Node
  20508. */
  20509. class OutputStructNode extends Node {
  20510. static get type() {
  20511. return 'OutputStructNode';
  20512. }
  20513. /**
  20514. * Constructs a new output struct node. The constructor can be invoked with an
  20515. * arbitrary number of nodes representing the members.
  20516. *
  20517. * @param {...Node} members - A parameter list of nodes.
  20518. */
  20519. constructor( ...members ) {
  20520. super();
  20521. /**
  20522. * An array of nodes which defines the output.
  20523. *
  20524. * @type {Array<Node>}
  20525. */
  20526. this.members = members;
  20527. /**
  20528. * This flag can be used for type testing.
  20529. *
  20530. * @type {boolean}
  20531. * @readonly
  20532. * @default true
  20533. */
  20534. this.isOutputStructNode = true;
  20535. }
  20536. getNodeType( builder ) {
  20537. const properties = builder.getNodeProperties( this );
  20538. if ( properties.membersLayout === undefined ) {
  20539. const members = this.members;
  20540. const membersLayout = [];
  20541. for ( let i = 0; i < members.length; i ++ ) {
  20542. const name = 'm' + i;
  20543. const type = members[ i ].getNodeType( builder );
  20544. membersLayout.push( { name, type, index: i } );
  20545. }
  20546. properties.membersLayout = membersLayout;
  20547. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  20548. }
  20549. return properties.structType.name;
  20550. }
  20551. generate( builder ) {
  20552. const propertyName = builder.getOutputStructName();
  20553. const members = this.members;
  20554. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  20555. for ( let i = 0; i < members.length; i ++ ) {
  20556. const snippet = members[ i ].build( builder );
  20557. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  20558. }
  20559. return propertyName;
  20560. }
  20561. }
  20562. /**
  20563. * TSL function for creating an output struct node.
  20564. *
  20565. * @tsl
  20566. * @function
  20567. * @param {...Node} members - A parameter list of nodes.
  20568. * @returns {OutputStructNode}
  20569. */
  20570. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  20571. /**
  20572. * Returns the MRT texture index for the given name.
  20573. *
  20574. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  20575. * @param {string} name - The name of the MRT texture which index is requested.
  20576. * @return {number} The texture index.
  20577. */
  20578. function getTextureIndex( textures, name ) {
  20579. for ( let i = 0; i < textures.length; i ++ ) {
  20580. if ( textures[ i ].name === name ) {
  20581. return i;
  20582. }
  20583. }
  20584. return - 1;
  20585. }
  20586. /**
  20587. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  20588. * post-processing is shown below:
  20589. * ```js
  20590. * const mrtNode = mrt( {
  20591. * output: output,
  20592. * normal: normalView
  20593. * } ) );
  20594. * ```
  20595. * The MRT output is defined as a dictionary.
  20596. *
  20597. * @augments OutputStructNode
  20598. */
  20599. class MRTNode extends OutputStructNode {
  20600. static get type() {
  20601. return 'MRTNode';
  20602. }
  20603. /**
  20604. * Constructs a new output struct node.
  20605. *
  20606. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  20607. */
  20608. constructor( outputNodes ) {
  20609. super();
  20610. /**
  20611. * A dictionary representing the MRT outputs. The key
  20612. * is the name of the output, the value the node which produces
  20613. * the output result.
  20614. *
  20615. * @type {Object<string, Node>}
  20616. */
  20617. this.outputNodes = outputNodes;
  20618. /**
  20619. * This flag can be used for type testing.
  20620. *
  20621. * @type {boolean}
  20622. * @readonly
  20623. * @default true
  20624. */
  20625. this.isMRTNode = true;
  20626. }
  20627. /**
  20628. * Returns `true` if the MRT node has an output with the given name.
  20629. *
  20630. * @param {string} name - The name of the output.
  20631. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  20632. */
  20633. has( name ) {
  20634. return this.outputNodes[ name ] !== undefined;
  20635. }
  20636. /**
  20637. * Returns the output node for the given name.
  20638. *
  20639. * @param {string} name - The name of the output.
  20640. * @return {Node} The output node.
  20641. */
  20642. get( name ) {
  20643. return this.outputNodes[ name ];
  20644. }
  20645. /**
  20646. * Merges the outputs of the given MRT node with the outputs of this node.
  20647. *
  20648. * @param {MRTNode} mrtNode - The MRT to merge.
  20649. * @return {MRTNode} A new MRT node with merged outputs..
  20650. */
  20651. merge( mrtNode ) {
  20652. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  20653. return mrt( outputs );
  20654. }
  20655. setup( builder ) {
  20656. const outputNodes = this.outputNodes;
  20657. const mrt = builder.renderer.getRenderTarget();
  20658. const members = [];
  20659. const textures = mrt.textures;
  20660. for ( const name in outputNodes ) {
  20661. const index = getTextureIndex( textures, name );
  20662. members[ index ] = vec4( outputNodes[ name ] );
  20663. }
  20664. this.members = members;
  20665. return super.setup( builder );
  20666. }
  20667. }
  20668. /**
  20669. * TSL function for creating a MRT node.
  20670. *
  20671. * @tsl
  20672. * @function
  20673. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  20674. * @returns {MRTNode}
  20675. */
  20676. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  20677. /**
  20678. * Generates a hash value in the range `[0, 1]` from the given seed.
  20679. *
  20680. * @tsl
  20681. * @function
  20682. * @param {Node<float>} seed - The seed.
  20683. * @return {Node<float>} The hash value.
  20684. */
  20685. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  20686. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  20687. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  20688. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  20689. const result = word.shiftRight( 22 ).bitXor( word );
  20690. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  20691. } );
  20692. /**
  20693. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20694. * The corners are mapped to `0` and the center to `1`.
  20695. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20696. *
  20697. * @tsl
  20698. * @function
  20699. * @param {Node<float>} x - The value to remap.
  20700. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  20701. * @return {Node<float>} The remapped value.
  20702. */
  20703. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  20704. /**
  20705. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20706. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  20707. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20708. *
  20709. * @tsl
  20710. * @function
  20711. * @param {Node<float>} x - The value to remap.
  20712. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  20713. * @return {Node<float>} The remapped value.
  20714. */
  20715. 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 ) );
  20716. /**
  20717. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20718. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  20719. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20720. *
  20721. * @tsl
  20722. * @function
  20723. * @param {Node<float>} x - The value to remap.
  20724. * @param {Node<float>} a - First control parameter.
  20725. * @param {Node<float>} b - Second control parameter.
  20726. * @return {Node<float>} The remapped value.
  20727. */
  20728. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  20729. /**
  20730. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  20731. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20732. *
  20733. * @tsl
  20734. * @function
  20735. * @param {Node<float>} x - The value to compute the sin for.
  20736. * @param {Node<float>} k - Controls the amount of bounces.
  20737. * @return {Node<float>} The result value.
  20738. */
  20739. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  20740. // https://github.com/cabbibo/glsl-tri-noise-3d
  20741. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  20742. return x.fract().sub( .5 ).abs();
  20743. } ).setLayout( {
  20744. name: 'tri',
  20745. type: 'float',
  20746. inputs: [
  20747. { name: 'x', type: 'float' }
  20748. ]
  20749. } );
  20750. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  20751. 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. ) ) ) ) );
  20752. } ).setLayout( {
  20753. name: 'tri3',
  20754. type: 'vec3',
  20755. inputs: [
  20756. { name: 'p', type: 'vec3' }
  20757. ]
  20758. } );
  20759. /**
  20760. * Generates a noise value from the given position, speed and time parameters.
  20761. *
  20762. * @tsl
  20763. * @function
  20764. * @param {Node<vec3>} position - The position.
  20765. * @param {Node<float>} speed - The speed.
  20766. * @param {Node<float>} time - The time.
  20767. * @return {Node<float>} The generated noise.
  20768. */
  20769. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  20770. const p = vec3( position ).toVar();
  20771. const z = float( 1.4 ).toVar();
  20772. const rz = float( 0.0 ).toVar();
  20773. const bp = vec3( p ).toVar();
  20774. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  20775. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  20776. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  20777. bp.mulAssign( 1.8 );
  20778. z.mulAssign( 1.5 );
  20779. p.mulAssign( 1.2 );
  20780. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  20781. rz.addAssign( t.div( z ) );
  20782. bp.addAssign( 0.14 );
  20783. } );
  20784. return rz;
  20785. } ).setLayout( {
  20786. name: 'triNoise3D',
  20787. type: 'float',
  20788. inputs: [
  20789. { name: 'position', type: 'vec3' },
  20790. { name: 'speed', type: 'float' },
  20791. { name: 'time', type: 'float' }
  20792. ]
  20793. } );
  20794. /**
  20795. * This class allows to define multiple overloaded versions
  20796. * of the same function. Depending on the parameters of the function
  20797. * call, the node picks the best-fit overloaded version.
  20798. *
  20799. * @augments Node
  20800. */
  20801. class FunctionOverloadingNode extends Node {
  20802. static get type() {
  20803. return 'FunctionOverloadingNode';
  20804. }
  20805. /**
  20806. * Constructs a new function overloading node.
  20807. *
  20808. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20809. * @param {...Node} parametersNodes - A list of parameter nodes.
  20810. */
  20811. constructor( functionNodes = [], ...parametersNodes ) {
  20812. super();
  20813. /**
  20814. * Array of `Fn` function definitions.
  20815. *
  20816. * @type {Array<Function>}
  20817. */
  20818. this.functionNodes = functionNodes;
  20819. /**
  20820. * A list of parameter nodes.
  20821. *
  20822. * @type {Array<Node>}
  20823. */
  20824. this.parametersNodes = parametersNodes;
  20825. /**
  20826. * The selected overloaded function call.
  20827. *
  20828. * @private
  20829. * @type {ShaderCallNodeInternal}
  20830. */
  20831. this._candidateFnCall = null;
  20832. /**
  20833. * This node is marked as global.
  20834. *
  20835. * @type {boolean}
  20836. * @default true
  20837. */
  20838. this.global = true;
  20839. }
  20840. /**
  20841. * This method is overwritten since the node type is inferred from
  20842. * the function's return type.
  20843. *
  20844. * @param {NodeBuilder} builder - The current node builder.
  20845. * @return {string} The node type.
  20846. */
  20847. getNodeType() {
  20848. return this.functionNodes[ 0 ].shaderNode.layout.type;
  20849. }
  20850. setup( builder ) {
  20851. const params = this.parametersNodes;
  20852. let candidateFnCall = this._candidateFnCall;
  20853. if ( candidateFnCall === null ) {
  20854. let candidateFn = null;
  20855. let candidateScore = - 1;
  20856. for ( const functionNode of this.functionNodes ) {
  20857. const shaderNode = functionNode.shaderNode;
  20858. const layout = shaderNode.layout;
  20859. if ( layout === null ) {
  20860. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  20861. }
  20862. const inputs = layout.inputs;
  20863. if ( params.length === inputs.length ) {
  20864. let score = 0;
  20865. for ( let i = 0; i < params.length; i ++ ) {
  20866. const param = params[ i ];
  20867. const input = inputs[ i ];
  20868. if ( param.getNodeType( builder ) === input.type ) {
  20869. score ++;
  20870. } else {
  20871. score = 0;
  20872. }
  20873. }
  20874. if ( score > candidateScore ) {
  20875. candidateFn = functionNode;
  20876. candidateScore = score;
  20877. }
  20878. }
  20879. }
  20880. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  20881. }
  20882. return candidateFnCall;
  20883. }
  20884. }
  20885. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  20886. /**
  20887. * TSL function for creating a function overloading node.
  20888. *
  20889. * @tsl
  20890. * @function
  20891. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20892. * @returns {FunctionOverloadingNode}
  20893. */
  20894. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  20895. /**
  20896. * Represents the elapsed time in seconds.
  20897. *
  20898. * @tsl
  20899. * @type {UniformNode<float>}
  20900. */
  20901. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  20902. /**
  20903. * Represents the delta time in seconds.
  20904. *
  20905. * @tsl
  20906. * @type {UniformNode<float>}
  20907. */
  20908. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  20909. /**
  20910. * Represents the current frame ID.
  20911. *
  20912. * @tsl
  20913. * @type {UniformNode<uint>}
  20914. */
  20915. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  20916. // Deprecated
  20917. /**
  20918. * @tsl
  20919. * @function
  20920. * @deprecated since r170. Use {@link time} instead.
  20921. *
  20922. * @param {number} [timeScale=1] - The time scale.
  20923. * @returns {UniformNode<float>}
  20924. */
  20925. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  20926. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  20927. return time.mul( timeScale );
  20928. };
  20929. /**
  20930. * @tsl
  20931. * @function
  20932. * @deprecated since r170. Use {@link time} instead.
  20933. *
  20934. * @param {number} [timeScale=1] - The time scale.
  20935. * @returns {UniformNode<float>}
  20936. */
  20937. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  20938. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  20939. return time.mul( timeScale );
  20940. };
  20941. /**
  20942. * @tsl
  20943. * @function
  20944. * @deprecated since r170. Use {@link deltaTime} instead.
  20945. *
  20946. * @param {number} [timeScale=1] - The time scale.
  20947. * @returns {UniformNode<float>}
  20948. */
  20949. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  20950. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  20951. return deltaTime.mul( timeScale );
  20952. };
  20953. /**
  20954. * Generates a sine wave oscillation based on a timer.
  20955. *
  20956. * @tsl
  20957. * @function
  20958. * @param {Node<float>} t - The timer to generate the oscillation with.
  20959. * @return {Node<float>} The oscillation node.
  20960. */
  20961. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  20962. /**
  20963. * Generates a square wave oscillation based on a timer.
  20964. *
  20965. * @tsl
  20966. * @function
  20967. * @param {Node<float>} t - The timer to generate the oscillation with.
  20968. * @return {Node<float>} The oscillation node.
  20969. */
  20970. const oscSquare = ( t = time ) => t.fract().round();
  20971. /**
  20972. * Generates a triangle wave oscillation based on a timer.
  20973. *
  20974. * @tsl
  20975. * @function
  20976. * @param {Node<float>} t - The timer to generate the oscillation with.
  20977. * @return {Node<float>} The oscillation node.
  20978. */
  20979. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  20980. /**
  20981. * Generates a sawtooth wave oscillation based on a timer.
  20982. *
  20983. * @tsl
  20984. * @function
  20985. * @param {Node<float>} t - The timer to generate the oscillation with.
  20986. * @return {Node<float>} The oscillation node.
  20987. */
  20988. const oscSawtooth = ( t = time ) => t.fract();
  20989. /**
  20990. * Rotates the given uv coordinates around a center point
  20991. *
  20992. * @tsl
  20993. * @function
  20994. * @param {Node<vec2>} uv - The uv coordinates.
  20995. * @param {Node<float>} rotation - The rotation defined in radians.
  20996. * @param {Node<vec2>} center - The center of rotation
  20997. * @return {Node<vec2>} The rotated uv coordinates.
  20998. */
  20999. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  21000. return rotate( uv.sub( center ), rotation ).add( center );
  21001. } );
  21002. /**
  21003. * Applies a spherical warping effect to the given uv coordinates.
  21004. *
  21005. * @tsl
  21006. * @function
  21007. * @param {Node<vec2>} uv - The uv coordinates.
  21008. * @param {Node<float>} strength - The strength of the effect.
  21009. * @param {Node<vec2>} center - The center point
  21010. * @return {Node<vec2>} The updated uv coordinates.
  21011. */
  21012. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  21013. const delta = uv.sub( center );
  21014. const delta2 = delta.dot( delta );
  21015. const delta4 = delta2.mul( delta2 );
  21016. const deltaOffset = delta4.mul( strength );
  21017. return uv.add( delta.mul( deltaOffset ) );
  21018. } );
  21019. /**
  21020. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  21021. * oriented always towards the camera.
  21022. *
  21023. * ```js
  21024. * material.vertexNode = billboarding();
  21025. * ```
  21026. *
  21027. * @tsl
  21028. * @function
  21029. * @param {Object} config - The configuration object.
  21030. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  21031. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  21032. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  21033. * @return {Node<vec3>} The updated vertex position in clip space.
  21034. */
  21035. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  21036. let worldMatrix;
  21037. if ( position !== null ) {
  21038. worldMatrix = modelWorldMatrix.toVar();
  21039. worldMatrix[ 3 ][ 0 ] = position.x;
  21040. worldMatrix[ 3 ][ 1 ] = position.y;
  21041. worldMatrix[ 3 ][ 2 ] = position.z;
  21042. } else {
  21043. worldMatrix = modelWorldMatrix;
  21044. }
  21045. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  21046. if ( defined( horizontal ) ) {
  21047. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  21048. modelViewMatrix[ 0 ][ 1 ] = 0;
  21049. modelViewMatrix[ 0 ][ 2 ] = 0;
  21050. }
  21051. if ( defined( vertical ) ) {
  21052. modelViewMatrix[ 1 ][ 0 ] = 0;
  21053. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  21054. modelViewMatrix[ 1 ][ 2 ] = 0;
  21055. }
  21056. modelViewMatrix[ 2 ][ 0 ] = 0;
  21057. modelViewMatrix[ 2 ][ 1 ] = 0;
  21058. modelViewMatrix[ 2 ][ 2 ] = 1;
  21059. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21060. } );
  21061. /**
  21062. * A special version of a screen uv function that involves a depth comparison
  21063. * when computing the final uvs. The function mitigates visual errors when
  21064. * using viewport texture nodes for refraction purposes. Without this function
  21065. * objects in front of a refractive surface might appear on the refractive surface
  21066. * which is incorrect.
  21067. *
  21068. * @tsl
  21069. * @function
  21070. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  21071. * @return {Node<vec2>} The update uv coordinates.
  21072. */
  21073. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  21074. const depth = linearDepth();
  21075. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  21076. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  21077. return finalUV;
  21078. } );
  21079. /**
  21080. * Can be used to compute texture coordinates for animated sprite sheets.
  21081. *
  21082. * ```js
  21083. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  21084. *
  21085. * material.colorNode = texture( spriteSheet, uvNode );
  21086. * ```
  21087. *
  21088. * @augments Node
  21089. */
  21090. class SpriteSheetUVNode extends Node {
  21091. static get type() {
  21092. return 'SpriteSheetUVNode';
  21093. }
  21094. /**
  21095. * Constructs a new sprite sheet uv node.
  21096. *
  21097. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  21098. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  21099. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  21100. */
  21101. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  21102. super( 'vec2' );
  21103. /**
  21104. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  21105. *
  21106. * @type {Node<vec2>}
  21107. */
  21108. this.countNode = countNode;
  21109. /**
  21110. * The uv node.
  21111. *
  21112. * @type {Node<vec2>}
  21113. */
  21114. this.uvNode = uvNode;
  21115. /**
  21116. * The node that defines the current frame/sprite.
  21117. *
  21118. * @type {Node<float>}
  21119. */
  21120. this.frameNode = frameNode;
  21121. }
  21122. setup() {
  21123. const { frameNode, uvNode, countNode } = this;
  21124. const { width, height } = countNode;
  21125. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  21126. const column = frameNum.mod( width );
  21127. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  21128. const scale = countNode.reciprocal();
  21129. const uvFrameOffset = vec2( column, row );
  21130. return uvNode.add( uvFrameOffset ).mul( scale );
  21131. }
  21132. }
  21133. /**
  21134. * TSL function for creating a sprite sheet uv node.
  21135. *
  21136. * @tsl
  21137. * @function
  21138. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  21139. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  21140. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  21141. * @returns {SpriteSheetUVNode}
  21142. */
  21143. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  21144. /**
  21145. * Can be used for triplanar texture mapping.
  21146. *
  21147. * ```js
  21148. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  21149. * ```
  21150. *
  21151. * @augments Node
  21152. */
  21153. class TriplanarTexturesNode extends Node {
  21154. static get type() {
  21155. return 'TriplanarTexturesNode';
  21156. }
  21157. /**
  21158. * Constructs a new triplanar textures node.
  21159. *
  21160. * @param {Node} textureXNode - First texture node.
  21161. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21162. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21163. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  21164. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  21165. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  21166. */
  21167. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  21168. super( 'vec4' );
  21169. /**
  21170. * First texture node.
  21171. *
  21172. * @type {Node}
  21173. */
  21174. this.textureXNode = textureXNode;
  21175. /**
  21176. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21177. *
  21178. * @type {?Node}
  21179. * @default null
  21180. */
  21181. this.textureYNode = textureYNode;
  21182. /**
  21183. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21184. *
  21185. * @type {?Node}
  21186. * @default null
  21187. */
  21188. this.textureZNode = textureZNode;
  21189. /**
  21190. * The scale node.
  21191. *
  21192. * @type {Node<float>}
  21193. * @default float(1)
  21194. */
  21195. this.scaleNode = scaleNode;
  21196. /**
  21197. * Vertex positions in local space.
  21198. *
  21199. * @type {Node<vec3>}
  21200. * @default positionLocal
  21201. */
  21202. this.positionNode = positionNode;
  21203. /**
  21204. * Normals in local space.
  21205. *
  21206. * @type {Node<vec3>}
  21207. * @default normalLocal
  21208. */
  21209. this.normalNode = normalNode;
  21210. }
  21211. setup() {
  21212. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  21213. // Ref: https://github.com/keijiro/StandardTriplanar
  21214. // Blending factor of triplanar mapping
  21215. let bf = normalNode.abs().normalize();
  21216. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  21217. // Triplanar mapping
  21218. const tx = positionNode.yz.mul( scaleNode );
  21219. const ty = positionNode.zx.mul( scaleNode );
  21220. const tz = positionNode.xy.mul( scaleNode );
  21221. // Base color
  21222. const textureX = textureXNode.value;
  21223. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  21224. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  21225. const cx = texture( textureX, tx ).mul( bf.x );
  21226. const cy = texture( textureY, ty ).mul( bf.y );
  21227. const cz = texture( textureZ, tz ).mul( bf.z );
  21228. return add( cx, cy, cz );
  21229. }
  21230. }
  21231. /**
  21232. * TSL function for creating a triplanar textures node.
  21233. *
  21234. * @tsl
  21235. * @function
  21236. * @param {Node} textureXNode - First texture node.
  21237. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21238. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21239. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  21240. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  21241. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  21242. * @returns {TriplanarTexturesNode}
  21243. */
  21244. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  21245. /**
  21246. * TSL function for creating a triplanar textures node.
  21247. *
  21248. * @tsl
  21249. * @function
  21250. * @param {Node} textureXNode - First texture node.
  21251. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21252. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21253. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  21254. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  21255. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  21256. * @returns {TriplanarTexturesNode}
  21257. */
  21258. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  21259. const _reflectorPlane = new Plane();
  21260. const _normal = new Vector3();
  21261. const _reflectorWorldPosition = new Vector3();
  21262. const _cameraWorldPosition = new Vector3();
  21263. const _rotationMatrix = new Matrix4();
  21264. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  21265. const clipPlane = new Vector4();
  21266. const _view = new Vector3();
  21267. const _target = new Vector3();
  21268. const _q = new Vector4();
  21269. const _size$2 = new Vector2();
  21270. const _defaultRT = new RenderTarget();
  21271. const _defaultUV = screenUV.flipX();
  21272. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  21273. let _inReflector = false;
  21274. /**
  21275. * This node can be used to implement mirror-like flat reflective surfaces.
  21276. *
  21277. * ```js
  21278. * const groundReflector = reflector();
  21279. * material.colorNode = groundReflector;
  21280. *
  21281. * const plane = new Mesh( geometry, material );
  21282. * plane.add( groundReflector.target );
  21283. * ```
  21284. *
  21285. * @augments TextureNode
  21286. */
  21287. class ReflectorNode extends TextureNode {
  21288. static get type() {
  21289. return 'ReflectorNode';
  21290. }
  21291. /**
  21292. * Constructs a new reflector node.
  21293. *
  21294. * @param {Object} [parameters={}] - An object holding configuration parameters.
  21295. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  21296. * @param {number} [parameters.resolution=1] - The resolution scale.
  21297. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  21298. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  21299. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  21300. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  21301. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  21302. */
  21303. constructor( parameters = {} ) {
  21304. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  21305. /**
  21306. * A reference to the internal reflector base node which holds the actual implementation.
  21307. *
  21308. * @private
  21309. * @type {ReflectorBaseNode}
  21310. * @default ReflectorBaseNode
  21311. */
  21312. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  21313. /**
  21314. * A reference to the internal depth node.
  21315. *
  21316. * @private
  21317. * @type {?Node}
  21318. * @default null
  21319. */
  21320. this._depthNode = null;
  21321. this.setUpdateMatrix( false );
  21322. }
  21323. /**
  21324. * A reference to the internal reflector node.
  21325. *
  21326. * @type {ReflectorBaseNode}
  21327. */
  21328. get reflector() {
  21329. return this._reflectorBaseNode;
  21330. }
  21331. /**
  21332. * A reference to 3D object the reflector is linked to.
  21333. *
  21334. * @type {Object3D}
  21335. */
  21336. get target() {
  21337. return this._reflectorBaseNode.target;
  21338. }
  21339. /**
  21340. * Returns a node representing the mirror's depth. That can be used
  21341. * to implement more advanced reflection effects like distance attenuation.
  21342. *
  21343. * @return {Node} The depth node.
  21344. */
  21345. getDepthNode() {
  21346. if ( this._depthNode === null ) {
  21347. if ( this._reflectorBaseNode.depth !== true ) {
  21348. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  21349. }
  21350. this._depthNode = nodeObject( new ReflectorNode( {
  21351. defaultTexture: _defaultRT.depthTexture,
  21352. reflector: this._reflectorBaseNode
  21353. } ) );
  21354. }
  21355. return this._depthNode;
  21356. }
  21357. setup( builder ) {
  21358. // ignore if used in post-processing
  21359. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  21360. return super.setup( builder );
  21361. }
  21362. clone() {
  21363. const texture = new this.constructor( this.reflectorNode );
  21364. texture._reflectorBaseNode = this._reflectorBaseNode;
  21365. return texture;
  21366. }
  21367. }
  21368. /**
  21369. * Holds the actual implementation of the reflector.
  21370. *
  21371. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  21372. * in `ReflectorNode`, see #29619.
  21373. *
  21374. * @private
  21375. * @augments Node
  21376. */
  21377. class ReflectorBaseNode extends Node {
  21378. static get type() {
  21379. return 'ReflectorBaseNode';
  21380. }
  21381. /**
  21382. * Constructs a new reflector base node.
  21383. *
  21384. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  21385. * @param {Object} [parameters={}] - An object holding configuration parameters.
  21386. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  21387. * @param {number} [parameters.resolution=1] - The resolution scale.
  21388. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  21389. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  21390. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  21391. */
  21392. constructor( textureNode, parameters = {} ) {
  21393. super();
  21394. const {
  21395. target = new Object3D(),
  21396. resolution = 1,
  21397. generateMipmaps = false,
  21398. bounces = true,
  21399. depth = false
  21400. } = parameters;
  21401. /**
  21402. * Represents the rendered reflections as a texture node.
  21403. *
  21404. * @type {TextureNode}
  21405. */
  21406. this.textureNode = textureNode;
  21407. /**
  21408. * The 3D object the reflector is linked to.
  21409. *
  21410. * @type {Object3D}
  21411. * @default {new Object3D()}
  21412. */
  21413. this.target = target;
  21414. /**
  21415. * The resolution scale.
  21416. *
  21417. * @type {number}
  21418. * @default {1}
  21419. */
  21420. this.resolution = resolution;
  21421. /**
  21422. * Whether mipmaps should be generated or not.
  21423. *
  21424. * @type {boolean}
  21425. * @default {false}
  21426. */
  21427. this.generateMipmaps = generateMipmaps;
  21428. /**
  21429. * Whether reflectors can render other reflector nodes or not.
  21430. *
  21431. * @type {boolean}
  21432. * @default {true}
  21433. */
  21434. this.bounces = bounces;
  21435. /**
  21436. * Whether depth data should be generated or not.
  21437. *
  21438. * @type {boolean}
  21439. * @default {false}
  21440. */
  21441. this.depth = depth;
  21442. /**
  21443. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  21444. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  21445. *
  21446. * @type {string}
  21447. * @default 'render'
  21448. */
  21449. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  21450. /**
  21451. * Weak map for managing virtual cameras.
  21452. *
  21453. * @type {WeakMap<Camera, Camera>}
  21454. */
  21455. this.virtualCameras = new WeakMap();
  21456. /**
  21457. * Weak map for managing render targets.
  21458. *
  21459. * @type {WeakMap<Camera, RenderTarget>}
  21460. */
  21461. this.renderTargets = new WeakMap();
  21462. /**
  21463. * Force render even if reflector is facing away from camera.
  21464. *
  21465. * @type {boolean}
  21466. * @default {false}
  21467. */
  21468. this.forceUpdate = false;
  21469. }
  21470. /**
  21471. * Updates the resolution of the internal render target.
  21472. *
  21473. * @private
  21474. * @param {RenderTarget} renderTarget - The render target to resize.
  21475. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  21476. */
  21477. _updateResolution( renderTarget, renderer ) {
  21478. const resolution = this.resolution;
  21479. renderer.getDrawingBufferSize( _size$2 );
  21480. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  21481. }
  21482. setup( builder ) {
  21483. this._updateResolution( _defaultRT, builder.renderer );
  21484. return super.setup( builder );
  21485. }
  21486. /**
  21487. * Returns a virtual camera for the given camera. The virtual camera is used to
  21488. * render the scene from the reflector's view so correct reflections can be produced.
  21489. *
  21490. * @param {Camera} camera - The scene's camera.
  21491. * @return {Camera} The corresponding virtual camera.
  21492. */
  21493. getVirtualCamera( camera ) {
  21494. let virtualCamera = this.virtualCameras.get( camera );
  21495. if ( virtualCamera === undefined ) {
  21496. virtualCamera = camera.clone();
  21497. this.virtualCameras.set( camera, virtualCamera );
  21498. }
  21499. return virtualCamera;
  21500. }
  21501. /**
  21502. * Returns a render target for the given camera. The reflections are rendered
  21503. * into this render target.
  21504. *
  21505. * @param {Camera} camera - The scene's camera.
  21506. * @return {RenderTarget} The render target.
  21507. */
  21508. getRenderTarget( camera ) {
  21509. let renderTarget = this.renderTargets.get( camera );
  21510. if ( renderTarget === undefined ) {
  21511. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  21512. if ( this.generateMipmaps === true ) {
  21513. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  21514. renderTarget.texture.generateMipmaps = true;
  21515. }
  21516. if ( this.depth === true ) {
  21517. renderTarget.depthTexture = new DepthTexture();
  21518. }
  21519. this.renderTargets.set( camera, renderTarget );
  21520. }
  21521. return renderTarget;
  21522. }
  21523. updateBefore( frame ) {
  21524. if ( this.bounces === false && _inReflector ) return false;
  21525. _inReflector = true;
  21526. const { scene, camera, renderer, material } = frame;
  21527. const { target } = this;
  21528. const virtualCamera = this.getVirtualCamera( camera );
  21529. const renderTarget = this.getRenderTarget( virtualCamera );
  21530. renderer.getDrawingBufferSize( _size$2 );
  21531. this._updateResolution( renderTarget, renderer );
  21532. //
  21533. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  21534. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  21535. _rotationMatrix.extractRotation( target.matrixWorld );
  21536. _normal.set( 0, 0, 1 );
  21537. _normal.applyMatrix4( _rotationMatrix );
  21538. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  21539. // Avoid rendering when reflector is facing away unless forcing an update
  21540. const isFacingAway = _view.dot( _normal ) > 0;
  21541. if ( isFacingAway === true && this.forceUpdate === false ) return;
  21542. _view.reflect( _normal ).negate();
  21543. _view.add( _reflectorWorldPosition );
  21544. _rotationMatrix.extractRotation( camera.matrixWorld );
  21545. _lookAtPosition.set( 0, 0, - 1 );
  21546. _lookAtPosition.applyMatrix4( _rotationMatrix );
  21547. _lookAtPosition.add( _cameraWorldPosition );
  21548. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  21549. _target.reflect( _normal ).negate();
  21550. _target.add( _reflectorWorldPosition );
  21551. //
  21552. virtualCamera.coordinateSystem = camera.coordinateSystem;
  21553. virtualCamera.position.copy( _view );
  21554. virtualCamera.up.set( 0, 1, 0 );
  21555. virtualCamera.up.applyMatrix4( _rotationMatrix );
  21556. virtualCamera.up.reflect( _normal );
  21557. virtualCamera.lookAt( _target );
  21558. virtualCamera.near = camera.near;
  21559. virtualCamera.far = camera.far;
  21560. virtualCamera.updateMatrixWorld();
  21561. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  21562. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  21563. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  21564. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  21565. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  21566. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  21567. const projectionMatrix = virtualCamera.projectionMatrix;
  21568. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  21569. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  21570. _q.z = - 1.0;
  21571. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  21572. // Calculate the scaled plane vector
  21573. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  21574. const clipBias = 0;
  21575. // Replacing the third row of the projection matrix
  21576. projectionMatrix.elements[ 2 ] = clipPlane.x;
  21577. projectionMatrix.elements[ 6 ] = clipPlane.y;
  21578. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  21579. projectionMatrix.elements[ 14 ] = clipPlane.w;
  21580. //
  21581. this.textureNode.value = renderTarget.texture;
  21582. if ( this.depth === true ) {
  21583. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  21584. }
  21585. material.visible = false;
  21586. const currentRenderTarget = renderer.getRenderTarget();
  21587. const currentMRT = renderer.getMRT();
  21588. const currentAutoClear = renderer.autoClear;
  21589. renderer.setMRT( null );
  21590. renderer.setRenderTarget( renderTarget );
  21591. renderer.autoClear = true;
  21592. renderer.render( scene, virtualCamera );
  21593. renderer.setMRT( currentMRT );
  21594. renderer.setRenderTarget( currentRenderTarget );
  21595. renderer.autoClear = currentAutoClear;
  21596. material.visible = true;
  21597. _inReflector = false;
  21598. this.forceUpdate = false;
  21599. }
  21600. }
  21601. /**
  21602. * TSL function for creating a reflector node.
  21603. *
  21604. * @tsl
  21605. * @function
  21606. * @param {Object} [parameters={}] - An object holding configuration parameters.
  21607. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  21608. * @param {number} [parameters.resolution=1] - The resolution scale.
  21609. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  21610. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  21611. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  21612. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  21613. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  21614. * @returns {ReflectorNode}
  21615. */
  21616. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  21617. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  21618. /**
  21619. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  21620. *
  21621. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  21622. *
  21623. * @private
  21624. * @augments BufferGeometry
  21625. */
  21626. class QuadGeometry extends BufferGeometry {
  21627. /**
  21628. * Constructs a new quad geometry.
  21629. *
  21630. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  21631. */
  21632. constructor( flipY = false ) {
  21633. super();
  21634. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  21635. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  21636. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  21637. }
  21638. }
  21639. const _geometry = /*@__PURE__*/ new QuadGeometry();
  21640. /**
  21641. * This module is a helper for passes which need to render a full
  21642. * screen effect which is quite common in context of post processing.
  21643. *
  21644. * The intended usage is to reuse a single quad mesh for rendering
  21645. * subsequent passes by just reassigning the `material` reference.
  21646. *
  21647. * Note: This module can only be used with `WebGPURenderer`.
  21648. *
  21649. * @augments Mesh
  21650. */
  21651. class QuadMesh extends Mesh {
  21652. /**
  21653. * Constructs a new quad mesh.
  21654. *
  21655. * @param {?Material} [material=null] - The material to render the quad mesh with.
  21656. */
  21657. constructor( material = null ) {
  21658. super( _geometry, material );
  21659. /**
  21660. * The camera to render the quad mesh with.
  21661. *
  21662. * @type {OrthographicCamera}
  21663. * @readonly
  21664. */
  21665. this.camera = _camera;
  21666. /**
  21667. * This flag can be used for type testing.
  21668. *
  21669. * @type {boolean}
  21670. * @readonly
  21671. * @default true
  21672. */
  21673. this.isQuadMesh = true;
  21674. }
  21675. /**
  21676. * Async version of `render()`.
  21677. *
  21678. * @async
  21679. * @param {Renderer} renderer - The renderer.
  21680. * @return {Promise} A Promise that resolves when the render has been finished.
  21681. */
  21682. async renderAsync( renderer ) {
  21683. return renderer.renderAsync( this, _camera );
  21684. }
  21685. /**
  21686. * Renders the quad mesh
  21687. *
  21688. * @param {Renderer} renderer - The renderer.
  21689. */
  21690. render( renderer ) {
  21691. renderer.render( this, _camera );
  21692. }
  21693. }
  21694. const _size$1 = /*@__PURE__*/ new Vector2();
  21695. /**
  21696. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  21697. * This module is especially relevant in context of post processing where certain nodes require
  21698. * texture input for their effects. With the helper function `convertToTexture()` which is based
  21699. * on this module, the node system can automatically ensure texture input if required.
  21700. *
  21701. * @augments TextureNode
  21702. */
  21703. class RTTNode extends TextureNode {
  21704. static get type() {
  21705. return 'RTTNode';
  21706. }
  21707. /**
  21708. * Constructs a new RTT node.
  21709. *
  21710. * @param {Node} node - The node to render a texture with.
  21711. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21712. * @param {?number} [height=null] - The height of the internal render target.
  21713. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21714. */
  21715. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  21716. const renderTarget = new RenderTarget( width, height, options );
  21717. super( renderTarget.texture, uv() );
  21718. /**
  21719. * The node to render a texture with.
  21720. *
  21721. * @type {Node}
  21722. */
  21723. this.node = node;
  21724. /**
  21725. * The width of the internal render target.
  21726. * If not width is applied, the render target is automatically resized.
  21727. *
  21728. * @type {?number}
  21729. * @default null
  21730. */
  21731. this.width = width;
  21732. /**
  21733. * The height of the internal render target.
  21734. *
  21735. * @type {?number}
  21736. * @default null
  21737. */
  21738. this.height = height;
  21739. /**
  21740. * The pixel ratio
  21741. *
  21742. * @type {number}
  21743. * @default 1
  21744. */
  21745. this.pixelRatio = 1;
  21746. /**
  21747. * The render target
  21748. *
  21749. * @type {RenderTarget}
  21750. */
  21751. this.renderTarget = renderTarget;
  21752. /**
  21753. * Whether the texture requires an update or not.
  21754. *
  21755. * @type {boolean}
  21756. * @default true
  21757. */
  21758. this.textureNeedsUpdate = true;
  21759. /**
  21760. * Whether the texture should automatically be updated or not.
  21761. *
  21762. * @type {boolean}
  21763. * @default true
  21764. */
  21765. this.autoUpdate = true;
  21766. /**
  21767. * The node which is used with the quad mesh for RTT.
  21768. *
  21769. * @private
  21770. * @type {Node}
  21771. * @default null
  21772. */
  21773. this._rttNode = null;
  21774. /**
  21775. * The internal quad mesh for RTT.
  21776. *
  21777. * @private
  21778. * @type {QuadMesh}
  21779. */
  21780. this._quadMesh = new QuadMesh( new NodeMaterial() );
  21781. /**
  21782. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  21783. * the texture once per render in its {@link RTTNode#updateBefore} method.
  21784. *
  21785. * @type {string}
  21786. * @default 'render'
  21787. */
  21788. this.updateBeforeType = NodeUpdateType.RENDER;
  21789. }
  21790. /**
  21791. * Whether the internal render target should automatically be resized or not.
  21792. *
  21793. * @type {boolean}
  21794. * @readonly
  21795. * @default true
  21796. */
  21797. get autoSize() {
  21798. return this.width === null;
  21799. }
  21800. setup( builder ) {
  21801. this._rttNode = this.node.context( builder.getSharedContext() );
  21802. this._quadMesh.material.name = 'RTT';
  21803. this._quadMesh.material.needsUpdate = true;
  21804. return super.setup( builder );
  21805. }
  21806. /**
  21807. * Sets the size of the internal render target
  21808. *
  21809. * @param {number} width - The width to set.
  21810. * @param {number} height - The width to set.
  21811. */
  21812. setSize( width, height ) {
  21813. this.width = width;
  21814. this.height = height;
  21815. const effectiveWidth = width * this.pixelRatio;
  21816. const effectiveHeight = height * this.pixelRatio;
  21817. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  21818. this.textureNeedsUpdate = true;
  21819. }
  21820. /**
  21821. * Sets the pixel ratio. This will also resize the render target.
  21822. *
  21823. * @param {number} pixelRatio - The pixel ratio to set.
  21824. */
  21825. setPixelRatio( pixelRatio ) {
  21826. this.pixelRatio = pixelRatio;
  21827. this.setSize( this.width, this.height );
  21828. }
  21829. updateBefore( { renderer } ) {
  21830. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  21831. this.textureNeedsUpdate = false;
  21832. //
  21833. if ( this.autoSize === true ) {
  21834. this.pixelRatio = renderer.getPixelRatio();
  21835. const size = renderer.getSize( _size$1 );
  21836. this.setSize( size.width, size.height );
  21837. }
  21838. //
  21839. this._quadMesh.material.fragmentNode = this._rttNode;
  21840. //
  21841. const currentRenderTarget = renderer.getRenderTarget();
  21842. renderer.setRenderTarget( this.renderTarget );
  21843. this._quadMesh.render( renderer );
  21844. renderer.setRenderTarget( currentRenderTarget );
  21845. }
  21846. clone() {
  21847. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  21848. newNode.sampler = this.sampler;
  21849. newNode.referenceNode = this;
  21850. return newNode;
  21851. }
  21852. }
  21853. /**
  21854. * TSL function for creating a RTT node.
  21855. *
  21856. * @tsl
  21857. * @function
  21858. * @param {Node} node - The node to render a texture with.
  21859. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21860. * @param {?number} [height=null] - The height of the internal render target.
  21861. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21862. * @returns {RTTNode}
  21863. */
  21864. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  21865. /**
  21866. * TSL function for converting nodes to textures nodes.
  21867. *
  21868. * @tsl
  21869. * @function
  21870. * @param {Node} node - The node to render a texture with.
  21871. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21872. * @param {?number} [height=null] - The height of the internal render target.
  21873. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21874. * @returns {RTTNode}
  21875. */
  21876. const convertToTexture = ( node, ...params ) => {
  21877. if ( node.isTextureNode ) return node;
  21878. if ( node.isPassNode ) return node.getTextureNode();
  21879. return rtt( node, ...params );
  21880. };
  21881. /**
  21882. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  21883. * depth value and the camera's inverse projection matrix.
  21884. *
  21885. * @tsl
  21886. * @function
  21887. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  21888. * @param {Node<float>} depth - The fragment's depth value.
  21889. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21890. * @return {Node<vec3>} The fragments position in view space.
  21891. */
  21892. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  21893. let clipSpacePosition;
  21894. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  21895. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  21896. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  21897. } else {
  21898. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  21899. }
  21900. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  21901. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  21902. } );
  21903. /**
  21904. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  21905. * and the camera's projection matrix
  21906. *
  21907. * @tsl
  21908. * @function
  21909. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  21910. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  21911. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  21912. */
  21913. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  21914. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  21915. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  21916. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  21917. } );
  21918. /**
  21919. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  21920. * target is available or if flat surface normals are required.
  21921. *
  21922. * @tsl
  21923. * @function
  21924. * @param {Node<vec2>} uv - The texture coordinate.
  21925. * @param {DepthTexture} depthTexture - The depth texture.
  21926. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21927. * @return {Node<vec3>} The computed normal vector.
  21928. */
  21929. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  21930. const size = textureSize( textureLoad( depthTexture ) );
  21931. const p = ivec2( uv.mul( size ) ).toVar();
  21932. const c0 = textureLoad( depthTexture, p ).toVar();
  21933. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  21934. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  21935. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  21936. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  21937. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  21938. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  21939. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  21940. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  21941. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  21942. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  21943. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  21944. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  21945. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  21946. 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 ) ) );
  21947. 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 ) ) );
  21948. return normalize( cross( dpdx, dpdy ) );
  21949. } );
  21950. /**
  21951. * This special type of instanced buffer attribute is intended for compute shaders.
  21952. * In earlier three.js versions it was only possible to update attribute data
  21953. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21954. * new material system and renderer it is now possible to use compute shaders
  21955. * to compute the data for an attribute more efficiently on the GPU.
  21956. *
  21957. * The idea is to create an instance of this class and provide it as an input
  21958. * to {@link StorageBufferNode}.
  21959. *
  21960. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21961. *
  21962. * @augments InstancedBufferAttribute
  21963. */
  21964. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  21965. /**
  21966. * Constructs a new storage instanced buffer attribute.
  21967. *
  21968. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21969. * The subsequent parameters are then obsolete.
  21970. * @param {number} itemSize - The item size.
  21971. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21972. */
  21973. constructor( count, itemSize, typeClass = Float32Array ) {
  21974. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21975. super( array, itemSize );
  21976. /**
  21977. * This flag can be used for type testing.
  21978. *
  21979. * @type {boolean}
  21980. * @readonly
  21981. * @default true
  21982. */
  21983. this.isStorageInstancedBufferAttribute = true;
  21984. }
  21985. }
  21986. /**
  21987. * This special type of buffer attribute is intended for compute shaders.
  21988. * In earlier three.js versions it was only possible to update attribute data
  21989. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21990. * new material system and renderer it is now possible to use compute shaders
  21991. * to compute the data for an attribute more efficiently on the GPU.
  21992. *
  21993. * The idea is to create an instance of this class and provide it as an input
  21994. * to {@link StorageBufferNode}.
  21995. *
  21996. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21997. *
  21998. * @augments BufferAttribute
  21999. */
  22000. class StorageBufferAttribute extends BufferAttribute {
  22001. /**
  22002. * Constructs a new storage buffer attribute.
  22003. *
  22004. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  22005. * The subsequent parameters are then obsolete.
  22006. * @param {number} itemSize - The item size.
  22007. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  22008. */
  22009. constructor( count, itemSize, typeClass = Float32Array ) {
  22010. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  22011. super( array, itemSize );
  22012. /**
  22013. * This flag can be used for type testing.
  22014. *
  22015. * @type {boolean}
  22016. * @readonly
  22017. * @default true
  22018. */
  22019. this.isStorageBufferAttribute = true;
  22020. }
  22021. }
  22022. /**
  22023. * This class enables element access on instances of {@link StorageBufferNode}.
  22024. * In most cases, it is indirectly used when accessing elements with the
  22025. * {@link StorageBufferNode#element} method.
  22026. *
  22027. * ```js
  22028. * const position = positionStorage.element( instanceIndex );
  22029. * ```
  22030. *
  22031. * @augments ArrayElementNode
  22032. */
  22033. class StorageArrayElementNode extends ArrayElementNode {
  22034. static get type() {
  22035. return 'StorageArrayElementNode';
  22036. }
  22037. /**
  22038. * Constructs storage buffer element node.
  22039. *
  22040. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  22041. * @param {Node} indexNode - The index node that defines the element access.
  22042. */
  22043. constructor( storageBufferNode, indexNode ) {
  22044. super( storageBufferNode, indexNode );
  22045. /**
  22046. * This flag can be used for type testing.
  22047. *
  22048. * @type {boolean}
  22049. * @readonly
  22050. * @default true
  22051. */
  22052. this.isStorageArrayElementNode = true;
  22053. }
  22054. /**
  22055. * The storage buffer node.
  22056. *
  22057. * @param {Node} value
  22058. * @type {StorageBufferNode}
  22059. */
  22060. set storageBufferNode( value ) {
  22061. this.node = value;
  22062. }
  22063. get storageBufferNode() {
  22064. return this.node;
  22065. }
  22066. getMemberType( builder, name ) {
  22067. const structTypeNode = this.storageBufferNode.structTypeNode;
  22068. if ( structTypeNode ) {
  22069. return structTypeNode.getMemberType( builder, name );
  22070. }
  22071. return 'void';
  22072. }
  22073. setup( builder ) {
  22074. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  22075. if ( this.node.isPBO === true ) {
  22076. builder.setupPBO( this.node );
  22077. }
  22078. }
  22079. return super.setup( builder );
  22080. }
  22081. generate( builder, output ) {
  22082. let snippet;
  22083. const isAssignContext = builder.context.assign;
  22084. //
  22085. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  22086. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  22087. snippet = builder.generatePBO( this );
  22088. } else {
  22089. snippet = this.node.build( builder );
  22090. }
  22091. } else {
  22092. snippet = super.generate( builder );
  22093. }
  22094. if ( isAssignContext !== true ) {
  22095. const type = this.getNodeType( builder );
  22096. snippet = builder.format( snippet, type, output );
  22097. }
  22098. return snippet;
  22099. }
  22100. }
  22101. /**
  22102. * TSL function for creating a storage element node.
  22103. *
  22104. * @tsl
  22105. * @function
  22106. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  22107. * @param {Node} indexNode - The index node that defines the element access.
  22108. * @returns {StorageArrayElementNode}
  22109. */
  22110. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  22111. /**
  22112. * This node is used in context of compute shaders and allows to define a
  22113. * storage buffer for data. A typical workflow is to create instances of
  22114. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  22115. * setup up a compute shader that writes into the buffers and then convert
  22116. * the storage buffers to attribute nodes for rendering.
  22117. *
  22118. * ```js
  22119. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  22120. *
  22121. * const computeInit = Fn( () => { // the compute shader
  22122. *
  22123. * const position = positionBuffer.element( instanceIndex );
  22124. *
  22125. * // compute position data
  22126. *
  22127. * position.x = 1;
  22128. * position.y = 1;
  22129. * position.z = 1;
  22130. *
  22131. * } )().compute( particleCount );
  22132. *
  22133. * const particleMaterial = new THREE.SpriteNodeMaterial();
  22134. * particleMaterial.positionNode = positionBuffer.toAttribute();
  22135. *
  22136. * renderer.computeAsync( computeInit );
  22137. *
  22138. * ```
  22139. *
  22140. * @augments BufferNode
  22141. */
  22142. class StorageBufferNode extends BufferNode {
  22143. static get type() {
  22144. return 'StorageBufferNode';
  22145. }
  22146. /**
  22147. * Constructs a new storage buffer node.
  22148. *
  22149. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  22150. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  22151. * @param {number} [bufferCount=0] - The buffer count.
  22152. */
  22153. constructor( value, bufferType = null, bufferCount = 0 ) {
  22154. let nodeType, structTypeNode = null;
  22155. if ( bufferType && bufferType.isStruct ) {
  22156. nodeType = 'struct';
  22157. structTypeNode = bufferType.layout;
  22158. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  22159. nodeType = getTypeFromLength( value.itemSize );
  22160. bufferCount = value.count;
  22161. } else {
  22162. nodeType = bufferType;
  22163. }
  22164. super( value, nodeType, bufferCount );
  22165. /**
  22166. * This flag can be used for type testing.
  22167. *
  22168. * @type {boolean}
  22169. * @readonly
  22170. * @default true
  22171. */
  22172. this.isStorageBufferNode = true;
  22173. /**
  22174. * The buffer struct type.
  22175. *
  22176. * @type {?StructTypeNode}
  22177. * @default null
  22178. */
  22179. this.structTypeNode = structTypeNode;
  22180. /**
  22181. * The access type of the texture node.
  22182. *
  22183. * @type {string}
  22184. * @default 'readWrite'
  22185. */
  22186. this.access = NodeAccess.READ_WRITE;
  22187. /**
  22188. * Whether the node is atomic or not.
  22189. *
  22190. * @type {boolean}
  22191. * @default false
  22192. */
  22193. this.isAtomic = false;
  22194. /**
  22195. * Whether the node represents a PBO or not.
  22196. * Only relevant for WebGL.
  22197. *
  22198. * @type {boolean}
  22199. * @default false
  22200. */
  22201. this.isPBO = false;
  22202. /**
  22203. * A reference to the internal buffer attribute node.
  22204. *
  22205. * @type {?BufferAttributeNode}
  22206. * @default null
  22207. */
  22208. this._attribute = null;
  22209. /**
  22210. * A reference to the internal varying node.
  22211. *
  22212. * @type {?VaryingNode}
  22213. * @default null
  22214. */
  22215. this._varying = null;
  22216. /**
  22217. * `StorageBufferNode` sets this property to `true` by default.
  22218. *
  22219. * @type {boolean}
  22220. * @default true
  22221. */
  22222. this.global = true;
  22223. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  22224. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  22225. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  22226. else value.isStorageBufferAttribute = true;
  22227. }
  22228. }
  22229. /**
  22230. * This method is overwritten since the buffer data might be shared
  22231. * and thus the hash should be shared as well.
  22232. *
  22233. * @param {NodeBuilder} builder - The current node builder.
  22234. * @return {string} The hash.
  22235. */
  22236. getHash( builder ) {
  22237. if ( this.bufferCount === 0 ) {
  22238. let bufferData = builder.globalCache.getData( this.value );
  22239. if ( bufferData === undefined ) {
  22240. bufferData = {
  22241. node: this
  22242. };
  22243. builder.globalCache.setData( this.value, bufferData );
  22244. }
  22245. return bufferData.node.uuid;
  22246. }
  22247. return this.uuid;
  22248. }
  22249. /**
  22250. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  22251. *
  22252. * @param {NodeBuilder} builder - The current node builder.
  22253. * @return {string} The input type.
  22254. */
  22255. getInputType( /*builder*/ ) {
  22256. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  22257. }
  22258. /**
  22259. * Enables element access with the given index node.
  22260. *
  22261. * @param {IndexNode} indexNode - The index node.
  22262. * @return {StorageArrayElementNode} A node representing the element access.
  22263. */
  22264. element( indexNode ) {
  22265. return storageElement( this, indexNode );
  22266. }
  22267. /**
  22268. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  22269. *
  22270. * @param {boolean} value - The value so set.
  22271. * @return {StorageBufferNode} A reference to this node.
  22272. */
  22273. setPBO( value ) {
  22274. this.isPBO = value;
  22275. return this;
  22276. }
  22277. /**
  22278. * Returns the `isPBO` value.
  22279. *
  22280. * @return {boolean} Whether the node represents a PBO or not.
  22281. */
  22282. getPBO() {
  22283. return this.isPBO;
  22284. }
  22285. /**
  22286. * Defines the node access.
  22287. *
  22288. * @param {string} value - The node access.
  22289. * @return {StorageBufferNode} A reference to this node.
  22290. */
  22291. setAccess( value ) {
  22292. this.access = value;
  22293. return this;
  22294. }
  22295. /**
  22296. * Convenience method for configuring a read-only node access.
  22297. *
  22298. * @return {StorageBufferNode} A reference to this node.
  22299. */
  22300. toReadOnly() {
  22301. return this.setAccess( NodeAccess.READ_ONLY );
  22302. }
  22303. /**
  22304. * Defines whether the node is atomic or not.
  22305. *
  22306. * @param {boolean} value - The atomic flag.
  22307. * @return {StorageBufferNode} A reference to this node.
  22308. */
  22309. setAtomic( value ) {
  22310. this.isAtomic = value;
  22311. return this;
  22312. }
  22313. /**
  22314. * Convenience method for making this node atomic.
  22315. *
  22316. * @return {StorageBufferNode} A reference to this node.
  22317. */
  22318. toAtomic() {
  22319. return this.setAtomic( true );
  22320. }
  22321. /**
  22322. * Returns attribute data for this storage buffer node.
  22323. *
  22324. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  22325. */
  22326. getAttributeData() {
  22327. if ( this._attribute === null ) {
  22328. this._attribute = bufferAttribute( this.value );
  22329. this._varying = varying( this._attribute );
  22330. }
  22331. return {
  22332. attribute: this._attribute,
  22333. varying: this._varying
  22334. };
  22335. }
  22336. /**
  22337. * This method is overwritten since the node type from the availability of storage buffers
  22338. * and the attribute data.
  22339. *
  22340. * @param {NodeBuilder} builder - The current node builder.
  22341. * @return {string} The node type.
  22342. */
  22343. getNodeType( builder ) {
  22344. if ( this.structTypeNode !== null ) {
  22345. return this.structTypeNode.getNodeType( builder );
  22346. }
  22347. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  22348. return super.getNodeType( builder );
  22349. }
  22350. const { attribute } = this.getAttributeData();
  22351. return attribute.getNodeType( builder );
  22352. }
  22353. /**
  22354. * Generates the code snippet of the storage buffer node.
  22355. *
  22356. * @param {NodeBuilder} builder - The current node builder.
  22357. * @return {string} The generated code snippet.
  22358. */
  22359. generate( builder ) {
  22360. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  22361. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  22362. return super.generate( builder );
  22363. }
  22364. const { attribute, varying } = this.getAttributeData();
  22365. const output = varying.build( builder );
  22366. builder.registerTransform( output, attribute );
  22367. return output;
  22368. }
  22369. }
  22370. /**
  22371. * TSL function for creating a storage buffer node.
  22372. *
  22373. * @tsl
  22374. * @function
  22375. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  22376. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  22377. * @param {number} [count=0] - The buffer count.
  22378. * @returns {StorageBufferNode}
  22379. */
  22380. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  22381. /**
  22382. * @tsl
  22383. * @function
  22384. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  22385. *
  22386. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  22387. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  22388. * @param {number} count - The buffer count.
  22389. * @returns {StorageBufferNode}
  22390. */
  22391. const storageObject = ( value, type, count ) => { // @deprecated, r171
  22392. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  22393. return storage( value, type, count ).setPBO( true );
  22394. };
  22395. /**
  22396. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  22397. *
  22398. * @tsl
  22399. * @function
  22400. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  22401. * @param {string|Struct} [type='float'] - The data type.
  22402. * @returns {StorageBufferNode}
  22403. */
  22404. const attributeArray = ( count, type = 'float' ) => {
  22405. let itemSize, typedArray;
  22406. if ( type.isStruct === true ) {
  22407. itemSize = type.layout.getLength();
  22408. typedArray = getTypedArrayFromType( 'float' );
  22409. } else {
  22410. itemSize = getLengthFromType( type );
  22411. typedArray = getTypedArrayFromType( type );
  22412. }
  22413. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  22414. const node = storage( buffer, type, count );
  22415. return node;
  22416. };
  22417. /**
  22418. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  22419. *
  22420. * @tsl
  22421. * @function
  22422. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  22423. * @param {string|Struct} [type='float'] - The data type.
  22424. * @returns {StorageBufferNode}
  22425. */
  22426. const instancedArray = ( count, type = 'float' ) => {
  22427. let itemSize, typedArray;
  22428. if ( type.isStruct === true ) {
  22429. itemSize = type.layout.getLength();
  22430. typedArray = getTypedArrayFromType( 'float' );
  22431. } else {
  22432. itemSize = getLengthFromType( type );
  22433. typedArray = getTypedArrayFromType( type );
  22434. }
  22435. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  22436. const node = storage( buffer, type, count );
  22437. return node;
  22438. };
  22439. /**
  22440. * An attribute node for representing vertex colors.
  22441. *
  22442. * @augments AttributeNode
  22443. */
  22444. class VertexColorNode extends AttributeNode {
  22445. static get type() {
  22446. return 'VertexColorNode';
  22447. }
  22448. /**
  22449. * Constructs a new vertex color node.
  22450. *
  22451. * @param {number} [index=0] - The attribute index.
  22452. */
  22453. constructor( index = 0 ) {
  22454. super( null, 'vec4' );
  22455. /**
  22456. * This flag can be used for type testing.
  22457. *
  22458. * @type {boolean}
  22459. * @readonly
  22460. * @default true
  22461. */
  22462. this.isVertexColorNode = true;
  22463. /**
  22464. * The attribute index to enable more than one sets of vertex colors.
  22465. *
  22466. * @type {number}
  22467. * @default 0
  22468. */
  22469. this.index = index;
  22470. }
  22471. /**
  22472. * Overwrites the default implementation by honoring the attribute index.
  22473. *
  22474. * @param {NodeBuilder} builder - The current node builder.
  22475. * @return {string} The attribute name.
  22476. */
  22477. getAttributeName( /*builder*/ ) {
  22478. const index = this.index;
  22479. return 'color' + ( index > 0 ? index : '' );
  22480. }
  22481. generate( builder ) {
  22482. const attributeName = this.getAttributeName( builder );
  22483. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  22484. let result;
  22485. if ( geometryAttribute === true ) {
  22486. result = super.generate( builder );
  22487. } else {
  22488. // Vertex color fallback should be white
  22489. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  22490. }
  22491. return result;
  22492. }
  22493. serialize( data ) {
  22494. super.serialize( data );
  22495. data.index = this.index;
  22496. }
  22497. deserialize( data ) {
  22498. super.deserialize( data );
  22499. this.index = data.index;
  22500. }
  22501. }
  22502. /**
  22503. * TSL function for creating a reference node.
  22504. *
  22505. * @tsl
  22506. * @function
  22507. * @param {number} index - The attribute index.
  22508. * @returns {VertexColorNode}
  22509. */
  22510. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  22511. /**
  22512. * A node for representing the uv coordinates of points.
  22513. *
  22514. * Can only be used with a WebGL backend. In WebGPU, point
  22515. * primitives always have the size of one pixel and can thus
  22516. * can't be used as sprite-like objects that display textures.
  22517. *
  22518. * @augments Node
  22519. */
  22520. class PointUVNode extends Node {
  22521. static get type() {
  22522. return 'PointUVNode';
  22523. }
  22524. /**
  22525. * Constructs a new point uv node.
  22526. */
  22527. constructor() {
  22528. super( 'vec2' );
  22529. /**
  22530. * This flag can be used for type testing.
  22531. *
  22532. * @type {boolean}
  22533. * @readonly
  22534. * @default true
  22535. */
  22536. this.isPointUVNode = true;
  22537. }
  22538. generate( /*builder*/ ) {
  22539. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  22540. }
  22541. }
  22542. /**
  22543. * TSL object that represents the uv coordinates of points.
  22544. *
  22545. * @tsl
  22546. * @type {PointUVNode}
  22547. */
  22548. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  22549. const _e1 = /*@__PURE__*/ new Euler();
  22550. const _m1 = /*@__PURE__*/ new Matrix4();
  22551. /**
  22552. * This module allows access to a collection of scene properties. The following predefined TSL objects
  22553. * are available for easier use:
  22554. *
  22555. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  22556. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  22557. * - `backgroundRotation`: A node that represents the scene's background rotation.
  22558. *
  22559. * @augments Node
  22560. */
  22561. class SceneNode extends Node {
  22562. static get type() {
  22563. return 'SceneNode';
  22564. }
  22565. /**
  22566. * Constructs a new scene node.
  22567. *
  22568. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  22569. * @param {?Scene} [scene=null] - A reference to the scene.
  22570. */
  22571. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  22572. super();
  22573. /**
  22574. * The scope defines the type of scene property that is accessed.
  22575. *
  22576. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  22577. */
  22578. this.scope = scope;
  22579. /**
  22580. * A reference to the scene that is going to be accessed.
  22581. *
  22582. * @type {?Scene}
  22583. * @default null
  22584. */
  22585. this.scene = scene;
  22586. }
  22587. /**
  22588. * Depending on the scope, the method returns a different type of node that represents
  22589. * the respective scene property.
  22590. *
  22591. * @param {NodeBuilder} builder - The current node builder.
  22592. * @return {Node} The output node.
  22593. */
  22594. setup( builder ) {
  22595. const scope = this.scope;
  22596. const scene = this.scene !== null ? this.scene : builder.scene;
  22597. let output;
  22598. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  22599. output = reference( 'backgroundBlurriness', 'float', scene );
  22600. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  22601. output = reference( 'backgroundIntensity', 'float', scene );
  22602. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  22603. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  22604. const background = scene.background;
  22605. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  22606. _e1.copy( scene.backgroundRotation );
  22607. // accommodate left-handed frame
  22608. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  22609. _m1.makeRotationFromEuler( _e1 );
  22610. } else {
  22611. _m1.identity();
  22612. }
  22613. return _m1;
  22614. } );
  22615. } else {
  22616. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  22617. }
  22618. return output;
  22619. }
  22620. }
  22621. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  22622. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  22623. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  22624. /**
  22625. * TSL object that represents the scene's background blurriness.
  22626. *
  22627. * @tsl
  22628. * @type {SceneNode}
  22629. */
  22630. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  22631. /**
  22632. * TSL object that represents the scene's background intensity.
  22633. *
  22634. * @tsl
  22635. * @type {SceneNode}
  22636. */
  22637. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  22638. /**
  22639. * TSL object that represents the scene's background rotation.
  22640. *
  22641. * @tsl
  22642. * @type {SceneNode}
  22643. */
  22644. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  22645. /**
  22646. * This special version of a texture node can be used to
  22647. * write data into a storage texture with a compute shader.
  22648. *
  22649. * ```js
  22650. * const storageTexture = new THREE.StorageTexture( width, height );
  22651. *
  22652. * const computeTexture = Fn( ( { storageTexture } ) => {
  22653. *
  22654. * const posX = instanceIndex.modInt( width );
  22655. * const posY = instanceIndex.div( width );
  22656. * const indexUV = uvec2( posX, posY );
  22657. *
  22658. * // generate RGB values
  22659. *
  22660. * const r = 1;
  22661. * const g = 1;
  22662. * const b = 1;
  22663. *
  22664. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  22665. *
  22666. * } );
  22667. *
  22668. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  22669. * renderer.computeAsync( computeNode );
  22670. * ```
  22671. *
  22672. * This node can only be used with a WebGPU backend.
  22673. *
  22674. * @augments TextureNode
  22675. */
  22676. class StorageTextureNode extends TextureNode {
  22677. static get type() {
  22678. return 'StorageTextureNode';
  22679. }
  22680. /**
  22681. * Constructs a new storage texture node.
  22682. *
  22683. * @param {StorageTexture} value - The storage texture.
  22684. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22685. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22686. */
  22687. constructor( value, uvNode, storeNode = null ) {
  22688. super( value, uvNode );
  22689. /**
  22690. * The value node that should be stored in the texture.
  22691. *
  22692. * @type {?Node}
  22693. * @default null
  22694. */
  22695. this.storeNode = storeNode;
  22696. /**
  22697. * This flag can be used for type testing.
  22698. *
  22699. * @type {boolean}
  22700. * @readonly
  22701. * @default true
  22702. */
  22703. this.isStorageTextureNode = true;
  22704. /**
  22705. * The access type of the texture node.
  22706. *
  22707. * @type {string}
  22708. * @default 'writeOnly'
  22709. */
  22710. this.access = NodeAccess.WRITE_ONLY;
  22711. }
  22712. /**
  22713. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  22714. *
  22715. * @param {NodeBuilder} builder - The current node builder.
  22716. * @return {string} The input type.
  22717. */
  22718. getInputType( /*builder*/ ) {
  22719. return 'storageTexture';
  22720. }
  22721. setup( builder ) {
  22722. super.setup( builder );
  22723. const properties = builder.getNodeProperties( this );
  22724. properties.storeNode = this.storeNode;
  22725. }
  22726. /**
  22727. * Defines the node access.
  22728. *
  22729. * @param {string} value - The node access.
  22730. * @return {StorageTextureNode} A reference to this node.
  22731. */
  22732. setAccess( value ) {
  22733. this.access = value;
  22734. return this;
  22735. }
  22736. /**
  22737. * Generates the code snippet of the storage node. If no `storeNode`
  22738. * is defined, the texture node is generated as normal texture.
  22739. *
  22740. * @param {NodeBuilder} builder - The current node builder.
  22741. * @param {string} output - The current output.
  22742. * @return {string} The generated code snippet.
  22743. */
  22744. generate( builder, output ) {
  22745. let snippet;
  22746. if ( this.storeNode !== null ) {
  22747. snippet = this.generateStore( builder );
  22748. } else {
  22749. snippet = super.generate( builder, output );
  22750. }
  22751. return snippet;
  22752. }
  22753. /**
  22754. * Convenience method for configuring a read/write node access.
  22755. *
  22756. * @return {StorageTextureNode} A reference to this node.
  22757. */
  22758. toReadWrite() {
  22759. return this.setAccess( NodeAccess.READ_WRITE );
  22760. }
  22761. /**
  22762. * Convenience method for configuring a read-only node access.
  22763. *
  22764. * @return {StorageTextureNode} A reference to this node.
  22765. */
  22766. toReadOnly() {
  22767. return this.setAccess( NodeAccess.READ_ONLY );
  22768. }
  22769. /**
  22770. * Convenience method for configuring a write-only node access.
  22771. *
  22772. * @return {StorageTextureNode} A reference to this node.
  22773. */
  22774. toWriteOnly() {
  22775. return this.setAccess( NodeAccess.WRITE_ONLY );
  22776. }
  22777. /**
  22778. * Generates the code snippet of the storage texture node.
  22779. *
  22780. * @param {NodeBuilder} builder - The current node builder.
  22781. */
  22782. generateStore( builder ) {
  22783. const properties = builder.getNodeProperties( this );
  22784. const { uvNode, storeNode } = properties;
  22785. const textureProperty = super.generate( builder, 'property' );
  22786. const uvSnippet = uvNode.build( builder, 'uvec2' );
  22787. const storeSnippet = storeNode.build( builder, 'vec4' );
  22788. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  22789. builder.addLineFlowCode( snippet, this );
  22790. }
  22791. }
  22792. /**
  22793. * TSL function for creating a storage texture node.
  22794. *
  22795. * @tsl
  22796. * @function
  22797. * @param {StorageTexture} value - The storage texture.
  22798. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22799. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22800. * @returns {StorageTextureNode}
  22801. */
  22802. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  22803. /**
  22804. * TODO: Explain difference to `storageTexture()`.
  22805. *
  22806. * @tsl
  22807. * @function
  22808. * @param {StorageTexture} value - The storage texture.
  22809. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22810. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22811. * @returns {StorageTextureNode}
  22812. */
  22813. const textureStore = ( value, uvNode, storeNode ) => {
  22814. const node = storageTexture( value, uvNode, storeNode );
  22815. if ( storeNode !== null ) node.append();
  22816. return node;
  22817. };
  22818. const normal = Fn( ( { texture, uv } ) => {
  22819. const epsilon = 0.0001;
  22820. const ret = vec3().toVar();
  22821. If( uv.x.lessThan( epsilon ), () => {
  22822. ret.assign( vec3( 1, 0, 0 ) );
  22823. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  22824. ret.assign( vec3( 0, 1, 0 ) );
  22825. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  22826. ret.assign( vec3( 0, 0, 1 ) );
  22827. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  22828. ret.assign( vec3( - 1, 0, 0 ) );
  22829. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  22830. ret.assign( vec3( 0, - 1, 0 ) );
  22831. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  22832. ret.assign( vec3( 0, 0, - 1 ) );
  22833. } ).Else( () => {
  22834. const step = 0.01;
  22835. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  22836. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  22837. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  22838. ret.assign( vec3( x, y, z ) );
  22839. } );
  22840. return ret.normalize();
  22841. } );
  22842. /**
  22843. * This type of uniform node represents a 3D texture.
  22844. *
  22845. * @augments TextureNode
  22846. */
  22847. class Texture3DNode extends TextureNode {
  22848. static get type() {
  22849. return 'Texture3DNode';
  22850. }
  22851. /**
  22852. * Constructs a new 3D texture node.
  22853. *
  22854. * @param {Data3DTexture} value - The 3D texture.
  22855. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  22856. * @param {?Node<int>} [levelNode=null] - The level node.
  22857. */
  22858. constructor( value, uvNode = null, levelNode = null ) {
  22859. super( value, uvNode, levelNode );
  22860. /**
  22861. * This flag can be used for type testing.
  22862. *
  22863. * @type {boolean}
  22864. * @readonly
  22865. * @default true
  22866. */
  22867. this.isTexture3DNode = true;
  22868. }
  22869. /**
  22870. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  22871. *
  22872. * @param {NodeBuilder} builder - The current node builder.
  22873. * @return {string} The input type.
  22874. */
  22875. getInputType( /*builder*/ ) {
  22876. return 'texture3D';
  22877. }
  22878. /**
  22879. * Returns a default uv node which is in context of 3D textures a three-dimensional
  22880. * uv node.
  22881. *
  22882. * @return {Node<vec3>} The default uv node.
  22883. */
  22884. getDefaultUV() {
  22885. return vec3( 0.5, 0.5, 0.5 );
  22886. }
  22887. /**
  22888. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  22889. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  22890. *
  22891. * @param {boolean} value - The update toggle.
  22892. */
  22893. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  22894. /**
  22895. * Overwrites the default implementation to return the unmodified uv node.
  22896. *
  22897. * @param {NodeBuilder} builder - The current node builder.
  22898. * @param {Node} uvNode - The uv node to setup.
  22899. * @return {Node} The unmodified uv node.
  22900. */
  22901. setupUV( builder, uvNode ) {
  22902. const texture = this.value;
  22903. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  22904. if ( this.sampler ) {
  22905. uvNode = uvNode.flipY();
  22906. } else {
  22907. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  22908. }
  22909. }
  22910. return uvNode;
  22911. }
  22912. /**
  22913. * Generates the uv code snippet.
  22914. *
  22915. * @param {NodeBuilder} builder - The current node builder.
  22916. * @param {Node} uvNode - The uv node to generate code for.
  22917. * @return {string} The generated code snippet.
  22918. */
  22919. generateUV( builder, uvNode ) {
  22920. return uvNode.build( builder, 'vec3' );
  22921. }
  22922. /**
  22923. * TODO.
  22924. *
  22925. * @param {Node<vec3>} uvNode - The uv node .
  22926. * @return {Node<vec3>} TODO.
  22927. */
  22928. normal( uvNode ) {
  22929. return normal( { texture: this, uv: uvNode } );
  22930. }
  22931. }
  22932. /**
  22933. * TSL function for creating a 3D texture node.
  22934. *
  22935. * @tsl
  22936. * @function
  22937. * @param {Data3DTexture} value - The 3D texture.
  22938. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  22939. * @param {?Node<int>} [levelNode=null] - The level node.
  22940. * @returns {Texture3DNode}
  22941. */
  22942. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  22943. /**
  22944. * A special type of reference node that allows to link values in
  22945. * `userData` fields to node objects.
  22946. * ```js
  22947. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  22948. *
  22949. * const material = new THREE.SpriteNodeMaterial();
  22950. * material.rotationNode = userData( 'rotation', 'float' );
  22951. * ```
  22952. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  22953. * will automatically be updated when the `rotation` user data field changes.
  22954. *
  22955. * @augments ReferenceNode
  22956. */
  22957. class UserDataNode extends ReferenceNode {
  22958. static get type() {
  22959. return 'UserDataNode';
  22960. }
  22961. /**
  22962. * Constructs a new user data node.
  22963. *
  22964. * @param {string} property - The property name that should be referenced by the node.
  22965. * @param {string} inputType - The node data type of the reference.
  22966. * @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.
  22967. */
  22968. constructor( property, inputType, userData = null ) {
  22969. super( property, inputType, userData );
  22970. /**
  22971. * A reference to the `userData` object. If not provided, the `userData`
  22972. * property of the 3D object that uses the node material is evaluated.
  22973. *
  22974. * @type {?Object}
  22975. * @default null
  22976. */
  22977. this.userData = userData;
  22978. }
  22979. /**
  22980. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  22981. * `userData` field.
  22982. *
  22983. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  22984. * @return {Object} A reference to the `userData` field.
  22985. */
  22986. updateReference( state ) {
  22987. this.reference = this.userData !== null ? this.userData : state.object.userData;
  22988. return this.reference;
  22989. }
  22990. }
  22991. /**
  22992. * TSL function for creating a user data node.
  22993. *
  22994. * @tsl
  22995. * @function
  22996. * @param {string} name - The property name that should be referenced by the node.
  22997. * @param {string} inputType - The node data type of the reference.
  22998. * @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.
  22999. * @returns {UserDataNode}
  23000. */
  23001. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  23002. const _objectData = new WeakMap();
  23003. /**
  23004. * A node for representing motion or velocity vectors. Foundation
  23005. * for advanced post processing effects like motion blur or TRAA.
  23006. *
  23007. * The node keeps track of the model, view and projection matrices
  23008. * of the previous frame and uses them to compute offsets in NDC space.
  23009. * These offsets represent the final velocity.
  23010. *
  23011. * @augments TempNode
  23012. */
  23013. class VelocityNode extends TempNode {
  23014. static get type() {
  23015. return 'VelocityNode';
  23016. }
  23017. /**
  23018. * Constructs a new vertex color node.
  23019. */
  23020. constructor() {
  23021. super( 'vec2' );
  23022. /**
  23023. * The current projection matrix.
  23024. *
  23025. * @type {?Matrix4}
  23026. * @default null
  23027. */
  23028. this.projectionMatrix = null;
  23029. /**
  23030. * Overwritten since velocity nodes are updated per object.
  23031. *
  23032. * @type {string}
  23033. * @default 'object'
  23034. */
  23035. this.updateType = NodeUpdateType.OBJECT;
  23036. /**
  23037. * Overwritten since velocity nodes save data after the update.
  23038. *
  23039. * @type {string}
  23040. * @default 'object'
  23041. */
  23042. this.updateAfterType = NodeUpdateType.OBJECT;
  23043. /**
  23044. * Uniform node representing the previous model matrix in world space.
  23045. *
  23046. * @type {UniformNode<mat4>}
  23047. * @default null
  23048. */
  23049. this.previousModelWorldMatrix = uniform( new Matrix4() );
  23050. /**
  23051. * Uniform node representing the previous projection matrix.
  23052. *
  23053. * @type {UniformNode<mat4>}
  23054. * @default null
  23055. */
  23056. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  23057. /**
  23058. * Uniform node representing the previous view matrix.
  23059. *
  23060. * @type {UniformNode<mat4>}
  23061. * @default null
  23062. */
  23063. this.previousCameraViewMatrix = uniform( new Matrix4() );
  23064. }
  23065. /**
  23066. * Sets the given projection matrix.
  23067. *
  23068. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  23069. */
  23070. setProjectionMatrix( projectionMatrix ) {
  23071. this.projectionMatrix = projectionMatrix;
  23072. }
  23073. /**
  23074. * Updates velocity specific uniforms.
  23075. *
  23076. * @param {NodeFrame} frame - A reference to the current node frame.
  23077. */
  23078. update( { frameId, camera, object } ) {
  23079. const previousModelMatrix = getPreviousMatrix( object );
  23080. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  23081. //
  23082. const cameraData = getData( camera );
  23083. if ( cameraData.frameId !== frameId ) {
  23084. cameraData.frameId = frameId;
  23085. if ( cameraData.previousProjectionMatrix === undefined ) {
  23086. cameraData.previousProjectionMatrix = new Matrix4();
  23087. cameraData.previousCameraViewMatrix = new Matrix4();
  23088. cameraData.currentProjectionMatrix = new Matrix4();
  23089. cameraData.currentCameraViewMatrix = new Matrix4();
  23090. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23091. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  23092. } else {
  23093. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  23094. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  23095. }
  23096. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23097. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  23098. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  23099. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  23100. }
  23101. }
  23102. /**
  23103. * Overwritten to updated velocity specific uniforms.
  23104. *
  23105. * @param {NodeFrame} frame - A reference to the current node frame.
  23106. */
  23107. updateAfter( { object } ) {
  23108. getPreviousMatrix( object ).copy( object.matrixWorld );
  23109. }
  23110. /**
  23111. * Implements the velocity computation based on the previous and current vertex data.
  23112. *
  23113. * @param {NodeBuilder} builder - A reference to the current node builder.
  23114. * @return {Node<vec2>} The motion vector.
  23115. */
  23116. setup( /*builder*/ ) {
  23117. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  23118. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  23119. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23120. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  23121. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  23122. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  23123. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  23124. return velocity;
  23125. }
  23126. }
  23127. function getData( object ) {
  23128. let objectData = _objectData.get( object );
  23129. if ( objectData === undefined ) {
  23130. objectData = {};
  23131. _objectData.set( object, objectData );
  23132. }
  23133. return objectData;
  23134. }
  23135. function getPreviousMatrix( object, index = 0 ) {
  23136. const objectData = getData( object );
  23137. let matrix = objectData[ index ];
  23138. if ( matrix === undefined ) {
  23139. objectData[ index ] = matrix = new Matrix4();
  23140. }
  23141. return matrix;
  23142. }
  23143. /**
  23144. * TSL object that represents the velocity of a render pass.
  23145. *
  23146. * @tsl
  23147. * @type {VelocityNode}
  23148. */
  23149. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  23150. /**
  23151. * Represents a "Color Burn" blend mode.
  23152. *
  23153. * It's designed to darken the base layer's colors based on the color of the blend layer.
  23154. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  23155. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  23156. *
  23157. * @tsl
  23158. * @function
  23159. * @param {Node<vec3>} base - The base color.
  23160. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  23161. * @return {Node<vec3>} The result.
  23162. */
  23163. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23164. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  23165. } ).setLayout( {
  23166. name: 'blendBurn',
  23167. type: 'vec3',
  23168. inputs: [
  23169. { name: 'base', type: 'vec3' },
  23170. { name: 'blend', type: 'vec3' }
  23171. ]
  23172. } );
  23173. /**
  23174. * Represents a "Color Dodge" blend mode.
  23175. *
  23176. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  23177. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  23178. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  23179. *
  23180. * @tsl
  23181. * @function
  23182. * @param {Node<vec3>} base - The base color.
  23183. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23184. * @return {Node<vec3>} The result.
  23185. */
  23186. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23187. return min$1( base.div( blend.oneMinus() ), 1.0 );
  23188. } ).setLayout( {
  23189. name: 'blendDodge',
  23190. type: 'vec3',
  23191. inputs: [
  23192. { name: 'base', type: 'vec3' },
  23193. { name: 'blend', type: 'vec3' }
  23194. ]
  23195. } );
  23196. /**
  23197. * Represents a "Screen" blend mode.
  23198. *
  23199. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  23200. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  23201. * effects.
  23202. *
  23203. * @tsl
  23204. * @function
  23205. * @param {Node<vec3>} base - The base color.
  23206. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23207. * @return {Node<vec3>} The result.
  23208. */
  23209. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23210. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  23211. } ).setLayout( {
  23212. name: 'blendScreen',
  23213. type: 'vec3',
  23214. inputs: [
  23215. { name: 'base', type: 'vec3' },
  23216. { name: 'blend', type: 'vec3' }
  23217. ]
  23218. } );
  23219. /**
  23220. * Represents a "Overlay" blend mode.
  23221. *
  23222. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  23223. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  23224. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  23225. *
  23226. * @tsl
  23227. * @function
  23228. * @param {Node<vec3>} base - The base color.
  23229. * @param {Node<vec3>} blend - The blend color
  23230. * @return {Node<vec3>} The result.
  23231. */
  23232. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23233. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  23234. } ).setLayout( {
  23235. name: 'blendOverlay',
  23236. type: 'vec3',
  23237. inputs: [
  23238. { name: 'base', type: 'vec3' },
  23239. { name: 'blend', type: 'vec3' }
  23240. ]
  23241. } );
  23242. /**
  23243. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  23244. * It assumes both input colors have non-premultiplied alpha.
  23245. *
  23246. * @tsl
  23247. * @function
  23248. * @param {Node<vec4>} base - The base color.
  23249. * @param {Node<vec4>} blend - The blend color
  23250. * @return {Node<vec4>} The result.
  23251. */
  23252. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23253. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  23254. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  23255. } ).setLayout( {
  23256. name: 'blendColor',
  23257. type: 'vec4',
  23258. inputs: [
  23259. { name: 'base', type: 'vec4' },
  23260. { name: 'blend', type: 'vec4' }
  23261. ]
  23262. } );
  23263. // Deprecated
  23264. /**
  23265. * @tsl
  23266. * @function
  23267. * @deprecated since r171. Use {@link blendBurn} instead.
  23268. *
  23269. * @param {...any} params
  23270. * @returns {Function}
  23271. */
  23272. const burn = ( ...params ) => { // @deprecated, r171
  23273. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  23274. return blendBurn( params );
  23275. };
  23276. /**
  23277. * @tsl
  23278. * @function
  23279. * @deprecated since r171. Use {@link blendDodge} instead.
  23280. *
  23281. * @param {...any} params
  23282. * @returns {Function}
  23283. */
  23284. const dodge = ( ...params ) => { // @deprecated, r171
  23285. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  23286. return blendDodge( params );
  23287. };
  23288. /**
  23289. * @tsl
  23290. * @function
  23291. * @deprecated since r171. Use {@link blendScreen} instead.
  23292. *
  23293. * @param {...any} params
  23294. * @returns {Function}
  23295. */
  23296. const screen = ( ...params ) => { // @deprecated, r171
  23297. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  23298. return blendScreen( params );
  23299. };
  23300. /**
  23301. * @tsl
  23302. * @function
  23303. * @deprecated since r171. Use {@link blendOverlay} instead.
  23304. *
  23305. * @param {...any} params
  23306. * @returns {Function}
  23307. */
  23308. const overlay = ( ...params ) => { // @deprecated, r171
  23309. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  23310. return blendOverlay( params );
  23311. };
  23312. /**
  23313. * Computes a grayscale value for the given RGB color value.
  23314. *
  23315. * @tsl
  23316. * @function
  23317. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  23318. * @return {Node<vec3>} The grayscale color.
  23319. */
  23320. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23321. return luminance( color.rgb );
  23322. } );
  23323. /**
  23324. * Super-saturates or desaturates the given RGB color.
  23325. *
  23326. * @tsl
  23327. * @function
  23328. * @param {Node<vec3>} color - The input color.
  23329. * @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.
  23330. * @return {Node<vec3>} The saturated color.
  23331. */
  23332. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23333. return adjustment.mix( luminance( color.rgb ), color.rgb );
  23334. } );
  23335. /**
  23336. * Selectively enhance the intensity of less saturated RGB colors. Can result
  23337. * in a more natural and visually appealing image with enhanced color depth
  23338. * compared to {@link ColorAdjustment#saturation}.
  23339. *
  23340. * @tsl
  23341. * @function
  23342. * @param {Node<vec3>} color - The input color.
  23343. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  23344. * @return {Node<vec3>} The updated color.
  23345. */
  23346. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23347. const average = add( color.r, color.g, color.b ).div( 3.0 );
  23348. const mx = color.r.max( color.g.max( color.b ) );
  23349. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  23350. return mix( color.rgb, mx, amt );
  23351. } );
  23352. /**
  23353. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  23354. *
  23355. * @tsl
  23356. * @function
  23357. * @param {Node<vec3>} color - The input color.
  23358. * @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.
  23359. * @return {Node<vec3>} The updated color.
  23360. */
  23361. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23362. const k = vec3( 0.57735, 0.57735, 0.57735 );
  23363. const cosAngle = adjustment.cos();
  23364. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  23365. } );
  23366. /**
  23367. * Computes the luminance for the given RGB color value.
  23368. *
  23369. * @tsl
  23370. * @function
  23371. * @param {Node<vec3>} color - The color value to compute the luminance for.
  23372. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  23373. * @return {Node<vec3>} The luminance.
  23374. */
  23375. const luminance = (
  23376. color,
  23377. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  23378. ) => dot( color, luminanceCoefficients );
  23379. /**
  23380. * Color Decision List (CDL) v1.2
  23381. *
  23382. * Compact representation of color grading information, defined by slope, offset, power, and
  23383. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  23384. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  23385. *
  23386. * @tsl
  23387. * @function
  23388. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  23389. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  23390. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  23391. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  23392. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  23393. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  23394. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  23395. *
  23396. * References:
  23397. * - ASC CDL v1.2
  23398. * - {@link https://blender.stackexchange.com/a/55239/43930}
  23399. * - {@link https://docs.acescentral.com/specifications/acescc/}
  23400. */
  23401. const cdl = /*@__PURE__*/ Fn( ( [
  23402. color,
  23403. slope = vec3( 1 ),
  23404. offset = vec3( 0 ),
  23405. power = vec3( 1 ),
  23406. saturation = float( 1 ),
  23407. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  23408. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  23409. ] ) => {
  23410. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  23411. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  23412. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  23413. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  23414. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  23415. const pv = v.pow( power ).toVar();
  23416. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  23417. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  23418. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  23419. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  23420. return vec4( v.rgb, color.a );
  23421. } );
  23422. /**
  23423. * Represents a posterize effect which reduces the number of colors
  23424. * in an image, resulting in a more blocky and stylized appearance.
  23425. *
  23426. * @augments TempNode
  23427. */
  23428. class PosterizeNode extends TempNode {
  23429. static get type() {
  23430. return 'PosterizeNode';
  23431. }
  23432. /**
  23433. * Constructs a new posterize node.
  23434. *
  23435. * @param {Node} sourceNode - The input color.
  23436. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23437. */
  23438. constructor( sourceNode, stepsNode ) {
  23439. super();
  23440. /**
  23441. * The input color.
  23442. *
  23443. * @type {Node}
  23444. */
  23445. this.sourceNode = sourceNode;
  23446. /**
  23447. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23448. *
  23449. * @type {Node}
  23450. */
  23451. this.stepsNode = stepsNode;
  23452. }
  23453. setup() {
  23454. const { sourceNode, stepsNode } = this;
  23455. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  23456. }
  23457. }
  23458. /**
  23459. * TSL function for creating a posterize node.
  23460. *
  23461. * @tsl
  23462. * @function
  23463. * @param {Node} sourceNode - The input color.
  23464. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23465. * @returns {PosterizeNode}
  23466. */
  23467. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  23468. const _size = /*@__PURE__*/ new Vector2();
  23469. /**
  23470. * Represents the texture of a pass node.
  23471. *
  23472. * @augments TextureNode
  23473. */
  23474. class PassTextureNode extends TextureNode {
  23475. static get type() {
  23476. return 'PassTextureNode';
  23477. }
  23478. /**
  23479. * Constructs a new pass texture node.
  23480. *
  23481. * @param {PassNode} passNode - The pass node.
  23482. * @param {Texture} texture - The output texture.
  23483. */
  23484. constructor( passNode, texture ) {
  23485. super( texture );
  23486. /**
  23487. * A reference to the pass node.
  23488. *
  23489. * @type {PassNode}
  23490. */
  23491. this.passNode = passNode;
  23492. this.setUpdateMatrix( false );
  23493. }
  23494. setup( builder ) {
  23495. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  23496. return super.setup( builder );
  23497. }
  23498. clone() {
  23499. return new this.constructor( this.passNode, this.value );
  23500. }
  23501. }
  23502. /**
  23503. * An extension of `PassTextureNode` which allows to manage more than one
  23504. * internal texture. Relevant for the `getPreviousTexture()` related API.
  23505. *
  23506. * @augments PassTextureNode
  23507. */
  23508. class PassMultipleTextureNode extends PassTextureNode {
  23509. static get type() {
  23510. return 'PassMultipleTextureNode';
  23511. }
  23512. /**
  23513. * Constructs a new pass texture node.
  23514. *
  23515. * @param {PassNode} passNode - The pass node.
  23516. * @param {string} textureName - The output texture name.
  23517. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  23518. */
  23519. constructor( passNode, textureName, previousTexture = false ) {
  23520. // null is passed to the super call since this class does not
  23521. // use an external texture for rendering pass data into. Instead
  23522. // the texture is managed by the pass node itself
  23523. super( passNode, null );
  23524. /**
  23525. * The output texture name.
  23526. *
  23527. * @type {string}
  23528. */
  23529. this.textureName = textureName;
  23530. /**
  23531. * Whether previous frame data should be used or not.
  23532. *
  23533. * @type {boolean}
  23534. */
  23535. this.previousTexture = previousTexture;
  23536. }
  23537. /**
  23538. * Updates the texture reference of this node.
  23539. */
  23540. updateTexture() {
  23541. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  23542. }
  23543. setup( builder ) {
  23544. this.updateTexture();
  23545. return super.setup( builder );
  23546. }
  23547. clone() {
  23548. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  23549. }
  23550. }
  23551. /**
  23552. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  23553. * This pass produces a render for the given scene and camera and can provide multiple outputs
  23554. * via MRT for further processing.
  23555. *
  23556. * ```js
  23557. * const postProcessing = new PostProcessing( renderer );
  23558. *
  23559. * const scenePass = pass( scene, camera );
  23560. *
  23561. * postProcessing.outputNode = scenePass;
  23562. * ```
  23563. *
  23564. * @augments TempNode
  23565. */
  23566. class PassNode extends TempNode {
  23567. static get type() {
  23568. return 'PassNode';
  23569. }
  23570. /**
  23571. * Constructs a new pass node.
  23572. *
  23573. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  23574. * @param {Scene} scene - A reference to the scene.
  23575. * @param {Camera} camera - A reference to the camera.
  23576. * @param {Object} options - Options for the internal render target.
  23577. */
  23578. constructor( scope, scene, camera, options = {} ) {
  23579. super( 'vec4' );
  23580. /**
  23581. * The scope of the pass. The scope determines whether the node outputs color or depth.
  23582. *
  23583. * @type {('color'|'depth')}
  23584. */
  23585. this.scope = scope;
  23586. /**
  23587. * A reference to the scene.
  23588. *
  23589. * @type {Scene}
  23590. */
  23591. this.scene = scene;
  23592. /**
  23593. * A reference to the camera.
  23594. *
  23595. * @type {Camera}
  23596. */
  23597. this.camera = camera;
  23598. /**
  23599. * Options for the internal render target.
  23600. *
  23601. * @type {Object}
  23602. */
  23603. this.options = options;
  23604. /**
  23605. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  23606. *
  23607. * @private
  23608. * @type {number}
  23609. * @default 1
  23610. */
  23611. this._pixelRatio = 1;
  23612. /**
  23613. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  23614. * @private
  23615. * @type {number}
  23616. * @default 1
  23617. */
  23618. this._width = 1;
  23619. /**
  23620. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  23621. * @private
  23622. * @type {number}
  23623. * @default 1
  23624. */
  23625. this._height = 1;
  23626. const depthTexture = new DepthTexture();
  23627. depthTexture.isRenderTargetTexture = true;
  23628. //depthTexture.type = FloatType;
  23629. depthTexture.name = 'depth';
  23630. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  23631. renderTarget.texture.name = 'output';
  23632. renderTarget.depthTexture = depthTexture;
  23633. /**
  23634. * The pass's render target.
  23635. *
  23636. * @type {RenderTarget}
  23637. */
  23638. this.renderTarget = renderTarget;
  23639. /**
  23640. * A dictionary holding the internal result textures.
  23641. *
  23642. * @private
  23643. * @type {Object<string, Texture>}
  23644. */
  23645. this._textures = {
  23646. output: renderTarget.texture,
  23647. depth: depthTexture
  23648. };
  23649. /**
  23650. * A dictionary holding the internal texture nodes.
  23651. *
  23652. * @private
  23653. * @type {Object<string, TextureNode>}
  23654. */
  23655. this._textureNodes = {};
  23656. /**
  23657. * A dictionary holding the internal depth nodes.
  23658. *
  23659. * @private
  23660. * @type {Object}
  23661. */
  23662. this._linearDepthNodes = {};
  23663. /**
  23664. * A dictionary holding the internal viewZ nodes.
  23665. *
  23666. * @private
  23667. * @type {Object}
  23668. */
  23669. this._viewZNodes = {};
  23670. /**
  23671. * A dictionary holding the texture data of the previous frame.
  23672. * Used for computing velocity/motion vectors.
  23673. *
  23674. * @private
  23675. * @type {Object<string, Texture>}
  23676. */
  23677. this._previousTextures = {};
  23678. /**
  23679. * A dictionary holding the texture nodes of the previous frame.
  23680. * Used for computing velocity/motion vectors.
  23681. *
  23682. * @private
  23683. * @type {Object<string, TextureNode>}
  23684. */
  23685. this._previousTextureNodes = {};
  23686. /**
  23687. * The `near` property of the camera as a uniform.
  23688. *
  23689. * @private
  23690. * @type {UniformNode}
  23691. */
  23692. this._cameraNear = uniform( 0 );
  23693. /**
  23694. * The `far` property of the camera as a uniform.
  23695. *
  23696. * @private
  23697. * @type {UniformNode}
  23698. */
  23699. this._cameraFar = uniform( 0 );
  23700. /**
  23701. * A MRT node configuring the MRT settings.
  23702. *
  23703. * @private
  23704. * @type {?MRTNode}
  23705. * @default null
  23706. */
  23707. this._mrt = null;
  23708. this._layers = null;
  23709. this._resolution = 1;
  23710. /**
  23711. * This flag can be used for type testing.
  23712. *
  23713. * @type {boolean}
  23714. * @readonly
  23715. * @default true
  23716. */
  23717. this.isPassNode = true;
  23718. /**
  23719. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  23720. * scene once per frame in its {@link PassNode#updateBefore} method.
  23721. *
  23722. * @type {string}
  23723. * @default 'frame'
  23724. */
  23725. this.updateBeforeType = NodeUpdateType.FRAME;
  23726. }
  23727. /**
  23728. * Sets the resolution for the pass.
  23729. * The resolution is a factor that is multiplied with the renderer's width and height.
  23730. *
  23731. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  23732. * @return {PassNode} A reference to this pass.
  23733. */
  23734. setResolution( resolution ) {
  23735. this._resolution = resolution;
  23736. return this;
  23737. }
  23738. /**
  23739. * Gets the current resolution of the pass.
  23740. *
  23741. * @return {number} The current resolution. A value of `1` means full resolution.
  23742. * @default 1
  23743. */
  23744. getResolution() {
  23745. return this._resolution;
  23746. }
  23747. setLayers( layers ) {
  23748. this._layers = layers;
  23749. return this;
  23750. }
  23751. getLayers() {
  23752. return this._layers;
  23753. }
  23754. /**
  23755. * Sets the given MRT node to setup MRT for this pass.
  23756. *
  23757. * @param {MRTNode} mrt - The MRT object.
  23758. * @return {PassNode} A reference to this pass.
  23759. */
  23760. setMRT( mrt ) {
  23761. this._mrt = mrt;
  23762. return this;
  23763. }
  23764. /**
  23765. * Returns the current MRT node.
  23766. *
  23767. * @return {MRTNode} The current MRT node.
  23768. */
  23769. getMRT() {
  23770. return this._mrt;
  23771. }
  23772. /**
  23773. * The method is overwritten so it always returns `true`.
  23774. *
  23775. * @return {boolean} Whether this node is global or not.
  23776. */
  23777. isGlobal() {
  23778. return true;
  23779. }
  23780. /**
  23781. * Returns the texture for the given output name.
  23782. *
  23783. * @param {string} name - The output name to get the texture for.
  23784. * @return {Texture} The texture.
  23785. */
  23786. getTexture( name ) {
  23787. let texture = this._textures[ name ];
  23788. if ( texture === undefined ) {
  23789. const refTexture = this.renderTarget.texture;
  23790. texture = refTexture.clone();
  23791. texture.name = name;
  23792. this._textures[ name ] = texture;
  23793. this.renderTarget.textures.push( texture );
  23794. }
  23795. return texture;
  23796. }
  23797. /**
  23798. * Returns the texture holding the data of the previous frame for the given output name.
  23799. *
  23800. * @param {string} name - The output name to get the texture for.
  23801. * @return {Texture} The texture holding the data of the previous frame.
  23802. */
  23803. getPreviousTexture( name ) {
  23804. let texture = this._previousTextures[ name ];
  23805. if ( texture === undefined ) {
  23806. texture = this.getTexture( name ).clone();
  23807. this._previousTextures[ name ] = texture;
  23808. }
  23809. return texture;
  23810. }
  23811. /**
  23812. * Switches current and previous textures for the given output name.
  23813. *
  23814. * @param {string} name - The output name.
  23815. */
  23816. toggleTexture( name ) {
  23817. const prevTexture = this._previousTextures[ name ];
  23818. if ( prevTexture !== undefined ) {
  23819. const texture = this._textures[ name ];
  23820. const index = this.renderTarget.textures.indexOf( texture );
  23821. this.renderTarget.textures[ index ] = prevTexture;
  23822. this._textures[ name ] = prevTexture;
  23823. this._previousTextures[ name ] = texture;
  23824. this._textureNodes[ name ].updateTexture();
  23825. this._previousTextureNodes[ name ].updateTexture();
  23826. }
  23827. }
  23828. /**
  23829. * Returns the texture node for the given output name.
  23830. *
  23831. * @param {string} [name='output'] - The output name to get the texture node for.
  23832. * @return {TextureNode} The texture node.
  23833. */
  23834. getTextureNode( name = 'output' ) {
  23835. let textureNode = this._textureNodes[ name ];
  23836. if ( textureNode === undefined ) {
  23837. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  23838. textureNode.updateTexture();
  23839. this._textureNodes[ name ] = textureNode;
  23840. }
  23841. return textureNode;
  23842. }
  23843. /**
  23844. * Returns the previous texture node for the given output name.
  23845. *
  23846. * @param {string} [name='output'] - The output name to get the previous texture node for.
  23847. * @return {TextureNode} The previous texture node.
  23848. */
  23849. getPreviousTextureNode( name = 'output' ) {
  23850. let textureNode = this._previousTextureNodes[ name ];
  23851. if ( textureNode === undefined ) {
  23852. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  23853. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  23854. textureNode.updateTexture();
  23855. this._previousTextureNodes[ name ] = textureNode;
  23856. }
  23857. return textureNode;
  23858. }
  23859. /**
  23860. * Returns a viewZ node of this pass.
  23861. *
  23862. * @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.
  23863. * @return {Node} The viewZ node.
  23864. */
  23865. getViewZNode( name = 'depth' ) {
  23866. let viewZNode = this._viewZNodes[ name ];
  23867. if ( viewZNode === undefined ) {
  23868. const cameraNear = this._cameraNear;
  23869. const cameraFar = this._cameraFar;
  23870. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  23871. }
  23872. return viewZNode;
  23873. }
  23874. /**
  23875. * Returns a linear depth node of this pass.
  23876. *
  23877. * @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.
  23878. * @return {Node} The linear depth node.
  23879. */
  23880. getLinearDepthNode( name = 'depth' ) {
  23881. let linearDepthNode = this._linearDepthNodes[ name ];
  23882. if ( linearDepthNode === undefined ) {
  23883. const cameraNear = this._cameraNear;
  23884. const cameraFar = this._cameraFar;
  23885. const viewZNode = this.getViewZNode( name );
  23886. // TODO: just if ( builder.camera.isPerspectiveCamera )
  23887. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  23888. }
  23889. return linearDepthNode;
  23890. }
  23891. setup( { renderer } ) {
  23892. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  23893. // TODO: Disable MSAA for WebGL backend for now
  23894. if ( renderer.backend.isWebGLBackend === true ) {
  23895. this.renderTarget.samples = 0;
  23896. }
  23897. this.renderTarget.texture.type = renderer.getColorBufferType();
  23898. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  23899. }
  23900. updateBefore( frame ) {
  23901. const { renderer } = frame;
  23902. const { scene } = this;
  23903. let camera;
  23904. let pixelRatio;
  23905. const outputRenderTarget = renderer.getOutputRenderTarget();
  23906. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  23907. pixelRatio = 1;
  23908. camera = renderer.xr.getCamera();
  23909. renderer.xr.updateCamera( camera );
  23910. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  23911. } else {
  23912. camera = this.camera;
  23913. pixelRatio = renderer.getPixelRatio();
  23914. renderer.getSize( _size );
  23915. }
  23916. this._pixelRatio = pixelRatio;
  23917. this.setSize( _size.width, _size.height );
  23918. const currentRenderTarget = renderer.getRenderTarget();
  23919. const currentMRT = renderer.getMRT();
  23920. const currentMask = camera.layers.mask;
  23921. this._cameraNear.value = camera.near;
  23922. this._cameraFar.value = camera.far;
  23923. if ( this._layers !== null ) {
  23924. camera.layers.mask = this._layers.mask;
  23925. }
  23926. for ( const name in this._previousTextures ) {
  23927. this.toggleTexture( name );
  23928. }
  23929. renderer.setRenderTarget( this.renderTarget );
  23930. renderer.setMRT( this._mrt );
  23931. renderer.render( scene, camera );
  23932. renderer.setRenderTarget( currentRenderTarget );
  23933. renderer.setMRT( currentMRT );
  23934. camera.layers.mask = currentMask;
  23935. }
  23936. /**
  23937. * Sets the size of the pass's render target. Honors the pixel ratio.
  23938. *
  23939. * @param {number} width - The width to set.
  23940. * @param {number} height - The height to set.
  23941. */
  23942. setSize( width, height ) {
  23943. this._width = width;
  23944. this._height = height;
  23945. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  23946. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  23947. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23948. }
  23949. /**
  23950. * Sets the pixel ratio the pass's render target and updates the size.
  23951. *
  23952. * @param {number} pixelRatio - The pixel ratio to set.
  23953. */
  23954. setPixelRatio( pixelRatio ) {
  23955. this._pixelRatio = pixelRatio;
  23956. this.setSize( this._width, this._height );
  23957. }
  23958. /**
  23959. * Frees internal resources. Should be called when the node is no longer in use.
  23960. */
  23961. dispose() {
  23962. this.renderTarget.dispose();
  23963. }
  23964. }
  23965. /**
  23966. * @static
  23967. * @type {'color'}
  23968. * @default 'color'
  23969. */
  23970. PassNode.COLOR = 'color';
  23971. /**
  23972. * @static
  23973. * @type {'depth'}
  23974. * @default 'depth'
  23975. */
  23976. PassNode.DEPTH = 'depth';
  23977. /**
  23978. * TSL function for creating a pass node.
  23979. *
  23980. * @tsl
  23981. * @function
  23982. * @param {Scene} scene - A reference to the scene.
  23983. * @param {Camera} camera - A reference to the camera.
  23984. * @param {Object} options - Options for the internal render target.
  23985. * @returns {PassNode}
  23986. */
  23987. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  23988. /**
  23989. * TSL function for creating a pass texture node.
  23990. *
  23991. * @tsl
  23992. * @function
  23993. * @param {PassNode} pass - The pass node.
  23994. * @param {Texture} texture - The output texture.
  23995. * @returns {PassTextureNode}
  23996. */
  23997. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  23998. /**
  23999. * TSL function for creating a depth pass node.
  24000. *
  24001. * @tsl
  24002. * @function
  24003. * @param {Scene} scene - A reference to the scene.
  24004. * @param {Camera} camera - A reference to the camera.
  24005. * @param {Object} options - Options for the internal render target.
  24006. * @returns {PassNode}
  24007. */
  24008. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  24009. /**
  24010. * Represents a render pass for producing a toon outline effect on compatible objects.
  24011. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  24012. * will receive the outline.
  24013. *
  24014. * ```js
  24015. * const postProcessing = new PostProcessing( renderer );
  24016. *
  24017. * const scenePass = toonOutlinePass( scene, camera );
  24018. *
  24019. * postProcessing.outputNode = scenePass;
  24020. * ```
  24021. * @augments PassNode
  24022. */
  24023. class ToonOutlinePassNode extends PassNode {
  24024. static get type() {
  24025. return 'ToonOutlinePassNode';
  24026. }
  24027. /**
  24028. * Constructs a new outline pass node.
  24029. *
  24030. * @param {Scene} scene - A reference to the scene.
  24031. * @param {Camera} camera - A reference to the camera.
  24032. * @param {Node} colorNode - Defines the outline's color.
  24033. * @param {Node} thicknessNode - Defines the outline's thickness.
  24034. * @param {Node} alphaNode - Defines the outline's alpha.
  24035. */
  24036. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  24037. super( PassNode.COLOR, scene, camera );
  24038. /**
  24039. * Defines the outline's color.
  24040. *
  24041. * @type {Node}
  24042. */
  24043. this.colorNode = colorNode;
  24044. /**
  24045. * Defines the outline's thickness.
  24046. *
  24047. * @type {Node}
  24048. */
  24049. this.thicknessNode = thicknessNode;
  24050. /**
  24051. * Defines the outline's alpha.
  24052. *
  24053. * @type {Node}
  24054. */
  24055. this.alphaNode = alphaNode;
  24056. /**
  24057. * An internal material cache.
  24058. *
  24059. * @private
  24060. * @type {WeakMap<Material, NodeMaterial>}
  24061. */
  24062. this._materialCache = new WeakMap();
  24063. }
  24064. updateBefore( frame ) {
  24065. const { renderer } = frame;
  24066. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  24067. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  24068. // only render outline for supported materials
  24069. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  24070. if ( material.wireframe === false ) {
  24071. const outlineMaterial = this._getOutlineMaterial( material );
  24072. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  24073. }
  24074. }
  24075. // default
  24076. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  24077. } );
  24078. super.updateBefore( frame );
  24079. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  24080. }
  24081. /**
  24082. * Creates the material used for outline rendering.
  24083. *
  24084. * @private
  24085. * @return {NodeMaterial} The outline material.
  24086. */
  24087. _createMaterial() {
  24088. const material = new NodeMaterial();
  24089. material.isMeshToonOutlineMaterial = true;
  24090. material.name = 'Toon_Outline';
  24091. material.side = BackSide;
  24092. // vertex node
  24093. const outlineNormal = normalLocal.negate();
  24094. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  24095. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  24096. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  24097. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  24098. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  24099. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  24100. // color node
  24101. material.colorNode = vec4( this.colorNode, this.alphaNode );
  24102. return material;
  24103. }
  24104. /**
  24105. * For the given toon material, this method returns a corresponding
  24106. * outline material.
  24107. *
  24108. * @private
  24109. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  24110. * @return {NodeMaterial} The outline material.
  24111. */
  24112. _getOutlineMaterial( originalMaterial ) {
  24113. let outlineMaterial = this._materialCache.get( originalMaterial );
  24114. if ( outlineMaterial === undefined ) {
  24115. outlineMaterial = this._createMaterial();
  24116. this._materialCache.set( originalMaterial, outlineMaterial );
  24117. }
  24118. return outlineMaterial;
  24119. }
  24120. }
  24121. /**
  24122. * TSL function for creating a toon outline pass node.
  24123. *
  24124. * @tsl
  24125. * @function
  24126. * @param {Scene} scene - A reference to the scene.
  24127. * @param {Camera} camera - A reference to the camera.
  24128. * @param {Color} color - Defines the outline's color.
  24129. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  24130. * @param {number} [alpha=1] - Defines the outline's alpha.
  24131. * @returns {ToonOutlinePassNode}
  24132. */
  24133. 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 ) ) );
  24134. /**
  24135. * Linear tone mapping, exposure only.
  24136. *
  24137. * @tsl
  24138. * @function
  24139. * @param {Node<vec3>} color - The color that should be tone mapped.
  24140. * @param {Node<float>} exposure - The exposure.
  24141. * @return {Node<vec3>} The tone mapped color.
  24142. */
  24143. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24144. return color.mul( exposure ).clamp();
  24145. } ).setLayout( {
  24146. name: 'linearToneMapping',
  24147. type: 'vec3',
  24148. inputs: [
  24149. { name: 'color', type: 'vec3' },
  24150. { name: 'exposure', type: 'float' }
  24151. ]
  24152. } );
  24153. /**
  24154. * Reinhard tone mapping.
  24155. *
  24156. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  24157. *
  24158. * @tsl
  24159. * @function
  24160. * @param {Node<vec3>} color - The color that should be tone mapped.
  24161. * @param {Node<float>} exposure - The exposure.
  24162. * @return {Node<vec3>} The tone mapped color.
  24163. */
  24164. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24165. color = color.mul( exposure );
  24166. return color.div( color.add( 1.0 ) ).clamp();
  24167. } ).setLayout( {
  24168. name: 'reinhardToneMapping',
  24169. type: 'vec3',
  24170. inputs: [
  24171. { name: 'color', type: 'vec3' },
  24172. { name: 'exposure', type: 'float' }
  24173. ]
  24174. } );
  24175. /**
  24176. * Cineon tone mapping.
  24177. *
  24178. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  24179. *
  24180. * @tsl
  24181. * @function
  24182. * @param {Node<vec3>} color - The color that should be tone mapped.
  24183. * @param {Node<float>} exposure - The exposure.
  24184. * @return {Node<vec3>} The tone mapped color.
  24185. */
  24186. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24187. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  24188. color = color.mul( exposure );
  24189. color = color.sub( 0.004 ).max( 0.0 );
  24190. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  24191. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  24192. return a.div( b ).pow( 2.2 );
  24193. } ).setLayout( {
  24194. name: 'cineonToneMapping',
  24195. type: 'vec3',
  24196. inputs: [
  24197. { name: 'color', type: 'vec3' },
  24198. { name: 'exposure', type: 'float' }
  24199. ]
  24200. } );
  24201. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  24202. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24203. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  24204. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  24205. return a.div( b );
  24206. } );
  24207. /**
  24208. * ACESFilmic tone mapping.
  24209. *
  24210. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  24211. *
  24212. * @tsl
  24213. * @function
  24214. * @param {Node<vec3>} color - The color that should be tone mapped.
  24215. * @param {Node<float>} exposure - The exposure.
  24216. * @return {Node<vec3>} The tone mapped color.
  24217. */
  24218. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24219. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  24220. const ACESInputMat = mat3(
  24221. 0.59719, 0.35458, 0.04823,
  24222. 0.07600, 0.90834, 0.01566,
  24223. 0.02840, 0.13383, 0.83777
  24224. );
  24225. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  24226. const ACESOutputMat = mat3(
  24227. 1.60475, - 0.53108, - 0.07367,
  24228. - 0.10208, 1.10813, - 0.00605,
  24229. - 0.00327, - 0.07276, 1.07602
  24230. );
  24231. color = color.mul( exposure ).div( 0.6 );
  24232. color = ACESInputMat.mul( color );
  24233. // Apply RRT and ODT
  24234. color = RRTAndODTFit( color );
  24235. color = ACESOutputMat.mul( color );
  24236. // Clamp to [0, 1]
  24237. return color.clamp();
  24238. } ).setLayout( {
  24239. name: 'acesFilmicToneMapping',
  24240. type: 'vec3',
  24241. inputs: [
  24242. { name: 'color', type: 'vec3' },
  24243. { name: 'exposure', type: 'float' }
  24244. ]
  24245. } );
  24246. 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, - 0.0083, 1.1187 ) );
  24247. 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 ) );
  24248. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  24249. const x = vec3( x_immutable ).toVar();
  24250. const x2 = vec3( x.mul( x ) ).toVar();
  24251. const x4 = vec3( x2.mul( x2 ) ).toVar();
  24252. 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 ) ) ) );
  24253. } );
  24254. /**
  24255. * AgX tone mapping.
  24256. *
  24257. * @tsl
  24258. * @function
  24259. * @param {Node<vec3>} color - The color that should be tone mapped.
  24260. * @param {Node<float>} exposure - The exposure.
  24261. * @return {Node<vec3>} The tone mapped color.
  24262. */
  24263. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24264. const colortone = vec3( color ).toVar();
  24265. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  24266. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  24267. const AgxMinEv = float( - 12.47393 );
  24268. const AgxMaxEv = float( 4.026069 );
  24269. colortone.mulAssign( exposure );
  24270. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  24271. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  24272. colortone.assign( max$1( colortone, 1e-10 ) );
  24273. colortone.assign( log2( colortone ) );
  24274. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  24275. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24276. colortone.assign( agxDefaultContrastApprox( colortone ) );
  24277. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  24278. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  24279. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  24280. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24281. return colortone;
  24282. } ).setLayout( {
  24283. name: 'agxToneMapping',
  24284. type: 'vec3',
  24285. inputs: [
  24286. { name: 'color', type: 'vec3' },
  24287. { name: 'exposure', type: 'float' }
  24288. ]
  24289. } );
  24290. /**
  24291. * Neutral tone mapping.
  24292. *
  24293. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  24294. *
  24295. * @tsl
  24296. * @function
  24297. * @param {Node<vec3>} color - The color that should be tone mapped.
  24298. * @param {Node<float>} exposure - The exposure.
  24299. * @return {Node<vec3>} The tone mapped color.
  24300. */
  24301. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24302. const StartCompression = float( 0.8 - 0.04 );
  24303. const Desaturation = float( 0.15 );
  24304. color = color.mul( exposure );
  24305. const x = min$1( color.r, min$1( color.g, color.b ) );
  24306. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  24307. color.subAssign( offset );
  24308. const peak = max$1( color.r, max$1( color.g, color.b ) );
  24309. If( peak.lessThan( StartCompression ), () => {
  24310. return color;
  24311. } );
  24312. const d = sub( 1, StartCompression );
  24313. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  24314. color.mulAssign( newPeak.div( peak ) );
  24315. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  24316. return mix( color, vec3( newPeak ), g );
  24317. } ).setLayout( {
  24318. name: 'neutralToneMapping',
  24319. type: 'vec3',
  24320. inputs: [
  24321. { name: 'color', type: 'vec3' },
  24322. { name: 'exposure', type: 'float' }
  24323. ]
  24324. } );
  24325. /**
  24326. * This class represents native code sections. It is the base
  24327. * class for modules like {@link FunctionNode} which allows to implement
  24328. * functions with native shader languages.
  24329. *
  24330. * @augments Node
  24331. */
  24332. class CodeNode extends Node {
  24333. static get type() {
  24334. return 'CodeNode';
  24335. }
  24336. /**
  24337. * Constructs a new code node.
  24338. *
  24339. * @param {string} [code=''] - The native code.
  24340. * @param {Array<Node>} [includes=[]] - An array of includes.
  24341. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24342. */
  24343. constructor( code = '', includes = [], language = '' ) {
  24344. super( 'code' );
  24345. /**
  24346. * This flag can be used for type testing.
  24347. *
  24348. * @type {boolean}
  24349. * @readonly
  24350. * @default true
  24351. */
  24352. this.isCodeNode = true;
  24353. /**
  24354. * The native code.
  24355. *
  24356. * @type {string}
  24357. * @default ''
  24358. */
  24359. this.code = code;
  24360. /**
  24361. * An array of includes
  24362. *
  24363. * @type {Array<Node>}
  24364. * @default []
  24365. */
  24366. this.includes = includes;
  24367. /**
  24368. * The used language.
  24369. *
  24370. * @type {('js'|'wgsl'|'glsl')}
  24371. * @default ''
  24372. */
  24373. this.language = language;
  24374. }
  24375. /**
  24376. * The method is overwritten so it always returns `true`.
  24377. *
  24378. * @return {boolean} Whether this node is global or not.
  24379. */
  24380. isGlobal() {
  24381. return true;
  24382. }
  24383. /**
  24384. * Sets the includes of this code node.
  24385. *
  24386. * @param {Array<Node>} includes - The includes to set.
  24387. * @return {CodeNode} A reference to this node.
  24388. */
  24389. setIncludes( includes ) {
  24390. this.includes = includes;
  24391. return this;
  24392. }
  24393. /**
  24394. * Returns the includes of this code node.
  24395. *
  24396. * @param {NodeBuilder} builder - The current node builder.
  24397. * @return {Array<Node>} The includes.
  24398. */
  24399. getIncludes( /*builder*/ ) {
  24400. return this.includes;
  24401. }
  24402. generate( builder ) {
  24403. const includes = this.getIncludes( builder );
  24404. for ( const include of includes ) {
  24405. include.build( builder );
  24406. }
  24407. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  24408. nodeCode.code = this.code;
  24409. return nodeCode.code;
  24410. }
  24411. serialize( data ) {
  24412. super.serialize( data );
  24413. data.code = this.code;
  24414. data.language = this.language;
  24415. }
  24416. deserialize( data ) {
  24417. super.deserialize( data );
  24418. this.code = data.code;
  24419. this.language = data.language;
  24420. }
  24421. }
  24422. /**
  24423. * TSL function for creating a code node.
  24424. *
  24425. * @tsl
  24426. * @function
  24427. * @param {string} [code=''] - The native code.
  24428. * @param {Array<Node>} [includes=[]] - An array of includes.
  24429. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24430. * @returns {CodeNode}
  24431. */
  24432. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  24433. /**
  24434. * TSL function for creating a JS code node.
  24435. *
  24436. * @tsl
  24437. * @function
  24438. * @param {string} src - The native code.
  24439. * @param {Array<Node>} includes - An array of includes.
  24440. * @returns {CodeNode}
  24441. */
  24442. const js = ( src, includes ) => code( src, includes, 'js' );
  24443. /**
  24444. * TSL function for creating a WGSL code node.
  24445. *
  24446. * @tsl
  24447. * @function
  24448. * @param {string} src - The native code.
  24449. * @param {Array<Node>} includes - An array of includes.
  24450. * @returns {CodeNode}
  24451. */
  24452. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  24453. /**
  24454. * TSL function for creating a GLSL code node.
  24455. *
  24456. * @tsl
  24457. * @function
  24458. * @param {string} src - The native code.
  24459. * @param {Array<Node>} includes - An array of includes.
  24460. * @returns {CodeNode}
  24461. */
  24462. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  24463. /**
  24464. * This class represents a native shader function. It can be used to implement
  24465. * certain aspects of a node material with native shader code. There are two predefined
  24466. * TSL functions for easier usage.
  24467. *
  24468. * - `wgslFn`: Creates a WGSL function node.
  24469. * - `glslFn`: Creates a GLSL function node.
  24470. *
  24471. * A basic example with one include looks like so:
  24472. *
  24473. * ```js
  24474. * const desaturateWGSLFn = wgslFn( `
  24475. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  24476. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  24477. * return vec3<f32>( dot( lum, color ) );
  24478. * }`
  24479. *);
  24480. * const someWGSLFn = wgslFn( `
  24481. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  24482. * return desaturate( color );
  24483. * }
  24484. * `, [ desaturateWGSLFn ] );
  24485. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  24486. *```
  24487. * @augments CodeNode
  24488. */
  24489. class FunctionNode extends CodeNode {
  24490. static get type() {
  24491. return 'FunctionNode';
  24492. }
  24493. /**
  24494. * Constructs a new function node.
  24495. *
  24496. * @param {string} [code=''] - The native code.
  24497. * @param {Array<Node>} [includes=[]] - An array of includes.
  24498. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24499. */
  24500. constructor( code = '', includes = [], language = '' ) {
  24501. super( code, includes, language );
  24502. }
  24503. getNodeType( builder ) {
  24504. return this.getNodeFunction( builder ).type;
  24505. }
  24506. /**
  24507. * Returns the inputs of this function node.
  24508. *
  24509. * @param {NodeBuilder} builder - The current node builder.
  24510. * @return {Array<NodeFunctionInput>} The inputs.
  24511. */
  24512. getInputs( builder ) {
  24513. return this.getNodeFunction( builder ).inputs;
  24514. }
  24515. /**
  24516. * Returns the node function for this function node.
  24517. *
  24518. * @param {NodeBuilder} builder - The current node builder.
  24519. * @return {NodeFunction} The node function.
  24520. */
  24521. getNodeFunction( builder ) {
  24522. const nodeData = builder.getDataFromNode( this );
  24523. let nodeFunction = nodeData.nodeFunction;
  24524. if ( nodeFunction === undefined ) {
  24525. nodeFunction = builder.parser.parseFunction( this.code );
  24526. nodeData.nodeFunction = nodeFunction;
  24527. }
  24528. return nodeFunction;
  24529. }
  24530. generate( builder, output ) {
  24531. super.generate( builder );
  24532. const nodeFunction = this.getNodeFunction( builder );
  24533. const name = nodeFunction.name;
  24534. const type = nodeFunction.type;
  24535. const nodeCode = builder.getCodeFromNode( this, type );
  24536. if ( name !== '' ) {
  24537. // use a custom property name
  24538. nodeCode.name = name;
  24539. }
  24540. const propertyName = builder.getPropertyName( nodeCode );
  24541. const code = this.getNodeFunction( builder ).getCode( propertyName );
  24542. nodeCode.code = code + '\n';
  24543. if ( output === 'property' ) {
  24544. return propertyName;
  24545. } else {
  24546. return builder.format( `${ propertyName }()`, type, output );
  24547. }
  24548. }
  24549. }
  24550. const nativeFn = ( code, includes = [], language = '' ) => {
  24551. for ( let i = 0; i < includes.length; i ++ ) {
  24552. const include = includes[ i ];
  24553. // TSL Function: glslFn, wgslFn
  24554. if ( typeof include === 'function' ) {
  24555. includes[ i ] = include.functionNode;
  24556. }
  24557. }
  24558. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  24559. const fn = ( ...params ) => functionNode.call( ...params );
  24560. fn.functionNode = functionNode;
  24561. return fn;
  24562. };
  24563. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  24564. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  24565. /**
  24566. * `ScriptableNode` uses this class to manage script inputs and outputs.
  24567. *
  24568. * @augments Node
  24569. */
  24570. class ScriptableValueNode extends Node {
  24571. static get type() {
  24572. return 'ScriptableValueNode';
  24573. }
  24574. /**
  24575. * Constructs a new scriptable node.
  24576. *
  24577. * @param {any} [value=null] - The value.
  24578. */
  24579. constructor( value = null ) {
  24580. super();
  24581. /**
  24582. * A reference to the value.
  24583. *
  24584. * @private
  24585. * @default null
  24586. */
  24587. this._value = value;
  24588. /**
  24589. * Depending on the type of `_value`, this property might cache parsed data.
  24590. *
  24591. * @private
  24592. * @default null
  24593. */
  24594. this._cache = null;
  24595. /**
  24596. * If this node represents an input, this property represents the input type.
  24597. *
  24598. * @type {?string}
  24599. * @default null
  24600. */
  24601. this.inputType = null;
  24602. /**
  24603. * If this node represents an output, this property represents the output type.
  24604. *
  24605. * @type {?string}
  24606. * @default null
  24607. */
  24608. this.outputType = null;
  24609. /**
  24610. * An event dispatcher for managing events.
  24611. *
  24612. * @type {EventDispatcher}
  24613. */
  24614. this.events = new EventDispatcher();
  24615. /**
  24616. * This flag can be used for type testing.
  24617. *
  24618. * @type {boolean}
  24619. * @readonly
  24620. * @default true
  24621. */
  24622. this.isScriptableValueNode = true;
  24623. }
  24624. /**
  24625. * Whether this node represents an output or not.
  24626. *
  24627. * @type {boolean}
  24628. * @readonly
  24629. * @default true
  24630. */
  24631. get isScriptableOutputNode() {
  24632. return this.outputType !== null;
  24633. }
  24634. set value( val ) {
  24635. if ( this._value === val ) return;
  24636. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  24637. URL.revokeObjectURL( this._cache );
  24638. this._cache = null;
  24639. }
  24640. this._value = val;
  24641. this.events.dispatchEvent( { type: 'change' } );
  24642. this.refresh();
  24643. }
  24644. /**
  24645. * The node's value.
  24646. *
  24647. * @type {any}
  24648. */
  24649. get value() {
  24650. return this._value;
  24651. }
  24652. /**
  24653. * Dispatches the `refresh` event.
  24654. */
  24655. refresh() {
  24656. this.events.dispatchEvent( { type: 'refresh' } );
  24657. }
  24658. /**
  24659. * The `value` property usually represents a node or even binary data in form of array buffers.
  24660. * In this case, this method tries to return the actual value behind the complex type.
  24661. *
  24662. * @return {any} The value.
  24663. */
  24664. getValue() {
  24665. const value = this.value;
  24666. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  24667. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  24668. } else if ( value && value.value !== null && value.value !== undefined && (
  24669. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  24670. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  24671. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  24672. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  24673. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  24674. ( this.inputType === 'Color' && value.value.isColor ) ||
  24675. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  24676. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  24677. ) ) {
  24678. return value.value;
  24679. }
  24680. return this._cache || value;
  24681. }
  24682. /**
  24683. * Overwritten since the node type is inferred from the value.
  24684. *
  24685. * @param {NodeBuilder} builder - The current node builder.
  24686. * @return {string} The node type.
  24687. */
  24688. getNodeType( builder ) {
  24689. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  24690. }
  24691. setup() {
  24692. return this.value && this.value.isNode ? this.value : float();
  24693. }
  24694. serialize( data ) {
  24695. super.serialize( data );
  24696. if ( this.value !== null ) {
  24697. if ( this.inputType === 'ArrayBuffer' ) {
  24698. data.value = arrayBufferToBase64( this.value );
  24699. } else {
  24700. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  24701. }
  24702. } else {
  24703. data.value = null;
  24704. }
  24705. data.inputType = this.inputType;
  24706. data.outputType = this.outputType;
  24707. }
  24708. deserialize( data ) {
  24709. super.deserialize( data );
  24710. let value = null;
  24711. if ( data.value !== null ) {
  24712. if ( data.inputType === 'ArrayBuffer' ) {
  24713. value = base64ToArrayBuffer( data.value );
  24714. } else if ( data.inputType === 'Texture' ) {
  24715. value = data.meta.textures[ data.value ];
  24716. } else {
  24717. value = data.meta.nodes[ data.value ] || null;
  24718. }
  24719. }
  24720. this.value = value;
  24721. this.inputType = data.inputType;
  24722. this.outputType = data.outputType;
  24723. }
  24724. }
  24725. /**
  24726. * TSL function for creating a scriptable value node.
  24727. *
  24728. * @tsl
  24729. * @function
  24730. * @param {any} [value=null] - The value.
  24731. * @returns {ScriptableValueNode}
  24732. */
  24733. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  24734. /**
  24735. * A Map-like data structure for managing resources of scriptable nodes.
  24736. *
  24737. * @augments Map
  24738. */
  24739. class Resources extends Map {
  24740. get( key, callback = null, ...params ) {
  24741. if ( this.has( key ) ) return super.get( key );
  24742. if ( callback !== null ) {
  24743. const value = callback( ...params );
  24744. this.set( key, value );
  24745. return value;
  24746. }
  24747. }
  24748. }
  24749. class Parameters {
  24750. constructor( scriptableNode ) {
  24751. this.scriptableNode = scriptableNode;
  24752. }
  24753. get parameters() {
  24754. return this.scriptableNode.parameters;
  24755. }
  24756. get layout() {
  24757. return this.scriptableNode.getLayout();
  24758. }
  24759. getInputLayout( id ) {
  24760. return this.scriptableNode.getInputLayout( id );
  24761. }
  24762. get( name ) {
  24763. const param = this.parameters[ name ];
  24764. const value = param ? param.getValue() : null;
  24765. return value;
  24766. }
  24767. }
  24768. /**
  24769. * Defines the resources (e.g. namespaces) of scriptable nodes.
  24770. *
  24771. * @type {Resources}
  24772. */
  24773. const ScriptableNodeResources = new Resources();
  24774. /**
  24775. * This type of node allows to implement nodes with custom scripts. The script
  24776. * section is represented as an instance of `CodeNode` written with JavaScript.
  24777. * The script itself must adhere to a specific structure.
  24778. *
  24779. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  24780. * - layout: The layout object defines the script's interface (inputs and outputs).
  24781. *
  24782. * ```js
  24783. * ScriptableNodeResources.set( 'TSL', TSL );
  24784. *
  24785. * const scriptableNode = scriptable( js( `
  24786. * layout = {
  24787. * outputType: 'node',
  24788. * elements: [
  24789. * { name: 'source', inputType: 'node' },
  24790. * ]
  24791. * };
  24792. *
  24793. * const { mul, oscSine } = TSL;
  24794. *
  24795. * function main() {
  24796. * const source = parameters.get( 'source' ) || float();
  24797. * return mul( source, oscSine() ) );
  24798. * }
  24799. *
  24800. * ` ) );
  24801. *
  24802. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  24803. *
  24804. * const material = new THREE.MeshBasicNodeMaterial();
  24805. * material.colorNode = scriptableNode;
  24806. * ```
  24807. *
  24808. * @augments Node
  24809. */
  24810. class ScriptableNode extends Node {
  24811. static get type() {
  24812. return 'ScriptableNode';
  24813. }
  24814. /**
  24815. * Constructs a new scriptable node.
  24816. *
  24817. * @param {?CodeNode} [codeNode=null] - The code node.
  24818. * @param {Object} [parameters={}] - The parameters definition.
  24819. */
  24820. constructor( codeNode = null, parameters = {} ) {
  24821. super();
  24822. /**
  24823. * The code node.
  24824. *
  24825. * @type {?CodeNode}
  24826. * @default null
  24827. */
  24828. this.codeNode = codeNode;
  24829. /**
  24830. * The parameters definition.
  24831. *
  24832. * @type {Object}
  24833. * @default {}
  24834. */
  24835. this.parameters = parameters;
  24836. this._local = new Resources();
  24837. this._output = scriptableValue();
  24838. this._outputs = {};
  24839. this._source = this.source;
  24840. this._method = null;
  24841. this._object = null;
  24842. this._value = null;
  24843. this._needsOutputUpdate = true;
  24844. this.onRefresh = this.onRefresh.bind( this );
  24845. /**
  24846. * This flag can be used for type testing.
  24847. *
  24848. * @type {boolean}
  24849. * @readonly
  24850. * @default true
  24851. */
  24852. this.isScriptableNode = true;
  24853. }
  24854. /**
  24855. * The source code of the scriptable node.
  24856. *
  24857. * @type {string}
  24858. */
  24859. get source() {
  24860. return this.codeNode ? this.codeNode.code : '';
  24861. }
  24862. /**
  24863. * Sets the reference of a local script variable.
  24864. *
  24865. * @param {string} name - The variable name.
  24866. * @param {Object} value - The reference to set.
  24867. * @return {Resources} The resource map
  24868. */
  24869. setLocal( name, value ) {
  24870. return this._local.set( name, value );
  24871. }
  24872. /**
  24873. * Gets the value of a local script variable.
  24874. *
  24875. * @param {string} name - The variable name.
  24876. * @return {Object} The value.
  24877. */
  24878. getLocal( name ) {
  24879. return this._local.get( name );
  24880. }
  24881. /**
  24882. * Event listener for the `refresh` event.
  24883. */
  24884. onRefresh() {
  24885. this._refresh();
  24886. }
  24887. /**
  24888. * Returns an input from the layout with the given id/name.
  24889. *
  24890. * @param {string} id - The id/name of the input.
  24891. * @return {Object} The element entry.
  24892. */
  24893. getInputLayout( id ) {
  24894. for ( const element of this.getLayout() ) {
  24895. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  24896. return element;
  24897. }
  24898. }
  24899. }
  24900. /**
  24901. * Returns an output from the layout with the given id/name.
  24902. *
  24903. * @param {string} id - The id/name of the output.
  24904. * @return {Object} The element entry.
  24905. */
  24906. getOutputLayout( id ) {
  24907. for ( const element of this.getLayout() ) {
  24908. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  24909. return element;
  24910. }
  24911. }
  24912. }
  24913. /**
  24914. * Defines a script output for the given name and value.
  24915. *
  24916. * @param {string} name - The name of the output.
  24917. * @param {Node} value - The node value.
  24918. * @return {ScriptableNode} A reference to this node.
  24919. */
  24920. setOutput( name, value ) {
  24921. const outputs = this._outputs;
  24922. if ( outputs[ name ] === undefined ) {
  24923. outputs[ name ] = scriptableValue( value );
  24924. } else {
  24925. outputs[ name ].value = value;
  24926. }
  24927. return this;
  24928. }
  24929. /**
  24930. * Returns a script output for the given name.
  24931. *
  24932. * @param {string} name - The name of the output.
  24933. * @return {ScriptableValueNode} The node value.
  24934. */
  24935. getOutput( name ) {
  24936. return this._outputs[ name ];
  24937. }
  24938. /**
  24939. * Returns a parameter for the given name
  24940. *
  24941. * @param {string} name - The name of the parameter.
  24942. * @return {ScriptableValueNode} The node value.
  24943. */
  24944. getParameter( name ) {
  24945. return this.parameters[ name ];
  24946. }
  24947. /**
  24948. * Sets a value for the given parameter name.
  24949. *
  24950. * @param {string} name - The parameter name.
  24951. * @param {any} value - The parameter value.
  24952. * @return {ScriptableNode} A reference to this node.
  24953. */
  24954. setParameter( name, value ) {
  24955. const parameters = this.parameters;
  24956. if ( value && value.isScriptableNode ) {
  24957. this.deleteParameter( name );
  24958. parameters[ name ] = value;
  24959. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  24960. } else if ( value && value.isScriptableValueNode ) {
  24961. this.deleteParameter( name );
  24962. parameters[ name ] = value;
  24963. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24964. } else if ( parameters[ name ] === undefined ) {
  24965. parameters[ name ] = scriptableValue( value );
  24966. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24967. } else {
  24968. parameters[ name ].value = value;
  24969. }
  24970. return this;
  24971. }
  24972. /**
  24973. * Returns the value of this node which is the value of
  24974. * the default output.
  24975. *
  24976. * @return {Node} The value.
  24977. */
  24978. getValue() {
  24979. return this.getDefaultOutput().getValue();
  24980. }
  24981. /**
  24982. * Deletes a parameter from the script.
  24983. *
  24984. * @param {string} name - The parameter to remove.
  24985. * @return {ScriptableNode} A reference to this node.
  24986. */
  24987. deleteParameter( name ) {
  24988. let valueNode = this.parameters[ name ];
  24989. if ( valueNode ) {
  24990. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  24991. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  24992. }
  24993. return this;
  24994. }
  24995. /**
  24996. * Deletes all parameters from the script.
  24997. *
  24998. * @return {ScriptableNode} A reference to this node.
  24999. */
  25000. clearParameters() {
  25001. for ( const name of Object.keys( this.parameters ) ) {
  25002. this.deleteParameter( name );
  25003. }
  25004. this.needsUpdate = true;
  25005. return this;
  25006. }
  25007. /**
  25008. * Calls a function from the script.
  25009. *
  25010. * @param {string} name - The function name.
  25011. * @param {...any} params - A list of parameters.
  25012. * @return {any} The result of the function call.
  25013. */
  25014. call( name, ...params ) {
  25015. const object = this.getObject();
  25016. const method = object[ name ];
  25017. if ( typeof method === 'function' ) {
  25018. return method( ...params );
  25019. }
  25020. }
  25021. /**
  25022. * Asynchronously calls a function from the script.
  25023. *
  25024. * @param {string} name - The function name.
  25025. * @param {...any} params - A list of parameters.
  25026. * @return {Promise<any>} The result of the function call.
  25027. */
  25028. async callAsync( name, ...params ) {
  25029. const object = this.getObject();
  25030. const method = object[ name ];
  25031. if ( typeof method === 'function' ) {
  25032. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  25033. }
  25034. }
  25035. /**
  25036. * Overwritten since the node types is inferred from the script's output.
  25037. *
  25038. * @param {NodeBuilder} builder - The current node builder
  25039. * @return {string} The node type.
  25040. */
  25041. getNodeType( builder ) {
  25042. return this.getDefaultOutputNode().getNodeType( builder );
  25043. }
  25044. /**
  25045. * Refreshes the script node.
  25046. *
  25047. * @param {?string} [output=null] - An optional output.
  25048. */
  25049. refresh( output = null ) {
  25050. if ( output !== null ) {
  25051. this.getOutput( output ).refresh();
  25052. } else {
  25053. this._refresh();
  25054. }
  25055. }
  25056. /**
  25057. * Returns an object representation of the script.
  25058. *
  25059. * @return {Object} The result object.
  25060. */
  25061. getObject() {
  25062. if ( this.needsUpdate ) this.dispose();
  25063. if ( this._object !== null ) return this._object;
  25064. //
  25065. const refresh = () => this.refresh();
  25066. const setOutput = ( id, value ) => this.setOutput( id, value );
  25067. const parameters = new Parameters( this );
  25068. const THREE = ScriptableNodeResources.get( 'THREE' );
  25069. const TSL = ScriptableNodeResources.get( 'TSL' );
  25070. const method = this.getMethod();
  25071. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  25072. this._object = method( ...params );
  25073. const layout = this._object.layout;
  25074. if ( layout ) {
  25075. if ( layout.cache === false ) {
  25076. this._local.clear();
  25077. }
  25078. // default output
  25079. this._output.outputType = layout.outputType || null;
  25080. if ( Array.isArray( layout.elements ) ) {
  25081. for ( const element of layout.elements ) {
  25082. const id = element.id || element.name;
  25083. if ( element.inputType ) {
  25084. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  25085. this.getParameter( id ).inputType = element.inputType;
  25086. }
  25087. if ( element.outputType ) {
  25088. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  25089. this.getOutput( id ).outputType = element.outputType;
  25090. }
  25091. }
  25092. }
  25093. }
  25094. return this._object;
  25095. }
  25096. deserialize( data ) {
  25097. super.deserialize( data );
  25098. for ( const name in this.parameters ) {
  25099. let valueNode = this.parameters[ name ];
  25100. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25101. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  25102. }
  25103. }
  25104. /**
  25105. * Returns the layout of the script.
  25106. *
  25107. * @return {Object} The script's layout.
  25108. */
  25109. getLayout() {
  25110. return this.getObject().layout;
  25111. }
  25112. /**
  25113. * Returns default node output of the script.
  25114. *
  25115. * @return {Node} The default node output.
  25116. */
  25117. getDefaultOutputNode() {
  25118. const output = this.getDefaultOutput().value;
  25119. if ( output && output.isNode ) {
  25120. return output;
  25121. }
  25122. return float();
  25123. }
  25124. /**
  25125. * Returns default output of the script.
  25126. *
  25127. * @return {ScriptableValueNode} The default output.
  25128. */
  25129. getDefaultOutput() {
  25130. return this._exec()._output;
  25131. }
  25132. /**
  25133. * Returns a function created from the node's script.
  25134. *
  25135. * @return {Function} The function representing the node's code.
  25136. */
  25137. getMethod() {
  25138. if ( this.needsUpdate ) this.dispose();
  25139. if ( this._method !== null ) return this._method;
  25140. //
  25141. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  25142. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  25143. const properties = interfaceProps.join( ', ' );
  25144. const declarations = 'var ' + properties + '; var output = {};\n';
  25145. const returns = '\nreturn { ...output, ' + properties + ' };';
  25146. const code = declarations + this.codeNode.code + returns;
  25147. //
  25148. this._method = new Function( ...parametersProps, code );
  25149. return this._method;
  25150. }
  25151. /**
  25152. * Frees all internal resources.
  25153. */
  25154. dispose() {
  25155. if ( this._method === null ) return;
  25156. if ( this._object && typeof this._object.dispose === 'function' ) {
  25157. this._object.dispose();
  25158. }
  25159. this._method = null;
  25160. this._object = null;
  25161. this._source = null;
  25162. this._value = null;
  25163. this._needsOutputUpdate = true;
  25164. this._output.value = null;
  25165. this._outputs = {};
  25166. }
  25167. setup() {
  25168. return this.getDefaultOutputNode();
  25169. }
  25170. getCacheKey( force ) {
  25171. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  25172. for ( const param in this.parameters ) {
  25173. values.push( this.parameters[ param ].getCacheKey( force ) );
  25174. }
  25175. return hashArray( values );
  25176. }
  25177. set needsUpdate( value ) {
  25178. if ( value === true ) this.dispose();
  25179. }
  25180. get needsUpdate() {
  25181. return this.source !== this._source;
  25182. }
  25183. /**
  25184. * Executes the `main` function of the script.
  25185. *
  25186. * @private
  25187. * @return {ScriptableNode} A reference to this node.
  25188. */
  25189. _exec() {
  25190. if ( this.codeNode === null ) return this;
  25191. if ( this._needsOutputUpdate === true ) {
  25192. this._value = this.call( 'main' );
  25193. this._needsOutputUpdate = false;
  25194. }
  25195. this._output.value = this._value;
  25196. return this;
  25197. }
  25198. /**
  25199. * Executes the refresh.
  25200. *
  25201. * @private
  25202. */
  25203. _refresh() {
  25204. this.needsUpdate = true;
  25205. this._exec();
  25206. this._output.refresh();
  25207. }
  25208. }
  25209. /**
  25210. * TSL function for creating a scriptable node.
  25211. *
  25212. * @tsl
  25213. * @function
  25214. * @param {?CodeNode} [codeNode=null] - The code node.
  25215. * @param {Object} [parameters={}] - The parameters definition.
  25216. * @returns {ScriptableNode}
  25217. */
  25218. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  25219. /**
  25220. * Returns a node that represents the `z` coordinate in view space
  25221. * for the current fragment. It's a different representation of the
  25222. * default depth value.
  25223. *
  25224. * This value can be part of a computation that defines how the fog
  25225. * density increases when moving away from the camera.
  25226. *
  25227. * @param {NodeBuilder} builder - The current node builder.
  25228. * @return {Node} The viewZ node.
  25229. */
  25230. function getViewZNode( builder ) {
  25231. let viewZ;
  25232. const getViewZ = builder.context.getViewZ;
  25233. if ( getViewZ !== undefined ) {
  25234. viewZ = getViewZ( this );
  25235. }
  25236. return ( viewZ || positionView.z ).negate();
  25237. }
  25238. /**
  25239. * Constructs a new range factor node.
  25240. *
  25241. * @tsl
  25242. * @function
  25243. * @param {Node} near - Defines the near value.
  25244. * @param {Node} far - Defines the far value.
  25245. */
  25246. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  25247. const viewZ = getViewZNode( builder );
  25248. return smoothstep( near, far, viewZ );
  25249. } );
  25250. /**
  25251. * Represents an exponential squared fog. This type of fog gives
  25252. * a clear view near the camera and a faster than exponentially
  25253. * densening fog farther from the camera.
  25254. *
  25255. * @tsl
  25256. * @function
  25257. * @param {Node} density - Defines the fog density.
  25258. */
  25259. const densityFogFactor = Fn( ( [ density ], builder ) => {
  25260. const viewZ = getViewZNode( builder );
  25261. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  25262. } );
  25263. /**
  25264. * This class can be used to configure a fog for the scene.
  25265. * Nodes of this type are assigned to `Scene.fogNode`.
  25266. *
  25267. * @tsl
  25268. * @function
  25269. * @param {Node} color - Defines the color of the fog.
  25270. * @param {Node} factor - Defines how the fog is factored in the scene.
  25271. */
  25272. const fog = Fn( ( [ color, factor ] ) => {
  25273. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  25274. } );
  25275. // Deprecated
  25276. /**
  25277. * @tsl
  25278. * @function
  25279. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  25280. *
  25281. * @param {Node} color
  25282. * @param {Node} near
  25283. * @param {Node} far
  25284. * @returns {Function}
  25285. */
  25286. function rangeFog( color, near, far ) { // @deprecated, r171
  25287. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  25288. return fog( color, rangeFogFactor( near, far ) );
  25289. }
  25290. /**
  25291. * @tsl
  25292. * @function
  25293. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  25294. *
  25295. * @param {Node} color
  25296. * @param {Node} density
  25297. * @returns {Function}
  25298. */
  25299. function densityFog( color, density ) { // @deprecated, r171
  25300. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  25301. return fog( color, densityFogFactor( density ) );
  25302. }
  25303. let min = null;
  25304. let max = null;
  25305. /**
  25306. * `RangeNode` generates random instanced attribute data in a defined range.
  25307. * An exemplary use case for this utility node is to generate random per-instance
  25308. * colors:
  25309. * ```js
  25310. * const material = new MeshBasicNodeMaterial();
  25311. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  25312. * const mesh = new InstancedMesh( geometry, material, count );
  25313. * ```
  25314. * @augments Node
  25315. */
  25316. class RangeNode extends Node {
  25317. static get type() {
  25318. return 'RangeNode';
  25319. }
  25320. /**
  25321. * Constructs a new range node.
  25322. *
  25323. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25324. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25325. */
  25326. constructor( minNode = float(), maxNode = float() ) {
  25327. super();
  25328. /**
  25329. * A node defining the lower bound of the range.
  25330. *
  25331. * @type {Node<any>}
  25332. * @default float()
  25333. */
  25334. this.minNode = minNode;
  25335. /**
  25336. * A node defining the upper bound of the range.
  25337. *
  25338. * @type {Node<any>}
  25339. * @default float()
  25340. */
  25341. this.maxNode = maxNode;
  25342. }
  25343. /**
  25344. * Returns the vector length which is computed based on the range definition.
  25345. *
  25346. * @param {NodeBuilder} builder - The current node builder.
  25347. * @return {number} The vector length.
  25348. */
  25349. getVectorLength( builder ) {
  25350. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  25351. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  25352. return minLength > maxLength ? minLength : maxLength;
  25353. }
  25354. /**
  25355. * This method is overwritten since the node type is inferred from range definition.
  25356. *
  25357. * @param {NodeBuilder} builder - The current node builder.
  25358. * @return {string} The node type.
  25359. */
  25360. getNodeType( builder ) {
  25361. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  25362. }
  25363. setup( builder ) {
  25364. const object = builder.object;
  25365. let output = null;
  25366. if ( object.count > 1 ) {
  25367. const minValue = this.minNode.value;
  25368. const maxValue = this.maxNode.value;
  25369. const minLength = builder.getTypeLength( getValueType( minValue ) );
  25370. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  25371. min = min || new Vector4();
  25372. max = max || new Vector4();
  25373. min.setScalar( 0 );
  25374. max.setScalar( 0 );
  25375. if ( minLength === 1 ) min.setScalar( minValue );
  25376. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  25377. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  25378. if ( maxLength === 1 ) max.setScalar( maxValue );
  25379. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  25380. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  25381. const stride = 4;
  25382. const length = stride * object.count;
  25383. const array = new Float32Array( length );
  25384. for ( let i = 0; i < length; i ++ ) {
  25385. const index = i % stride;
  25386. const minElementValue = min.getComponent( index );
  25387. const maxElementValue = max.getComponent( index );
  25388. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  25389. }
  25390. const nodeType = this.getNodeType( builder );
  25391. if ( object.count <= 4096 ) {
  25392. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  25393. } else {
  25394. // TODO: Improve anonymous buffer attribute creation removing this part
  25395. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  25396. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  25397. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  25398. }
  25399. } else {
  25400. output = float( 0 );
  25401. }
  25402. return output;
  25403. }
  25404. }
  25405. /**
  25406. * TSL function for creating a range node.
  25407. *
  25408. * @tsl
  25409. * @function
  25410. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25411. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25412. * @returns {RangeNode}
  25413. */
  25414. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  25415. /**
  25416. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  25417. * about the currently running dispatch and/or the device it is running on.
  25418. *
  25419. * This node can only be used with a WebGPU backend.
  25420. *
  25421. * @augments Node
  25422. */
  25423. class ComputeBuiltinNode extends Node {
  25424. static get type() {
  25425. return 'ComputeBuiltinNode';
  25426. }
  25427. /**
  25428. * Constructs a new compute builtin node.
  25429. *
  25430. * @param {string} builtinName - The built-in name.
  25431. * @param {string} nodeType - The node type.
  25432. */
  25433. constructor( builtinName, nodeType ) {
  25434. super( nodeType );
  25435. /**
  25436. * The built-in name.
  25437. *
  25438. * @private
  25439. * @type {string}
  25440. */
  25441. this._builtinName = builtinName;
  25442. }
  25443. /**
  25444. * This method is overwritten since hash is derived from the built-in name.
  25445. *
  25446. * @param {NodeBuilder} builder - The current node builder.
  25447. * @return {string} The hash.
  25448. */
  25449. getHash( builder ) {
  25450. return this.getBuiltinName( builder );
  25451. }
  25452. /**
  25453. * This method is overwritten since the node type is simply derived from `nodeType`..
  25454. *
  25455. * @param {NodeBuilder} builder - The current node builder.
  25456. * @return {string} The node type.
  25457. */
  25458. getNodeType( /*builder*/ ) {
  25459. return this.nodeType;
  25460. }
  25461. /**
  25462. * Sets the builtin name.
  25463. *
  25464. * @param {string} builtinName - The built-in name.
  25465. * @return {ComputeBuiltinNode} A reference to this node.
  25466. */
  25467. setBuiltinName( builtinName ) {
  25468. this._builtinName = builtinName;
  25469. return this;
  25470. }
  25471. /**
  25472. * Returns the builtin name.
  25473. *
  25474. * @param {NodeBuilder} builder - The current node builder.
  25475. * @return {string} The builtin name.
  25476. */
  25477. getBuiltinName( /*builder*/ ) {
  25478. return this._builtinName;
  25479. }
  25480. /**
  25481. * Whether the current node builder has the builtin or not.
  25482. *
  25483. * @param {NodeBuilder} builder - The current node builder.
  25484. * @return {boolean} Whether the builder has the builtin or not.
  25485. */
  25486. hasBuiltin( builder ) {
  25487. return builder.hasBuiltin( this._builtinName );
  25488. }
  25489. generate( builder, output ) {
  25490. const builtinName = this.getBuiltinName( builder );
  25491. const nodeType = this.getNodeType( builder );
  25492. if ( builder.shaderStage === 'compute' ) {
  25493. return builder.format( builtinName, nodeType, output );
  25494. } else {
  25495. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  25496. return builder.generateConst( nodeType );
  25497. }
  25498. }
  25499. serialize( data ) {
  25500. super.serialize( data );
  25501. data.global = this.global;
  25502. data._builtinName = this._builtinName;
  25503. }
  25504. deserialize( data ) {
  25505. super.deserialize( data );
  25506. this.global = data.global;
  25507. this._builtinName = data._builtinName;
  25508. }
  25509. }
  25510. /**
  25511. * TSL function for creating a compute builtin node.
  25512. *
  25513. * @tsl
  25514. * @function
  25515. * @param {string} name - The built-in name.
  25516. * @param {string} nodeType - The node type.
  25517. * @returns {ComputeBuiltinNode}
  25518. */
  25519. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  25520. /**
  25521. * Represents the number of workgroups dispatched by the compute shader.
  25522. * ```js
  25523. * // Run 512 invocations/threads with a workgroup size of 128.
  25524. * const computeFn = Fn(() => {
  25525. *
  25526. * // numWorkgroups.x = 4
  25527. * storageBuffer.element(0).assign(numWorkgroups.x)
  25528. *
  25529. * })().compute(512, [128]);
  25530. *
  25531. * // Run 512 invocations/threads with the default workgroup size of 64.
  25532. * const computeFn = Fn(() => {
  25533. *
  25534. * // numWorkgroups.x = 8
  25535. * storageBuffer.element(0).assign(numWorkgroups.x)
  25536. *
  25537. * })().compute(512);
  25538. * ```
  25539. *
  25540. * @tsl
  25541. * @type {ComputeBuiltinNode<uvec3>}
  25542. */
  25543. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  25544. /**
  25545. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  25546. * ```js
  25547. * // Execute 12 compute threads with a workgroup size of 3.
  25548. * const computeFn = Fn( () => {
  25549. *
  25550. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  25551. *
  25552. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  25553. *
  25554. * } ).Else( () => {
  25555. *
  25556. * storageBuffer.element( instanceIndex ).assign( 0 );
  25557. *
  25558. * } );
  25559. *
  25560. * } )().compute( 12, [ 3 ] );
  25561. *
  25562. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  25563. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  25564. * ```
  25565. *
  25566. * @tsl
  25567. * @type {ComputeBuiltinNode<uvec3>}
  25568. */
  25569. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  25570. /**
  25571. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  25572. *
  25573. * @tsl
  25574. * @type {ComputeBuiltinNode<uvec3>}
  25575. */
  25576. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  25577. /**
  25578. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  25579. *
  25580. * @tsl
  25581. * @type {ComputeBuiltinNode<uvec3>}
  25582. */
  25583. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  25584. /**
  25585. * A device dependent variable that exposes the size of the current invocation's subgroup.
  25586. *
  25587. * @tsl
  25588. * @type {ComputeBuiltinNode<uint>}
  25589. */
  25590. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  25591. /**
  25592. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  25593. *
  25594. * This node can only be used with a WebGPU backend.
  25595. *
  25596. * @augments Node
  25597. */
  25598. class BarrierNode extends Node {
  25599. /**
  25600. * Constructs a new barrier node.
  25601. *
  25602. * @param {string} scope - The scope defines the behavior of the node.
  25603. */
  25604. constructor( scope ) {
  25605. super();
  25606. this.scope = scope;
  25607. }
  25608. generate( builder ) {
  25609. const { scope } = this;
  25610. const { renderer } = builder;
  25611. if ( renderer.backend.isWebGLBackend === true ) {
  25612. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  25613. } else {
  25614. builder.addLineFlowCode( `${scope}Barrier()`, this );
  25615. }
  25616. }
  25617. }
  25618. /**
  25619. * TSL function for creating a barrier node.
  25620. *
  25621. * @tsl
  25622. * @function
  25623. * @param {string} scope - The scope defines the behavior of the node..
  25624. * @returns {BarrierNode}
  25625. */
  25626. const barrier = nodeProxy( BarrierNode );
  25627. /**
  25628. * TSL function for creating a workgroup barrier. All compute shader
  25629. * invocations must wait for each invocation within a workgroup to
  25630. * complete before the barrier can be surpassed.
  25631. *
  25632. * @tsl
  25633. * @function
  25634. * @returns {BarrierNode}
  25635. */
  25636. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  25637. /**
  25638. * TSL function for creating a storage barrier. All invocations must
  25639. * wait for each access to variables within the 'storage' address space
  25640. * to complete before the barrier can be passed.
  25641. *
  25642. * @tsl
  25643. * @function
  25644. * @returns {BarrierNode}
  25645. */
  25646. const storageBarrier = () => barrier( 'storage' ).append();
  25647. /**
  25648. * TSL function for creating a texture barrier. All invocations must
  25649. * wait for each access to variables within the 'texture' address space
  25650. * to complete before the barrier can be passed.
  25651. *
  25652. * @tsl
  25653. * @function
  25654. * @returns {BarrierNode}
  25655. */
  25656. const textureBarrier = () => barrier( 'texture' ).append();
  25657. /**
  25658. * Represents an element of a 'workgroup' scoped buffer.
  25659. *
  25660. * @augments ArrayElementNode
  25661. */
  25662. class WorkgroupInfoElementNode extends ArrayElementNode {
  25663. /**
  25664. * Constructs a new workgroup info element node.
  25665. *
  25666. * @param {Node} workgroupInfoNode - The workgroup info node.
  25667. * @param {Node} indexNode - The index node that defines the element access.
  25668. */
  25669. constructor( workgroupInfoNode, indexNode ) {
  25670. super( workgroupInfoNode, indexNode );
  25671. /**
  25672. * This flag can be used for type testing.
  25673. *
  25674. * @type {boolean}
  25675. * @readonly
  25676. * @default true
  25677. */
  25678. this.isWorkgroupInfoElementNode = true;
  25679. }
  25680. generate( builder, output ) {
  25681. let snippet;
  25682. const isAssignContext = builder.context.assign;
  25683. snippet = super.generate( builder );
  25684. if ( isAssignContext !== true ) {
  25685. const type = this.getNodeType( builder );
  25686. snippet = builder.format( snippet, type, output );
  25687. }
  25688. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  25689. return snippet;
  25690. }
  25691. }
  25692. /**
  25693. * A node allowing the user to create a 'workgroup' scoped buffer within the
  25694. * context of a compute shader. Typically, workgroup scoped buffers are
  25695. * created to hold data that is transferred from a global storage scope into
  25696. * a local workgroup scope. For invocations within a workgroup, data
  25697. * access speeds on 'workgroup' scoped buffers can be significantly faster
  25698. * than similar access operations on globally accessible storage buffers.
  25699. *
  25700. * This node can only be used with a WebGPU backend.
  25701. *
  25702. * @augments Node
  25703. */
  25704. class WorkgroupInfoNode extends Node {
  25705. /**
  25706. * Constructs a new buffer scoped to type scope.
  25707. *
  25708. * @param {string} scope - TODO.
  25709. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  25710. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  25711. */
  25712. constructor( scope, bufferType, bufferCount = 0 ) {
  25713. super( bufferType );
  25714. /**
  25715. * The buffer type.
  25716. *
  25717. * @type {string}
  25718. */
  25719. this.bufferType = bufferType;
  25720. /**
  25721. * The buffer count.
  25722. *
  25723. * @type {number}
  25724. * @default 0
  25725. */
  25726. this.bufferCount = bufferCount;
  25727. /**
  25728. * This flag can be used for type testing.
  25729. *
  25730. * @type {boolean}
  25731. * @readonly
  25732. * @default true
  25733. */
  25734. this.isWorkgroupInfoNode = true;
  25735. /**
  25736. * The data type of the array buffer.
  25737. *
  25738. * @type {string}
  25739. */
  25740. this.elementType = bufferType;
  25741. /**
  25742. * TODO.
  25743. *
  25744. * @type {string}
  25745. */
  25746. this.scope = scope;
  25747. }
  25748. /**
  25749. * Sets the name/label of this node.
  25750. *
  25751. * @param {string} name - The name to set.
  25752. * @return {WorkgroupInfoNode} A reference to this node.
  25753. */
  25754. label( name ) {
  25755. this.name = name;
  25756. return this;
  25757. }
  25758. /**
  25759. * Sets the scope of this node.
  25760. *
  25761. * @param {string} scope - The scope to set.
  25762. * @return {WorkgroupInfoNode} A reference to this node.
  25763. */
  25764. setScope( scope ) {
  25765. this.scope = scope;
  25766. return this;
  25767. }
  25768. /**
  25769. * The data type of the array buffer.
  25770. *
  25771. * @return {string} The element type.
  25772. */
  25773. getElementType() {
  25774. return this.elementType;
  25775. }
  25776. /**
  25777. * Overwrites the default implementation since the input type
  25778. * is inferred from the scope.
  25779. *
  25780. * @param {NodeBuilder} builder - The current node builder.
  25781. * @return {string} The input type.
  25782. */
  25783. getInputType( /*builder*/ ) {
  25784. return `${this.scope}Array`;
  25785. }
  25786. /**
  25787. * This method can be used to access elements via an index node.
  25788. *
  25789. * @param {IndexNode} indexNode - indexNode.
  25790. * @return {WorkgroupInfoElementNode} A reference to an element.
  25791. */
  25792. element( indexNode ) {
  25793. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  25794. }
  25795. generate( builder ) {
  25796. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  25797. }
  25798. }
  25799. /**
  25800. * TSL function for creating a workgroup info node.
  25801. * Creates a new 'workgroup' scoped array buffer.
  25802. *
  25803. * @tsl
  25804. * @function
  25805. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  25806. * @param {number} [count=0] - The number of elements in the buffer.
  25807. * @returns {WorkgroupInfoNode}
  25808. */
  25809. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  25810. /**
  25811. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  25812. * within a shader. In an atomic function, any modification to an atomic variable will
  25813. * occur as an indivisible step with a defined order relative to other modifications.
  25814. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  25815. * atomic operations will not interfere with each other.
  25816. *
  25817. * This node can only be used with a WebGPU backend.
  25818. *
  25819. * @augments TempNode
  25820. */
  25821. class AtomicFunctionNode extends TempNode {
  25822. static get type() {
  25823. return 'AtomicFunctionNode';
  25824. }
  25825. /**
  25826. * Constructs a new atomic function node.
  25827. *
  25828. * @param {string} method - The signature of the atomic function to construct.
  25829. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25830. * @param {Node} valueNode - The value that mutates the atomic variable.
  25831. */
  25832. constructor( method, pointerNode, valueNode ) {
  25833. super( 'uint' );
  25834. /**
  25835. * The signature of the atomic function to construct.
  25836. *
  25837. * @type {string}
  25838. */
  25839. this.method = method;
  25840. /**
  25841. * An atomic variable or element of an atomic buffer.
  25842. *
  25843. * @type {Node}
  25844. */
  25845. this.pointerNode = pointerNode;
  25846. /**
  25847. * A value that modifies the atomic variable.
  25848. *
  25849. * @type {Node}
  25850. */
  25851. this.valueNode = valueNode;
  25852. }
  25853. /**
  25854. * Overwrites the default implementation to return the type of
  25855. * the pointer node.
  25856. *
  25857. * @param {NodeBuilder} builder - The current node builder.
  25858. * @return {string} The input type.
  25859. */
  25860. getInputType( builder ) {
  25861. return this.pointerNode.getNodeType( builder );
  25862. }
  25863. /**
  25864. * Overwritten since the node type is inferred from the input type.
  25865. *
  25866. * @param {NodeBuilder} builder - The current node builder.
  25867. * @return {string} The node type.
  25868. */
  25869. getNodeType( builder ) {
  25870. return this.getInputType( builder );
  25871. }
  25872. generate( builder ) {
  25873. const method = this.method;
  25874. const type = this.getNodeType( builder );
  25875. const inputType = this.getInputType( builder );
  25876. const a = this.pointerNode;
  25877. const b = this.valueNode;
  25878. const params = [];
  25879. params.push( `&${ a.build( builder, inputType ) }` );
  25880. if ( b !== null ) {
  25881. params.push( b.build( builder, inputType ) );
  25882. }
  25883. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  25884. if ( b !== null ) {
  25885. builder.addLineFlowCode( methodSnippet, this );
  25886. }
  25887. return methodSnippet;
  25888. }
  25889. }
  25890. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  25891. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  25892. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  25893. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  25894. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  25895. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  25896. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  25897. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  25898. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  25899. /**
  25900. * TSL function for creating an atomic function node.
  25901. *
  25902. * @tsl
  25903. * @function
  25904. * @param {string} method - The signature of the atomic function to construct.
  25905. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25906. * @param {Node} valueNode - The value that mutates the atomic variable.
  25907. * @returns {AtomicFunctionNode}
  25908. */
  25909. const atomicNode = nodeProxy( AtomicFunctionNode );
  25910. /**
  25911. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  25912. *
  25913. * @tsl
  25914. * @function
  25915. * @param {string} method - The signature of the atomic function to construct.
  25916. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25917. * @param {Node} valueNode - The value that mutates the atomic variable.
  25918. * @returns {AtomicFunctionNode}
  25919. */
  25920. const atomicFunc = ( method, pointerNode, valueNode ) => {
  25921. const node = atomicNode( method, pointerNode, valueNode );
  25922. node.append();
  25923. return node;
  25924. };
  25925. /**
  25926. * Loads the value stored in the atomic variable.
  25927. *
  25928. * @tsl
  25929. * @function
  25930. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25931. * @returns {AtomicFunctionNode}
  25932. */
  25933. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  25934. /**
  25935. * Stores a value in the atomic variable.
  25936. *
  25937. * @tsl
  25938. * @function
  25939. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25940. * @param {Node} valueNode - The value that mutates the atomic variable.
  25941. * @returns {AtomicFunctionNode}
  25942. */
  25943. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  25944. /**
  25945. * Increments the value stored in the atomic variable.
  25946. *
  25947. * @tsl
  25948. * @function
  25949. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25950. * @param {Node} valueNode - The value that mutates the atomic variable.
  25951. * @returns {AtomicFunctionNode}
  25952. */
  25953. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  25954. /**
  25955. * Decrements the value stored in the atomic variable.
  25956. *
  25957. * @tsl
  25958. * @function
  25959. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25960. * @param {Node} valueNode - The value that mutates the atomic variable.
  25961. * @returns {AtomicFunctionNode}
  25962. */
  25963. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  25964. /**
  25965. * Stores in an atomic variable the maximum between its current value and a parameter.
  25966. *
  25967. * @tsl
  25968. * @function
  25969. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25970. * @param {Node} valueNode - The value that mutates the atomic variable.
  25971. * @returns {AtomicFunctionNode}
  25972. */
  25973. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  25974. /**
  25975. * Stores in an atomic variable the minimum between its current value and a parameter.
  25976. *
  25977. * @tsl
  25978. * @function
  25979. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25980. * @param {Node} valueNode - The value that mutates the atomic variable.
  25981. * @returns {AtomicFunctionNode}
  25982. */
  25983. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  25984. /**
  25985. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  25986. *
  25987. * @tsl
  25988. * @function
  25989. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25990. * @param {Node} valueNode - The value that mutates the atomic variable.
  25991. * @returns {AtomicFunctionNode}
  25992. */
  25993. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  25994. /**
  25995. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  25996. *
  25997. * @tsl
  25998. * @function
  25999. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26000. * @param {Node} valueNode - The value that mutates the atomic variable.
  26001. * @returns {AtomicFunctionNode}
  26002. */
  26003. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  26004. /**
  26005. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  26006. *
  26007. * @tsl
  26008. * @function
  26009. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26010. * @param {Node} valueNode - The value that mutates the atomic variable.
  26011. * @returns {AtomicFunctionNode}
  26012. */
  26013. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  26014. let uniformsLib;
  26015. function getLightData( light ) {
  26016. uniformsLib = uniformsLib || new WeakMap();
  26017. let uniforms = uniformsLib.get( light );
  26018. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  26019. return uniforms;
  26020. }
  26021. /**
  26022. * TSL function for getting a shadow matrix uniform node for the given light.
  26023. *
  26024. * @tsl
  26025. * @function
  26026. * @param {Light} light -The light source.
  26027. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  26028. */
  26029. function lightShadowMatrix( light ) {
  26030. const data = getLightData( light );
  26031. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26032. if ( light.castShadow !== true ) {
  26033. light.shadow.updateMatrices( light );
  26034. }
  26035. return light.shadow.matrix;
  26036. } ) );
  26037. }
  26038. /**
  26039. * TSL function for getting projected uv coordinates for the given light.
  26040. * Relevant when using maps with spot lights.
  26041. *
  26042. * @tsl
  26043. * @function
  26044. * @param {Light} light -The light source.
  26045. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  26046. * @returns {Node<vec3>} The projected uvs.
  26047. */
  26048. function lightProjectionUV( light, position = positionWorld ) {
  26049. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  26050. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  26051. return projectionUV;
  26052. }
  26053. /**
  26054. * TSL function for getting the position in world space for the given light.
  26055. *
  26056. * @tsl
  26057. * @function
  26058. * @param {Light} light -The light source.
  26059. * @returns {UniformNode<vec3>} The light's position in world space.
  26060. */
  26061. function lightPosition( light ) {
  26062. const data = getLightData( light );
  26063. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  26064. }
  26065. /**
  26066. * TSL function for getting the light target position in world space for the given light.
  26067. *
  26068. * @tsl
  26069. * @function
  26070. * @param {Light} light -The light source.
  26071. * @returns {UniformNode<vec3>} The light target position in world space.
  26072. */
  26073. function lightTargetPosition( light ) {
  26074. const data = getLightData( light );
  26075. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  26076. }
  26077. /**
  26078. * TSL function for getting the position in view space for the given light.
  26079. *
  26080. * @tsl
  26081. * @function
  26082. * @param {Light} light - The light source.
  26083. * @returns {UniformNode<vec3>} The light's position in view space.
  26084. */
  26085. function lightViewPosition( light ) {
  26086. const data = getLightData( light );
  26087. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  26088. self.value = self.value || new Vector3();
  26089. self.value.setFromMatrixPosition( light.matrixWorld );
  26090. self.value.applyMatrix4( camera.matrixWorldInverse );
  26091. } ) );
  26092. }
  26093. /**
  26094. * TSL function for getting the light target direction for the given light.
  26095. *
  26096. * @tsl
  26097. * @function
  26098. * @param {Light} light -The light source.
  26099. * @returns {Node<vec3>} The light's target direction.
  26100. */
  26101. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  26102. const sortLights = ( lights ) => {
  26103. return lights.sort( ( a, b ) => a.id - b.id );
  26104. };
  26105. const getLightNodeById = ( id, lightNodes ) => {
  26106. for ( const lightNode of lightNodes ) {
  26107. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26108. return lightNode;
  26109. }
  26110. }
  26111. return null;
  26112. };
  26113. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26114. /**
  26115. * This node represents the scene's lighting and manages the lighting model's life cycle
  26116. * for the current build 3D object. It is responsible for computing the total outgoing
  26117. * light in a given lighting context.
  26118. *
  26119. * @augments Node
  26120. */
  26121. class LightsNode extends Node {
  26122. static get type() {
  26123. return 'LightsNode';
  26124. }
  26125. /**
  26126. * Constructs a new lights node.
  26127. */
  26128. constructor() {
  26129. super( 'vec3' );
  26130. /**
  26131. * A node representing the total diffuse light.
  26132. *
  26133. * @type {Node<vec3>}
  26134. */
  26135. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  26136. /**
  26137. * A node representing the total specular light.
  26138. *
  26139. * @type {Node<vec3>}
  26140. */
  26141. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  26142. /**
  26143. * A node representing the outgoing light.
  26144. *
  26145. * @type {Node<vec3>}
  26146. */
  26147. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  26148. /**
  26149. * An array representing the lights in the scene.
  26150. *
  26151. * @private
  26152. * @type {Array<Light>}
  26153. */
  26154. this._lights = [];
  26155. /**
  26156. * For each light in the scene, this node will create a
  26157. * corresponding light node.
  26158. *
  26159. * @private
  26160. * @type {?Array<LightingNode>}
  26161. * @default null
  26162. */
  26163. this._lightNodes = null;
  26164. /**
  26165. * A hash for identifying the current light nodes setup.
  26166. *
  26167. * @private
  26168. * @type {?string}
  26169. * @default null
  26170. */
  26171. this._lightNodesHash = null;
  26172. /**
  26173. * `LightsNode` sets this property to `true` by default.
  26174. *
  26175. * @type {boolean}
  26176. * @default true
  26177. */
  26178. this.global = true;
  26179. }
  26180. /**
  26181. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  26182. * light IDs into the cache key.
  26183. *
  26184. * @return {number} The custom cache key.
  26185. */
  26186. customCacheKey() {
  26187. const lightIDs = [];
  26188. const lights = this._lights;
  26189. for ( let i = 0; i < lights.length; i ++ ) {
  26190. lightIDs.push( lights[ i ].id );
  26191. }
  26192. return hashArray( lightIDs );
  26193. }
  26194. /**
  26195. * Computes a hash value for identifying the current light nodes setup.
  26196. *
  26197. * @param {NodeBuilder} builder - A reference to the current node builder.
  26198. * @return {string} The computed hash.
  26199. */
  26200. getHash( builder ) {
  26201. if ( this._lightNodesHash === null ) {
  26202. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26203. const hash = [];
  26204. for ( const lightNode of this._lightNodes ) {
  26205. hash.push( lightNode.getSelf().getHash() );
  26206. }
  26207. this._lightNodesHash = 'lights-' + hash.join( ',' );
  26208. }
  26209. return this._lightNodesHash;
  26210. }
  26211. analyze( builder ) {
  26212. const properties = builder.getDataFromNode( this );
  26213. for ( const node of properties.nodes ) {
  26214. node.build( builder );
  26215. }
  26216. }
  26217. /**
  26218. * Creates lighting nodes for each scene light. This makes it possible to further
  26219. * process lights in the node system.
  26220. *
  26221. * @param {NodeBuilder} builder - A reference to the current node builder.
  26222. */
  26223. setupLightsNode( builder ) {
  26224. const lightNodes = [];
  26225. const previousLightNodes = this._lightNodes;
  26226. const lights = sortLights( this._lights );
  26227. const nodeLibrary = builder.renderer.library;
  26228. for ( const light of lights ) {
  26229. if ( light.isNode ) {
  26230. lightNodes.push( nodeObject( light ) );
  26231. } else {
  26232. let lightNode = null;
  26233. if ( previousLightNodes !== null ) {
  26234. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  26235. }
  26236. if ( lightNode === null ) {
  26237. // find the corresponding node type for a given light
  26238. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  26239. if ( lightNodeClass === null ) {
  26240. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  26241. continue;
  26242. }
  26243. let lightNode = null;
  26244. if ( ! _lightsNodeRef.has( light ) ) {
  26245. lightNode = nodeObject( new lightNodeClass( light ) );
  26246. _lightsNodeRef.set( light, lightNode );
  26247. } else {
  26248. lightNode = _lightsNodeRef.get( light );
  26249. }
  26250. lightNodes.push( lightNode );
  26251. }
  26252. }
  26253. }
  26254. this._lightNodes = lightNodes;
  26255. }
  26256. /**
  26257. * Sets up a direct light in the lighting model.
  26258. *
  26259. * @param {Object} builder - The builder object containing the context and stack.
  26260. * @param {Object} lightNode - The light node.
  26261. * @param {Object} lightData - The light object containing color and direction properties.
  26262. */
  26263. setupDirectLight( builder, lightNode, lightData ) {
  26264. const { lightingModel, reflectedLight } = builder.context;
  26265. lightingModel.direct( {
  26266. ...lightData,
  26267. lightNode,
  26268. reflectedLight
  26269. }, builder );
  26270. }
  26271. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  26272. const { lightingModel, reflectedLight } = builder.context;
  26273. lightingModel.directRectArea( {
  26274. ...lightData,
  26275. lightNode,
  26276. reflectedLight
  26277. }, builder );
  26278. }
  26279. /**
  26280. * Setups the internal lights by building all respective
  26281. * light nodes.
  26282. *
  26283. * @param {NodeBuilder} builder - A reference to the current node builder.
  26284. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  26285. */
  26286. setupLights( builder, lightNodes ) {
  26287. for ( const lightNode of lightNodes ) {
  26288. lightNode.build( builder );
  26289. }
  26290. }
  26291. getLightNodes( builder ) {
  26292. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26293. return this._lightNodes;
  26294. }
  26295. /**
  26296. * The implementation makes sure that for each light in the scene
  26297. * there is a corresponding light node. By building the light nodes
  26298. * and evaluating the lighting model the outgoing light is computed.
  26299. *
  26300. * @param {NodeBuilder} builder - A reference to the current node builder.
  26301. * @return {Node<vec3>} A node representing the outgoing light.
  26302. */
  26303. setup( builder ) {
  26304. const currentLightsNode = builder.lightsNode;
  26305. builder.lightsNode = this;
  26306. //
  26307. let outgoingLightNode = this.outgoingLightNode;
  26308. const context = builder.context;
  26309. const lightingModel = context.lightingModel;
  26310. const properties = builder.getDataFromNode( this );
  26311. if ( lightingModel ) {
  26312. const { totalDiffuseNode, totalSpecularNode } = this;
  26313. context.outgoingLight = outgoingLightNode;
  26314. const stack = builder.addStack();
  26315. //
  26316. properties.nodes = stack.nodes;
  26317. //
  26318. lightingModel.start( builder );
  26319. //
  26320. const { backdrop, backdropAlpha } = context;
  26321. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26322. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26323. if ( backdrop !== null ) {
  26324. if ( backdropAlpha !== null ) {
  26325. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26326. } else {
  26327. totalDiffuse = vec3( backdrop );
  26328. }
  26329. context.material.transparent = true;
  26330. }
  26331. totalDiffuseNode.assign( totalDiffuse );
  26332. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26333. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26334. //
  26335. lightingModel.finish( builder );
  26336. //
  26337. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26338. } else {
  26339. properties.nodes = [];
  26340. }
  26341. //
  26342. builder.lightsNode = currentLightsNode;
  26343. return outgoingLightNode;
  26344. }
  26345. /**
  26346. * Configures this node with an array of lights.
  26347. *
  26348. * @param {Array<Light>} lights - An array of lights.
  26349. * @return {LightsNode} A reference to this node.
  26350. */
  26351. setLights( lights ) {
  26352. this._lights = lights;
  26353. this._lightNodes = null;
  26354. this._lightNodesHash = null;
  26355. return this;
  26356. }
  26357. /**
  26358. * Returns an array of the scene's lights.
  26359. *
  26360. * @return {Array<Light>} The scene's lights.
  26361. */
  26362. getLights() {
  26363. return this._lights;
  26364. }
  26365. /**
  26366. * Whether the scene has lights or not.
  26367. *
  26368. * @type {boolean}
  26369. */
  26370. get hasLights() {
  26371. return this._lights.length > 0;
  26372. }
  26373. }
  26374. /**
  26375. * TSL function for creating an instance of `LightsNode` and configuring
  26376. * it with the given array of lights.
  26377. *
  26378. * @tsl
  26379. * @function
  26380. * @param {Array<Light>} lights - An array of lights.
  26381. * @return {LightsNode} The created lights node.
  26382. */
  26383. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  26384. /**
  26385. * Base class for all shadow nodes.
  26386. *
  26387. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  26388. * Lighting nodes might share the same shadow node type or use specific ones depending on
  26389. * their requirements.
  26390. *
  26391. * @augments Node
  26392. */
  26393. class ShadowBaseNode extends Node {
  26394. static get type() {
  26395. return 'ShadowBaseNode';
  26396. }
  26397. /**
  26398. * Constructs a new shadow base node.
  26399. *
  26400. * @param {Light} light - The shadow casting light.
  26401. */
  26402. constructor( light ) {
  26403. super();
  26404. /**
  26405. * The shadow casting light.
  26406. *
  26407. * @type {Light}
  26408. */
  26409. this.light = light;
  26410. /**
  26411. * Overwritten since shadows are updated by default per render.
  26412. *
  26413. * @type {string}
  26414. * @default 'render'
  26415. */
  26416. this.updateBeforeType = NodeUpdateType.RENDER;
  26417. /**
  26418. * This flag can be used for type testing.
  26419. *
  26420. * @type {boolean}
  26421. * @readonly
  26422. * @default true
  26423. */
  26424. this.isShadowBaseNode = true;
  26425. }
  26426. /**
  26427. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  26428. *
  26429. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  26430. */
  26431. setupShadowPosition( { context, material } ) {
  26432. // Use assign inside an Fn()
  26433. shadowPositionWorld.assign( material.shadowPositionNode || context.shadowPositionWorld || positionWorld );
  26434. }
  26435. /**
  26436. * Can be called when the shadow isn't required anymore. That can happen when
  26437. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  26438. * to `false`.
  26439. */
  26440. dispose() {
  26441. this.updateBeforeType = NodeUpdateType.NONE;
  26442. }
  26443. }
  26444. /**
  26445. * TSL object that represents the vertex position in world space during the shadow pass.
  26446. *
  26447. * @tsl
  26448. * @type {Node<vec3>}
  26449. */
  26450. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  26451. /**
  26452. * Saves the state of the given renderer and stores it into the given state object.
  26453. *
  26454. * If not state object is provided, the function creates one.
  26455. *
  26456. * @function
  26457. * @param {Renderer} renderer - The renderer.
  26458. * @param {Object} [state={}] - The state.
  26459. * @return {Object} The state.
  26460. */
  26461. function saveRendererState( renderer, state = {} ) {
  26462. state.toneMapping = renderer.toneMapping;
  26463. state.toneMappingExposure = renderer.toneMappingExposure;
  26464. state.outputColorSpace = renderer.outputColorSpace;
  26465. state.renderTarget = renderer.getRenderTarget();
  26466. state.activeCubeFace = renderer.getActiveCubeFace();
  26467. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  26468. state.renderObjectFunction = renderer.getRenderObjectFunction();
  26469. state.pixelRatio = renderer.getPixelRatio();
  26470. state.mrt = renderer.getMRT();
  26471. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  26472. state.clearAlpha = renderer.getClearAlpha();
  26473. state.autoClear = renderer.autoClear;
  26474. state.scissorTest = renderer.getScissorTest();
  26475. return state;
  26476. }
  26477. /**
  26478. * Saves the state of the given renderer and stores it into the given state object.
  26479. * Besides, the function also resets the state of the renderer to its default values.
  26480. *
  26481. * If not state object is provided, the function creates one.
  26482. *
  26483. * @function
  26484. * @param {Renderer} renderer - The renderer.
  26485. * @param {Object} [state={}] - The state.
  26486. * @return {Object} The state.
  26487. */
  26488. function resetRendererState( renderer, state ) {
  26489. state = saveRendererState( renderer, state );
  26490. renderer.setMRT( null );
  26491. renderer.setRenderObjectFunction( null );
  26492. renderer.setClearColor( 0x000000, 1 );
  26493. renderer.autoClear = true;
  26494. return state;
  26495. }
  26496. /**
  26497. * Restores the state of the given renderer from the given state object.
  26498. *
  26499. * @function
  26500. * @param {Renderer} renderer - The renderer.
  26501. * @param {Object} state - The state to restore.
  26502. */
  26503. function restoreRendererState( renderer, state ) {
  26504. renderer.toneMapping = state.toneMapping;
  26505. renderer.toneMappingExposure = state.toneMappingExposure;
  26506. renderer.outputColorSpace = state.outputColorSpace;
  26507. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  26508. renderer.setRenderObjectFunction( state.renderObjectFunction );
  26509. renderer.setPixelRatio( state.pixelRatio );
  26510. renderer.setMRT( state.mrt );
  26511. renderer.setClearColor( state.clearColor, state.clearAlpha );
  26512. renderer.autoClear = state.autoClear;
  26513. renderer.setScissorTest( state.scissorTest );
  26514. }
  26515. /**
  26516. * Saves the state of the given scene and stores it into the given state object.
  26517. *
  26518. * If not state object is provided, the function creates one.
  26519. *
  26520. * @function
  26521. * @param {Scene} scene - The scene.
  26522. * @param {Object} [state={}] - The state.
  26523. * @return {Object} The state.
  26524. */
  26525. function saveSceneState( scene, state = {} ) {
  26526. state.background = scene.background;
  26527. state.backgroundNode = scene.backgroundNode;
  26528. state.overrideMaterial = scene.overrideMaterial;
  26529. return state;
  26530. }
  26531. /**
  26532. * Saves the state of the given scene and stores it into the given state object.
  26533. * Besides, the function also resets the state of the scene to its default values.
  26534. *
  26535. * If not state object is provided, the function creates one.
  26536. *
  26537. * @function
  26538. * @param {Scene} scene - The scene.
  26539. * @param {Object} [state={}] - The state.
  26540. * @return {Object} The state.
  26541. */
  26542. function resetSceneState( scene, state ) {
  26543. state = saveSceneState( scene, state );
  26544. scene.background = null;
  26545. scene.backgroundNode = null;
  26546. scene.overrideMaterial = null;
  26547. return state;
  26548. }
  26549. /**
  26550. * Restores the state of the given scene from the given state object.
  26551. *
  26552. * @function
  26553. * @param {Scene} scene - The scene.
  26554. * @param {Object} state - The state to restore.
  26555. */
  26556. function restoreSceneState( scene, state ) {
  26557. scene.background = state.background;
  26558. scene.backgroundNode = state.backgroundNode;
  26559. scene.overrideMaterial = state.overrideMaterial;
  26560. }
  26561. /**
  26562. * Saves the state of the given renderer and scene and stores it into the given state object.
  26563. *
  26564. * If not state object is provided, the function creates one.
  26565. *
  26566. * @function
  26567. * @param {Renderer} renderer - The renderer.
  26568. * @param {Scene} scene - The scene.
  26569. * @param {Object} [state={}] - The state.
  26570. * @return {Object} The state.
  26571. */
  26572. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  26573. state = saveRendererState( renderer, state );
  26574. state = saveSceneState( scene, state );
  26575. return state;
  26576. }
  26577. /**
  26578. * Saves the state of the given renderer and scene and stores it into the given state object.
  26579. * Besides, the function also resets the state of the renderer and scene to its default values.
  26580. *
  26581. * If not state object is provided, the function creates one.
  26582. *
  26583. * @function
  26584. * @param {Renderer} renderer - The renderer.
  26585. * @param {Scene} scene - The scene.
  26586. * @param {Object} [state={}] - The state.
  26587. * @return {Object} The state.
  26588. */
  26589. function resetRendererAndSceneState( renderer, scene, state ) {
  26590. state = resetRendererState( renderer, state );
  26591. state = resetSceneState( scene, state );
  26592. return state;
  26593. }
  26594. /**
  26595. * Restores the state of the given renderer and scene from the given state object.
  26596. *
  26597. * @function
  26598. * @param {Renderer} renderer - The renderer.
  26599. * @param {Scene} scene - The scene.
  26600. * @param {Object} state - The state to restore.
  26601. */
  26602. function restoreRendererAndSceneState( renderer, scene, state ) {
  26603. restoreRendererState( renderer, state );
  26604. restoreSceneState( scene, state );
  26605. }
  26606. var RendererUtils = /*#__PURE__*/Object.freeze({
  26607. __proto__: null,
  26608. resetRendererAndSceneState: resetRendererAndSceneState,
  26609. resetRendererState: resetRendererState,
  26610. resetSceneState: resetSceneState,
  26611. restoreRendererAndSceneState: restoreRendererAndSceneState,
  26612. restoreRendererState: restoreRendererState,
  26613. restoreSceneState: restoreSceneState,
  26614. saveRendererAndSceneState: saveRendererAndSceneState,
  26615. saveRendererState: saveRendererState,
  26616. saveSceneState: saveSceneState
  26617. });
  26618. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  26619. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  26620. let dist = positionWorld.sub( position ).length();
  26621. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  26622. dist = dist.saturate(); // clamp to [ 0, 1 ]
  26623. return dist;
  26624. } );
  26625. const linearShadowDistance = ( light ) => {
  26626. const camera = light.shadow.camera;
  26627. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  26628. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  26629. const referencePosition = objectPosition( light );
  26630. return linearDistance( referencePosition, nearDistance, farDistance );
  26631. };
  26632. const getShadowMaterial = ( light ) => {
  26633. let material = shadowMaterialLib.get( light );
  26634. if ( material === undefined ) {
  26635. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  26636. material = new NodeMaterial();
  26637. material.colorNode = vec4( 0, 0, 0, 1 );
  26638. material.depthNode = depthNode;
  26639. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  26640. material.name = 'ShadowMaterial';
  26641. material.fog = false;
  26642. shadowMaterialLib.set( light, material );
  26643. }
  26644. return material;
  26645. };
  26646. /**
  26647. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  26648. * with a binary `[0,1]` result.
  26649. *
  26650. * @method
  26651. * @param {Object} inputs - The input parameter object.
  26652. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26653. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26654. * @return {Node<float>} The filtering result.
  26655. */
  26656. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  26657. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  26658. } );
  26659. /**
  26660. * A shadow filtering function performing PCF filtering.
  26661. *
  26662. * @method
  26663. * @param {Object} inputs - The input parameter object.
  26664. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26665. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26666. * @param {LightShadow} inputs.shadow - The light shadow.
  26667. * @return {Node<float>} The filtering result.
  26668. */
  26669. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  26670. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  26671. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  26672. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  26673. const texelSize = vec2( 1 ).div( mapSize );
  26674. const dx0 = texelSize.x.negate().mul( radius );
  26675. const dy0 = texelSize.y.negate().mul( radius );
  26676. const dx1 = texelSize.x.mul( radius );
  26677. const dy1 = texelSize.y.mul( radius );
  26678. const dx2 = dx0.div( 2 );
  26679. const dy2 = dy0.div( 2 );
  26680. const dx3 = dx1.div( 2 );
  26681. const dy3 = dy1.div( 2 );
  26682. return add(
  26683. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  26684. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  26685. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  26686. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  26687. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  26688. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  26689. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  26690. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  26691. depthCompare( shadowCoord.xy, shadowCoord.z ),
  26692. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  26693. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  26694. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  26695. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  26696. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  26697. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  26698. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  26699. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  26700. ).mul( 1 / 17 );
  26701. } );
  26702. /**
  26703. * A shadow filtering function performing PCF soft filtering.
  26704. *
  26705. * @method
  26706. * @param {Object} inputs - The input parameter object.
  26707. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26708. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26709. * @param {LightShadow} inputs.shadow - The light shadow.
  26710. * @return {Node<float>} The filtering result.
  26711. */
  26712. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  26713. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  26714. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  26715. const texelSize = vec2( 1 ).div( mapSize );
  26716. const dx = texelSize.x;
  26717. const dy = texelSize.y;
  26718. const uv = shadowCoord.xy;
  26719. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  26720. uv.subAssign( f.mul( texelSize ) );
  26721. return add(
  26722. depthCompare( uv, shadowCoord.z ),
  26723. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  26724. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  26725. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  26726. mix(
  26727. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  26728. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  26729. f.x
  26730. ),
  26731. mix(
  26732. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  26733. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  26734. f.x
  26735. ),
  26736. mix(
  26737. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  26738. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  26739. f.y
  26740. ),
  26741. mix(
  26742. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  26743. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  26744. f.y
  26745. ),
  26746. mix(
  26747. mix(
  26748. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  26749. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  26750. f.x
  26751. ),
  26752. mix(
  26753. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  26754. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  26755. f.x
  26756. ),
  26757. f.y
  26758. )
  26759. ).mul( 1 / 9 );
  26760. } );
  26761. /**
  26762. * A shadow filtering function performing VSM filtering.
  26763. *
  26764. * @method
  26765. * @param {Object} inputs - The input parameter object.
  26766. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26767. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26768. * @return {Node<float>} The filtering result.
  26769. */
  26770. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  26771. const occlusion = float( 1 ).toVar();
  26772. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  26773. const hardShadow = step( shadowCoord.z, distribution.x );
  26774. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  26775. const distance = shadowCoord.z.sub( distribution.x );
  26776. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  26777. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  26778. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  26779. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  26780. } );
  26781. return occlusion;
  26782. } );
  26783. /**
  26784. * Represents the shader code for the first VSM render pass.
  26785. *
  26786. * @method
  26787. * @param {Object} inputs - The input parameter object.
  26788. * @param {Node<float>} inputs.samples - The number of samples
  26789. * @param {Node<float>} inputs.radius - The radius.
  26790. * @param {Node<float>} inputs.size - The size.
  26791. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  26792. * @return {Node<vec2>} The VSM output.
  26793. */
  26794. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  26795. const mean = float( 0 ).toVar();
  26796. const squaredMean = float( 0 ).toVar();
  26797. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  26798. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  26799. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  26800. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  26801. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  26802. mean.addAssign( depth );
  26803. squaredMean.addAssign( depth.mul( depth ) );
  26804. } );
  26805. mean.divAssign( samples );
  26806. squaredMean.divAssign( samples );
  26807. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  26808. return vec2( mean, std_dev );
  26809. } );
  26810. /**
  26811. * Represents the shader code for the second VSM render pass.
  26812. *
  26813. * @method
  26814. * @param {Object} inputs - The input parameter object.
  26815. * @param {Node<float>} inputs.samples - The number of samples
  26816. * @param {Node<float>} inputs.radius - The radius.
  26817. * @param {Node<float>} inputs.size - The size.
  26818. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  26819. * @return {Node<vec2>} The VSM output.
  26820. */
  26821. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  26822. const mean = float( 0 ).toVar();
  26823. const squaredMean = float( 0 ).toVar();
  26824. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  26825. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  26826. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  26827. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  26828. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  26829. mean.addAssign( distribution.x );
  26830. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  26831. } );
  26832. mean.divAssign( samples );
  26833. squaredMean.divAssign( samples );
  26834. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  26835. return vec2( mean, std_dev );
  26836. } );
  26837. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  26838. //
  26839. let _rendererState;
  26840. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  26841. /**
  26842. * Represents the default shadow implementation for lighting nodes.
  26843. *
  26844. * @augments ShadowBaseNode
  26845. */
  26846. class ShadowNode extends ShadowBaseNode {
  26847. static get type() {
  26848. return 'ShadowNode';
  26849. }
  26850. /**
  26851. * Constructs a new shadow node.
  26852. *
  26853. * @param {Light} light - The shadow casting light.
  26854. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  26855. */
  26856. constructor( light, shadow = null ) {
  26857. super( light );
  26858. /**
  26859. * The light shadow which defines the properties light's
  26860. * shadow.
  26861. *
  26862. * @type {?LightShadow}
  26863. * @default null
  26864. */
  26865. this.shadow = shadow || light.shadow;
  26866. /**
  26867. * A reference to the shadow map which is a render target.
  26868. *
  26869. * @type {?RenderTarget}
  26870. * @default null
  26871. */
  26872. this.shadowMap = null;
  26873. /**
  26874. * Only relevant for VSM shadows. Render target for the
  26875. * first VSM render pass.
  26876. *
  26877. * @type {?RenderTarget}
  26878. * @default null
  26879. */
  26880. this.vsmShadowMapVertical = null;
  26881. /**
  26882. * Only relevant for VSM shadows. Render target for the
  26883. * second VSM render pass.
  26884. *
  26885. * @type {?RenderTarget}
  26886. * @default null
  26887. */
  26888. this.vsmShadowMapHorizontal = null;
  26889. /**
  26890. * Only relevant for VSM shadows. Node material which
  26891. * is used to render the first VSM pass.
  26892. *
  26893. * @type {?NodeMaterial}
  26894. * @default null
  26895. */
  26896. this.vsmMaterialVertical = null;
  26897. /**
  26898. * Only relevant for VSM shadows. Node material which
  26899. * is used to render the second VSM pass.
  26900. *
  26901. * @type {?NodeMaterial}
  26902. * @default null
  26903. */
  26904. this.vsmMaterialHorizontal = null;
  26905. /**
  26906. * A reference to the output node which defines the
  26907. * final result of this shadow node.
  26908. *
  26909. * @type {?Node}
  26910. * @private
  26911. * @default null
  26912. */
  26913. this._node = null;
  26914. this._cameraFrameId = new WeakMap();
  26915. /**
  26916. * This flag can be used for type testing.
  26917. *
  26918. * @type {boolean}
  26919. * @readonly
  26920. * @default true
  26921. */
  26922. this.isShadowNode = true;
  26923. }
  26924. /**
  26925. * Setups the shadow filtering.
  26926. *
  26927. * @param {NodeBuilder} builder - A reference to the current node builder.
  26928. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26929. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26930. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26931. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26932. * @param {LightShadow} inputs.shadow - The light shadow.
  26933. * @return {Node<float>} The result node of the shadow filtering.
  26934. */
  26935. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  26936. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  26937. .and( shadowCoord.x.lessThanEqual( 1 ) )
  26938. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  26939. .and( shadowCoord.y.lessThanEqual( 1 ) )
  26940. .and( shadowCoord.z.lessThanEqual( 1 ) );
  26941. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  26942. return frustumTest.select( shadowNode, float( 1 ) );
  26943. }
  26944. /**
  26945. * Setups the shadow coordinates.
  26946. *
  26947. * @param {NodeBuilder} builder - A reference to the current node builder.
  26948. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26949. * @return {Node<vec3>} The shadow coordinates.
  26950. */
  26951. setupShadowCoord( builder, shadowPosition ) {
  26952. const { shadow } = this;
  26953. const { renderer } = builder;
  26954. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  26955. let shadowCoord = shadowPosition;
  26956. let coordZ;
  26957. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  26958. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  26959. coordZ = shadowCoord.z;
  26960. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26961. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  26962. }
  26963. } else {
  26964. const w = shadowCoord.w;
  26965. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  26966. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  26967. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  26968. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  26969. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  26970. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  26971. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  26972. }
  26973. shadowCoord = vec3(
  26974. shadowCoord.x,
  26975. shadowCoord.y.oneMinus(), // follow webgpu standards
  26976. coordZ.add( bias )
  26977. );
  26978. return shadowCoord;
  26979. }
  26980. /**
  26981. * Returns the shadow filtering function for the given shadow type.
  26982. *
  26983. * @param {number} type - The shadow type.
  26984. * @return {Function} The filtering function.
  26985. */
  26986. getShadowFilterFn( type ) {
  26987. return _shadowFilterLib[ type ];
  26988. }
  26989. /**
  26990. * Setups the shadow output node.
  26991. *
  26992. * @param {NodeBuilder} builder - A reference to the current node builder.
  26993. * @return {Node<vec3>} The shadow output node.
  26994. */
  26995. setupShadow( builder ) {
  26996. const { renderer } = builder;
  26997. const { light, shadow } = this;
  26998. const shadowMapType = renderer.shadowMap.type;
  26999. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  27000. depthTexture.compareFunction = LessCompare;
  27001. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  27002. shadowMap.depthTexture = depthTexture;
  27003. shadow.camera.updateProjectionMatrix();
  27004. // VSM
  27005. if ( shadowMapType === VSMShadowMap ) {
  27006. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  27007. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  27008. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  27009. const shadowPassVertical = texture( depthTexture );
  27010. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  27011. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  27012. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27013. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27014. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  27015. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  27016. material.name = 'VSMVertical';
  27017. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  27018. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  27019. material.name = 'VSMHorizontal';
  27020. }
  27021. //
  27022. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  27023. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  27024. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  27025. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  27026. //
  27027. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  27028. if ( filterFn === null ) {
  27029. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  27030. }
  27031. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  27032. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  27033. const shadowColor = texture( shadowMap.texture, shadowCoord );
  27034. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  27035. this.shadowMap = shadowMap;
  27036. this.shadow.map = shadowMap;
  27037. return shadowOutput;
  27038. }
  27039. /**
  27040. * The implementation performs the setup of the output node. An output is only
  27041. * produces if shadow mapping is globally enabled in the renderer.
  27042. *
  27043. * @param {NodeBuilder} builder - A reference to the current node builder.
  27044. * @return {ShaderCallNodeInternal} The output node.
  27045. */
  27046. setup( builder ) {
  27047. if ( builder.renderer.shadowMap.enabled === false ) return;
  27048. return Fn( () => {
  27049. let node = this._node;
  27050. this.setupShadowPosition( builder );
  27051. if ( node === null ) {
  27052. this._node = node = this.setupShadow( builder );
  27053. }
  27054. if ( builder.material.shadowNode ) { // @deprecated, r171
  27055. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  27056. }
  27057. if ( builder.material.receivedShadowNode ) {
  27058. node = builder.material.receivedShadowNode( node );
  27059. }
  27060. return node;
  27061. } )();
  27062. }
  27063. /**
  27064. * Renders the shadow. The logic of this function could be included
  27065. * into {@link ShadowNode#updateShadow} however more specialized shadow
  27066. * nodes might require a custom shadow map rendering. By having a
  27067. * dedicated method, it's easier to overwrite the default behavior.
  27068. *
  27069. * @param {NodeFrame} frame - A reference to the current node frame.
  27070. */
  27071. renderShadow( frame ) {
  27072. const { shadow, shadowMap, light } = this;
  27073. const { renderer, scene } = frame;
  27074. shadow.updateMatrices( light );
  27075. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  27076. renderer.render( scene, shadow.camera );
  27077. }
  27078. /**
  27079. * Updates the shadow.
  27080. *
  27081. * @param {NodeFrame} frame - A reference to the current node frame.
  27082. */
  27083. updateShadow( frame ) {
  27084. const { shadowMap, light, shadow } = this;
  27085. const { renderer, scene, camera } = frame;
  27086. const shadowType = renderer.shadowMap.type;
  27087. const depthVersion = shadowMap.depthTexture.version;
  27088. this._depthVersionCached = depthVersion;
  27089. shadow.camera.layers.mask = camera.layers.mask;
  27090. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27091. const currentMRT = renderer.getMRT();
  27092. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  27093. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  27094. scene.overrideMaterial = getShadowMaterial( light );
  27095. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  27096. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27097. if ( useVelocity ) {
  27098. getDataFromObject( object ).useVelocity = true;
  27099. }
  27100. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27101. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27102. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27103. }
  27104. } );
  27105. renderer.setRenderTarget( shadowMap );
  27106. this.renderShadow( frame );
  27107. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27108. // vsm blur pass
  27109. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  27110. this.vsmPass( renderer );
  27111. }
  27112. restoreRendererAndSceneState( renderer, scene, _rendererState );
  27113. }
  27114. /**
  27115. * For VSM additional render passes are required.
  27116. *
  27117. * @param {Renderer} renderer - A reference to the current renderer.
  27118. */
  27119. vsmPass( renderer ) {
  27120. const { shadow } = this;
  27121. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  27122. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  27123. renderer.setRenderTarget( this.vsmShadowMapVertical );
  27124. _quadMesh.material = this.vsmMaterialVertical;
  27125. _quadMesh.render( renderer );
  27126. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  27127. _quadMesh.material = this.vsmMaterialHorizontal;
  27128. _quadMesh.render( renderer );
  27129. }
  27130. /**
  27131. * Frees the internal resources of this shadow node.
  27132. */
  27133. dispose() {
  27134. this.shadowMap.dispose();
  27135. this.shadowMap = null;
  27136. if ( this.vsmShadowMapVertical !== null ) {
  27137. this.vsmShadowMapVertical.dispose();
  27138. this.vsmShadowMapVertical = null;
  27139. this.vsmMaterialVertical.dispose();
  27140. this.vsmMaterialVertical = null;
  27141. }
  27142. if ( this.vsmShadowMapHorizontal !== null ) {
  27143. this.vsmShadowMapHorizontal.dispose();
  27144. this.vsmShadowMapHorizontal = null;
  27145. this.vsmMaterialHorizontal.dispose();
  27146. this.vsmMaterialHorizontal = null;
  27147. }
  27148. super.dispose();
  27149. }
  27150. /**
  27151. * The implementation performs the update of the shadow map if necessary.
  27152. *
  27153. * @param {NodeFrame} frame - A reference to the current node frame.
  27154. */
  27155. updateBefore( frame ) {
  27156. const { shadow } = this;
  27157. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  27158. if ( needsUpdate ) {
  27159. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  27160. needsUpdate = false;
  27161. }
  27162. this._cameraFrameId[ frame.camera ] = frame.frameId;
  27163. }
  27164. if ( needsUpdate ) {
  27165. this.updateShadow( frame );
  27166. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  27167. shadow.needsUpdate = false;
  27168. }
  27169. }
  27170. }
  27171. }
  27172. /**
  27173. * TSL function for creating an instance of `ShadowNode`.
  27174. *
  27175. * @tsl
  27176. * @function
  27177. * @param {Light} light - The shadow casting light.
  27178. * @param {?LightShadow} [shadow] - The light shadow.
  27179. * @return {ShadowNode} The created shadow node.
  27180. */
  27181. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  27182. const _clearColor$1 = /*@__PURE__*/ new Color();
  27183. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  27184. // vector suitable for 2D texture mapping. This code uses the following layout for the
  27185. // 2D texture:
  27186. //
  27187. // xzXZ
  27188. // y Y
  27189. //
  27190. // Y - Positive y direction
  27191. // y - Negative y direction
  27192. // X - Positive x direction
  27193. // x - Negative x direction
  27194. // Z - Positive z direction
  27195. // z - Negative z direction
  27196. //
  27197. // Source and test bed:
  27198. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  27199. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  27200. const v = pos.toVar();
  27201. // Number of texels to avoid at the edge of each square
  27202. const absV = abs( v );
  27203. // Intersect unit cube
  27204. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  27205. absV.mulAssign( scaleToCube );
  27206. // Apply scale to avoid seams
  27207. // two texels less per square (one texel will do for NEAREST)
  27208. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  27209. // Unwrap
  27210. // space: -1 ... 1 range for each square
  27211. //
  27212. // #X## dim := ( 4 , 2 )
  27213. // # # center := ( 1 , 1 )
  27214. const planar = vec2( v.xy ).toVar();
  27215. const almostATexel = texelSizeY.mul( 1.5 );
  27216. const almostOne = almostATexel.oneMinus();
  27217. If( absV.z.greaterThanEqual( almostOne ), () => {
  27218. If( v.z.greaterThan( 0.0 ), () => {
  27219. planar.x.assign( sub( 4.0, v.x ) );
  27220. } );
  27221. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  27222. const signX = sign( v.x );
  27223. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  27224. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  27225. const signY = sign( v.y );
  27226. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  27227. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  27228. } );
  27229. // Transform to UV space
  27230. // scale := 0.5 / dim
  27231. // translate := ( center + 0.5 ) / dim
  27232. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  27233. } ).setLayout( {
  27234. name: 'cubeToUV',
  27235. type: 'vec2',
  27236. inputs: [
  27237. { name: 'pos', type: 'vec3' },
  27238. { name: 'texelSizeY', type: 'float' }
  27239. ]
  27240. } );
  27241. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  27242. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  27243. } );
  27244. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  27245. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27246. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  27247. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  27248. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  27249. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  27250. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  27251. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  27252. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  27253. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  27254. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  27255. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  27256. .mul( 1.0 / 9.0 );
  27257. } );
  27258. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  27259. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  27260. // the vector from the light to the world-space position of the fragment.
  27261. const lightToPosition = shadowCoord.xyz.toVar();
  27262. const lightToPositionLength = lightToPosition.length();
  27263. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  27264. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  27265. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27266. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  27267. const result = float( 1.0 ).toVar();
  27268. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  27269. // dp = normalized distance from light to fragment position
  27270. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  27271. dp.addAssign( bias );
  27272. // bd3D = base direction 3D
  27273. const bd3D = lightToPosition.normalize();
  27274. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  27275. // percentage-closer filtering
  27276. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  27277. } );
  27278. return result;
  27279. } );
  27280. const _viewport = /*@__PURE__*/ new Vector4();
  27281. const _viewportSize = /*@__PURE__*/ new Vector2();
  27282. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  27283. /**
  27284. * Represents the shadow implementation for point light nodes.
  27285. *
  27286. * @augments ShadowNode
  27287. */
  27288. class PointShadowNode extends ShadowNode {
  27289. static get type() {
  27290. return 'PointShadowNode';
  27291. }
  27292. /**
  27293. * Constructs a new point shadow node.
  27294. *
  27295. * @param {PointLight} light - The shadow casting point light.
  27296. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  27297. */
  27298. constructor( light, shadow = null ) {
  27299. super( light, shadow );
  27300. }
  27301. /**
  27302. * Overwrites the default implementation to return point light shadow specific
  27303. * filtering functions.
  27304. *
  27305. * @param {number} type - The shadow type.
  27306. * @return {Function} The filtering function.
  27307. */
  27308. getShadowFilterFn( type ) {
  27309. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  27310. }
  27311. /**
  27312. * Overwrites the default implementation so the unaltered shadow position is used.
  27313. *
  27314. * @param {NodeBuilder} builder - A reference to the current node builder.
  27315. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  27316. * @return {Node<vec3>} The shadow coordinates.
  27317. */
  27318. setupShadowCoord( builder, shadowPosition ) {
  27319. return shadowPosition;
  27320. }
  27321. /**
  27322. * Overwrites the default implementation to only use point light specific
  27323. * shadow filter functions.
  27324. *
  27325. * @param {NodeBuilder} builder - A reference to the current node builder.
  27326. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  27327. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  27328. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  27329. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27330. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  27331. * @param {LightShadow} inputs.shadow - The light shadow.
  27332. * @return {Node<float>} The result node of the shadow filtering.
  27333. */
  27334. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  27335. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  27336. }
  27337. /**
  27338. * Overwrites the default implementation with point light specific
  27339. * rendering code.
  27340. *
  27341. * @param {NodeFrame} frame - A reference to the current node frame.
  27342. */
  27343. renderShadow( frame ) {
  27344. const { shadow, shadowMap, light } = this;
  27345. const { renderer, scene } = frame;
  27346. const shadowFrameExtents = shadow.getFrameExtents();
  27347. _shadowMapSize.copy( shadow.mapSize );
  27348. _shadowMapSize.multiply( shadowFrameExtents );
  27349. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  27350. _viewportSize.copy( shadow.mapSize );
  27351. //
  27352. const previousAutoClear = renderer.autoClear;
  27353. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  27354. const previousClearAlpha = renderer.getClearAlpha();
  27355. renderer.autoClear = false;
  27356. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  27357. renderer.clear();
  27358. const viewportCount = shadow.getViewportCount();
  27359. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  27360. const viewport = shadow.getViewport( vp );
  27361. const x = _viewportSize.x * viewport.x;
  27362. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  27363. _viewport.set(
  27364. x,
  27365. y,
  27366. _viewportSize.x * viewport.z,
  27367. _viewportSize.y * viewport.w
  27368. );
  27369. shadowMap.viewport.copy( _viewport );
  27370. shadow.updateMatrices( light, vp );
  27371. renderer.render( scene, shadow.camera );
  27372. }
  27373. //
  27374. renderer.autoClear = previousAutoClear;
  27375. renderer.setClearColor( previousClearColor, previousClearAlpha );
  27376. }
  27377. }
  27378. /**
  27379. * TSL function for creating an instance of `PointShadowNode`.
  27380. *
  27381. * @tsl
  27382. * @function
  27383. * @param {PointLight} light - The shadow casting point light.
  27384. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  27385. * @return {PointShadowNode} The created point shadow node.
  27386. */
  27387. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  27388. /**
  27389. * Base class for analytic light nodes.
  27390. *
  27391. * @augments LightingNode
  27392. */
  27393. class AnalyticLightNode extends LightingNode {
  27394. static get type() {
  27395. return 'AnalyticLightNode';
  27396. }
  27397. /**
  27398. * Constructs a new analytic light node.
  27399. *
  27400. * @param {?Light} [light=null] - The light source.
  27401. */
  27402. constructor( light = null ) {
  27403. super();
  27404. /**
  27405. * The light source.
  27406. *
  27407. * @type {?Light}
  27408. * @default null
  27409. */
  27410. this.light = light;
  27411. /**
  27412. * The light's color value.
  27413. *
  27414. * @type {Color}
  27415. */
  27416. this.color = new Color();
  27417. /**
  27418. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  27419. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  27420. *
  27421. * @type {Node}
  27422. */
  27423. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  27424. /**
  27425. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  27426. * The final color node is represented by a different node when using shadows.
  27427. *
  27428. * @type {?Node}
  27429. * @default null
  27430. */
  27431. this.baseColorNode = null;
  27432. /**
  27433. * Represents the light's shadow.
  27434. *
  27435. * @type {?ShadowNode}
  27436. * @default null
  27437. */
  27438. this.shadowNode = null;
  27439. /**
  27440. * Represents the light's shadow color.
  27441. *
  27442. * @type {?Node}
  27443. * @default null
  27444. */
  27445. this.shadowColorNode = null;
  27446. /**
  27447. * This flag can be used for type testing.
  27448. *
  27449. * @type {boolean}
  27450. * @readonly
  27451. * @default true
  27452. */
  27453. this.isAnalyticLightNode = true;
  27454. /**
  27455. * Overwritten since analytic light nodes are updated
  27456. * once per frame.
  27457. *
  27458. * @type {string}
  27459. * @default 'frame'
  27460. */
  27461. this.updateType = NodeUpdateType.FRAME;
  27462. }
  27463. /**
  27464. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  27465. * `light.id` and `light.castShadow` into the cache key.
  27466. *
  27467. * @return {number} The custom cache key.
  27468. */
  27469. customCacheKey() {
  27470. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  27471. }
  27472. getHash() {
  27473. return this.light.uuid;
  27474. }
  27475. getLightVector( builder ) {
  27476. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  27477. }
  27478. /**
  27479. * Sets up the direct lighting for the analytic light node.
  27480. *
  27481. * @abstract
  27482. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  27483. * @return {Object|undefined} The direct light data (color and direction).
  27484. */
  27485. setupDirect( /*builder*/ ) { }
  27486. /**
  27487. * Sets up the direct rect area lighting for the analytic light node.
  27488. *
  27489. * @abstract
  27490. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  27491. * @return {Object|undefined} The direct rect area light data.
  27492. */
  27493. setupDirectRectArea( /*builder*/ ) { }
  27494. /**
  27495. * Setups the shadow node for this light. The method exists so concrete light classes
  27496. * can setup different types of shadow nodes.
  27497. *
  27498. * @return {ShadowNode} The created shadow node.
  27499. */
  27500. setupShadowNode() {
  27501. return shadow( this.light );
  27502. }
  27503. /**
  27504. * Setups the shadow for this light. This method is only executed if the light
  27505. * cast shadows and the current build object receives shadows. It incorporates
  27506. * shadows into the lighting computation.
  27507. *
  27508. * @param {NodeBuilder} builder - The current node builder.
  27509. */
  27510. setupShadow( builder ) {
  27511. const { renderer } = builder;
  27512. if ( renderer.shadowMap.enabled === false ) return;
  27513. let shadowColorNode = this.shadowColorNode;
  27514. if ( shadowColorNode === null ) {
  27515. const customShadowNode = this.light.shadow.shadowNode;
  27516. let shadowNode;
  27517. if ( customShadowNode !== undefined ) {
  27518. shadowNode = nodeObject( customShadowNode );
  27519. } else {
  27520. shadowNode = this.setupShadowNode();
  27521. }
  27522. this.shadowNode = shadowNode;
  27523. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  27524. this.baseColorNode = this.colorNode;
  27525. }
  27526. //
  27527. this.colorNode = shadowColorNode;
  27528. }
  27529. /**
  27530. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  27531. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  27532. * invocate the respective interface methods.
  27533. *
  27534. * @param {NodeBuilder} builder - The current node builder.
  27535. */
  27536. setup( builder ) {
  27537. this.colorNode = this.baseColorNode || this.colorNode;
  27538. if ( this.light.castShadow ) {
  27539. if ( builder.object.receiveShadow ) {
  27540. this.setupShadow( builder );
  27541. }
  27542. } else if ( this.shadowNode !== null ) {
  27543. this.shadowNode.dispose();
  27544. this.shadowNode = null;
  27545. this.shadowColorNode = null;
  27546. }
  27547. const directLightData = this.setupDirect( builder );
  27548. const directRectAreaLightData = this.setupDirectRectArea( builder );
  27549. if ( directLightData ) {
  27550. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  27551. }
  27552. if ( directRectAreaLightData ) {
  27553. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  27554. }
  27555. }
  27556. /**
  27557. * The update method is used to update light uniforms per frame.
  27558. * Potentially overwritten in concrete light nodes to update light
  27559. * specific uniforms.
  27560. *
  27561. * @param {NodeFrame} frame - A reference to the current node frame.
  27562. */
  27563. update( /*frame*/ ) {
  27564. const { light } = this;
  27565. this.color.copy( light.color ).multiplyScalar( light.intensity );
  27566. }
  27567. }
  27568. /**
  27569. * Represents a `discard` shader operation in TSL.
  27570. *
  27571. * @method
  27572. * @param {Object} inputs - The input parameter object.
  27573. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  27574. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  27575. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  27576. * @return {Node<float>} The distance falloff.
  27577. */
  27578. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  27579. // based upon Frostbite 3 Moving to Physically-based Rendering
  27580. // page 32, equation 26: E[window1]
  27581. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27582. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  27583. return cutoffDistance.greaterThan( 0 ).select(
  27584. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  27585. distanceFalloff
  27586. );
  27587. } ); // validated
  27588. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  27589. const lightDirection = lightVector.normalize();
  27590. const lightDistance = lightVector.length();
  27591. const attenuation = getDistanceAttenuation( {
  27592. lightDistance,
  27593. cutoffDistance,
  27594. decayExponent
  27595. } );
  27596. const lightColor = color.mul( attenuation );
  27597. return { lightDirection, lightColor };
  27598. };
  27599. /**
  27600. * Module for representing point lights as nodes.
  27601. *
  27602. * @augments AnalyticLightNode
  27603. */
  27604. class PointLightNode extends AnalyticLightNode {
  27605. static get type() {
  27606. return 'PointLightNode';
  27607. }
  27608. /**
  27609. * Constructs a new point light node.
  27610. *
  27611. * @param {?PointLight} [light=null] - The point light source.
  27612. */
  27613. constructor( light = null ) {
  27614. super( light );
  27615. /**
  27616. * Uniform node representing the cutoff distance.
  27617. *
  27618. * @type {UniformNode<float>}
  27619. */
  27620. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  27621. /**
  27622. * Uniform node representing the decay exponent.
  27623. *
  27624. * @type {UniformNode<float>}
  27625. */
  27626. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  27627. }
  27628. /**
  27629. * Overwritten to updated point light specific uniforms.
  27630. *
  27631. * @param {NodeFrame} frame - A reference to the current node frame.
  27632. */
  27633. update( frame ) {
  27634. const { light } = this;
  27635. super.update( frame );
  27636. this.cutoffDistanceNode.value = light.distance;
  27637. this.decayExponentNode.value = light.decay;
  27638. }
  27639. /**
  27640. * Overwritten to setup point light specific shadow.
  27641. *
  27642. * @return {PointShadowNode}
  27643. */
  27644. setupShadowNode() {
  27645. return pointShadow( this.light );
  27646. }
  27647. setupDirect( builder ) {
  27648. return directPointLight( {
  27649. color: this.colorNode,
  27650. lightVector: this.getLightVector( builder ),
  27651. cutoffDistance: this.cutoffDistanceNode,
  27652. decayExponent: this.decayExponentNode
  27653. } );
  27654. }
  27655. }
  27656. /**
  27657. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  27658. *
  27659. * @tsl
  27660. * @function
  27661. * @param {Node<vec2>} coord - The uv coordinates.
  27662. * @return {Node<float>} The result data.
  27663. */
  27664. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  27665. const uv = coord.mul( 2.0 );
  27666. const cx = uv.x.floor();
  27667. const cy = uv.y.floor();
  27668. const result = cx.add( cy ).mod( 2.0 );
  27669. return result.sign();
  27670. } );
  27671. /**
  27672. * Generates a circle based on the uv coordinates.
  27673. *
  27674. * @tsl
  27675. * @function
  27676. * @param {Node<vec2>} coord - The uv to generate the circle.
  27677. * @return {Node<float>} The circle shape.
  27678. */
  27679. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  27680. const alpha = float( 1 ).toVar();
  27681. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  27682. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  27683. const dlen = float( len2.fwidth() ).toVar();
  27684. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27685. } else {
  27686. len2.greaterThan( 1.0 ).discard();
  27687. }
  27688. return alpha;
  27689. } );
  27690. // Three.js Transpiler
  27691. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  27692. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  27693. const f = float( f_immutable ).toVar();
  27694. const t = float( t_immutable ).toVar();
  27695. const b = bool( b_immutable ).toVar();
  27696. return select( b, t, f );
  27697. } ).setLayout( {
  27698. name: 'mx_select',
  27699. type: 'float',
  27700. inputs: [
  27701. { name: 'b', type: 'bool' },
  27702. { name: 't', type: 'float' },
  27703. { name: 'f', type: 'float' }
  27704. ]
  27705. } );
  27706. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  27707. const b = bool( b_immutable ).toVar();
  27708. const val = float( val_immutable ).toVar();
  27709. return select( b, val.negate(), val );
  27710. } ).setLayout( {
  27711. name: 'mx_negate_if',
  27712. type: 'float',
  27713. inputs: [
  27714. { name: 'val', type: 'float' },
  27715. { name: 'b', type: 'bool' }
  27716. ]
  27717. } );
  27718. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27719. const x = float( x_immutable ).toVar();
  27720. return int( floor( x ) );
  27721. } ).setLayout( {
  27722. name: 'mx_floor',
  27723. type: 'int',
  27724. inputs: [
  27725. { name: 'x', type: 'float' }
  27726. ]
  27727. } );
  27728. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  27729. const x = float( x_immutable ).toVar();
  27730. i.assign( mx_floor( x ) );
  27731. return x.sub( float( i ) );
  27732. } );
  27733. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  27734. const t = float( t_immutable ).toVar();
  27735. const s = float( s_immutable ).toVar();
  27736. const v3 = float( v3_immutable ).toVar();
  27737. const v2 = float( v2_immutable ).toVar();
  27738. const v1 = float( v1_immutable ).toVar();
  27739. const v0 = float( v0_immutable ).toVar();
  27740. const s1 = float( sub( 1.0, s ) ).toVar();
  27741. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  27742. } ).setLayout( {
  27743. name: 'mx_bilerp_0',
  27744. type: 'float',
  27745. inputs: [
  27746. { name: 'v0', type: 'float' },
  27747. { name: 'v1', type: 'float' },
  27748. { name: 'v2', type: 'float' },
  27749. { name: 'v3', type: 'float' },
  27750. { name: 's', type: 'float' },
  27751. { name: 't', type: 'float' }
  27752. ]
  27753. } );
  27754. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  27755. const t = float( t_immutable ).toVar();
  27756. const s = float( s_immutable ).toVar();
  27757. const v3 = vec3( v3_immutable ).toVar();
  27758. const v2 = vec3( v2_immutable ).toVar();
  27759. const v1 = vec3( v1_immutable ).toVar();
  27760. const v0 = vec3( v0_immutable ).toVar();
  27761. const s1 = float( sub( 1.0, s ) ).toVar();
  27762. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  27763. } ).setLayout( {
  27764. name: 'mx_bilerp_1',
  27765. type: 'vec3',
  27766. inputs: [
  27767. { name: 'v0', type: 'vec3' },
  27768. { name: 'v1', type: 'vec3' },
  27769. { name: 'v2', type: 'vec3' },
  27770. { name: 'v3', type: 'vec3' },
  27771. { name: 's', type: 'float' },
  27772. { name: 't', type: 'float' }
  27773. ]
  27774. } );
  27775. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  27776. 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 ] ) => {
  27777. const r = float( r_immutable ).toVar();
  27778. const t = float( t_immutable ).toVar();
  27779. const s = float( s_immutable ).toVar();
  27780. const v7 = float( v7_immutable ).toVar();
  27781. const v6 = float( v6_immutable ).toVar();
  27782. const v5 = float( v5_immutable ).toVar();
  27783. const v4 = float( v4_immutable ).toVar();
  27784. const v3 = float( v3_immutable ).toVar();
  27785. const v2 = float( v2_immutable ).toVar();
  27786. const v1 = float( v1_immutable ).toVar();
  27787. const v0 = float( v0_immutable ).toVar();
  27788. const s1 = float( sub( 1.0, s ) ).toVar();
  27789. const t1 = float( sub( 1.0, t ) ).toVar();
  27790. const r1 = float( sub( 1.0, r ) ).toVar();
  27791. 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 ) ) ) ) ) );
  27792. } ).setLayout( {
  27793. name: 'mx_trilerp_0',
  27794. type: 'float',
  27795. inputs: [
  27796. { name: 'v0', type: 'float' },
  27797. { name: 'v1', type: 'float' },
  27798. { name: 'v2', type: 'float' },
  27799. { name: 'v3', type: 'float' },
  27800. { name: 'v4', type: 'float' },
  27801. { name: 'v5', type: 'float' },
  27802. { name: 'v6', type: 'float' },
  27803. { name: 'v7', type: 'float' },
  27804. { name: 's', type: 'float' },
  27805. { name: 't', type: 'float' },
  27806. { name: 'r', type: 'float' }
  27807. ]
  27808. } );
  27809. 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 ] ) => {
  27810. const r = float( r_immutable ).toVar();
  27811. const t = float( t_immutable ).toVar();
  27812. const s = float( s_immutable ).toVar();
  27813. const v7 = vec3( v7_immutable ).toVar();
  27814. const v6 = vec3( v6_immutable ).toVar();
  27815. const v5 = vec3( v5_immutable ).toVar();
  27816. const v4 = vec3( v4_immutable ).toVar();
  27817. const v3 = vec3( v3_immutable ).toVar();
  27818. const v2 = vec3( v2_immutable ).toVar();
  27819. const v1 = vec3( v1_immutable ).toVar();
  27820. const v0 = vec3( v0_immutable ).toVar();
  27821. const s1 = float( sub( 1.0, s ) ).toVar();
  27822. const t1 = float( sub( 1.0, t ) ).toVar();
  27823. const r1 = float( sub( 1.0, r ) ).toVar();
  27824. 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 ) ) ) ) ) );
  27825. } ).setLayout( {
  27826. name: 'mx_trilerp_1',
  27827. type: 'vec3',
  27828. inputs: [
  27829. { name: 'v0', type: 'vec3' },
  27830. { name: 'v1', type: 'vec3' },
  27831. { name: 'v2', type: 'vec3' },
  27832. { name: 'v3', type: 'vec3' },
  27833. { name: 'v4', type: 'vec3' },
  27834. { name: 'v5', type: 'vec3' },
  27835. { name: 'v6', type: 'vec3' },
  27836. { name: 'v7', type: 'vec3' },
  27837. { name: 's', type: 'float' },
  27838. { name: 't', type: 'float' },
  27839. { name: 'r', type: 'float' }
  27840. ]
  27841. } );
  27842. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  27843. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  27844. const y = float( y_immutable ).toVar();
  27845. const x = float( x_immutable ).toVar();
  27846. const hash = uint( hash_immutable ).toVar();
  27847. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  27848. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  27849. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  27850. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  27851. } ).setLayout( {
  27852. name: 'mx_gradient_float_0',
  27853. type: 'float',
  27854. inputs: [
  27855. { name: 'hash', type: 'uint' },
  27856. { name: 'x', type: 'float' },
  27857. { name: 'y', type: 'float' }
  27858. ]
  27859. } );
  27860. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  27861. const z = float( z_immutable ).toVar();
  27862. const y = float( y_immutable ).toVar();
  27863. const x = float( x_immutable ).toVar();
  27864. const hash = uint( hash_immutable ).toVar();
  27865. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  27866. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  27867. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  27868. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  27869. } ).setLayout( {
  27870. name: 'mx_gradient_float_1',
  27871. type: 'float',
  27872. inputs: [
  27873. { name: 'hash', type: 'uint' },
  27874. { name: 'x', type: 'float' },
  27875. { name: 'y', type: 'float' },
  27876. { name: 'z', type: 'float' }
  27877. ]
  27878. } );
  27879. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  27880. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  27881. const y = float( y_immutable ).toVar();
  27882. const x = float( x_immutable ).toVar();
  27883. const hash = uvec3( hash_immutable ).toVar();
  27884. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  27885. } ).setLayout( {
  27886. name: 'mx_gradient_vec3_0',
  27887. type: 'vec3',
  27888. inputs: [
  27889. { name: 'hash', type: 'uvec3' },
  27890. { name: 'x', type: 'float' },
  27891. { name: 'y', type: 'float' }
  27892. ]
  27893. } );
  27894. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  27895. const z = float( z_immutable ).toVar();
  27896. const y = float( y_immutable ).toVar();
  27897. const x = float( x_immutable ).toVar();
  27898. const hash = uvec3( hash_immutable ).toVar();
  27899. 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 ) );
  27900. } ).setLayout( {
  27901. name: 'mx_gradient_vec3_1',
  27902. type: 'vec3',
  27903. inputs: [
  27904. { name: 'hash', type: 'uvec3' },
  27905. { name: 'x', type: 'float' },
  27906. { name: 'y', type: 'float' },
  27907. { name: 'z', type: 'float' }
  27908. ]
  27909. } );
  27910. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  27911. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27912. const v = float( v_immutable ).toVar();
  27913. return mul( 0.6616, v );
  27914. } ).setLayout( {
  27915. name: 'mx_gradient_scale2d_0',
  27916. type: 'float',
  27917. inputs: [
  27918. { name: 'v', type: 'float' }
  27919. ]
  27920. } );
  27921. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27922. const v = float( v_immutable ).toVar();
  27923. return mul( 0.9820, v );
  27924. } ).setLayout( {
  27925. name: 'mx_gradient_scale3d_0',
  27926. type: 'float',
  27927. inputs: [
  27928. { name: 'v', type: 'float' }
  27929. ]
  27930. } );
  27931. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27932. const v = vec3( v_immutable ).toVar();
  27933. return mul( 0.6616, v );
  27934. } ).setLayout( {
  27935. name: 'mx_gradient_scale2d_1',
  27936. type: 'vec3',
  27937. inputs: [
  27938. { name: 'v', type: 'vec3' }
  27939. ]
  27940. } );
  27941. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  27942. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27943. const v = vec3( v_immutable ).toVar();
  27944. return mul( 0.9820, v );
  27945. } ).setLayout( {
  27946. name: 'mx_gradient_scale3d_1',
  27947. type: 'vec3',
  27948. inputs: [
  27949. { name: 'v', type: 'vec3' }
  27950. ]
  27951. } );
  27952. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  27953. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  27954. const k = int( k_immutable ).toVar();
  27955. const x = uint( x_immutable ).toVar();
  27956. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  27957. } ).setLayout( {
  27958. name: 'mx_rotl32',
  27959. type: 'uint',
  27960. inputs: [
  27961. { name: 'x', type: 'uint' },
  27962. { name: 'k', type: 'int' }
  27963. ]
  27964. } );
  27965. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  27966. a.subAssign( c );
  27967. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  27968. c.addAssign( b );
  27969. b.subAssign( a );
  27970. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  27971. a.addAssign( c );
  27972. c.subAssign( b );
  27973. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  27974. b.addAssign( a );
  27975. a.subAssign( c );
  27976. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  27977. c.addAssign( b );
  27978. b.subAssign( a );
  27979. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  27980. a.addAssign( c );
  27981. c.subAssign( b );
  27982. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  27983. b.addAssign( a );
  27984. } );
  27985. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  27986. const c = uint( c_immutable ).toVar();
  27987. const b = uint( b_immutable ).toVar();
  27988. const a = uint( a_immutable ).toVar();
  27989. c.bitXorAssign( b );
  27990. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  27991. a.bitXorAssign( c );
  27992. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  27993. b.bitXorAssign( a );
  27994. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  27995. c.bitXorAssign( b );
  27996. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  27997. a.bitXorAssign( c );
  27998. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  27999. b.bitXorAssign( a );
  28000. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  28001. c.bitXorAssign( b );
  28002. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  28003. return c;
  28004. } ).setLayout( {
  28005. name: 'mx_bjfinal',
  28006. type: 'uint',
  28007. inputs: [
  28008. { name: 'a', type: 'uint' },
  28009. { name: 'b', type: 'uint' },
  28010. { name: 'c', type: 'uint' }
  28011. ]
  28012. } );
  28013. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  28014. const bits = uint( bits_immutable ).toVar();
  28015. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  28016. } ).setLayout( {
  28017. name: 'mx_bits_to_01',
  28018. type: 'float',
  28019. inputs: [
  28020. { name: 'bits', type: 'uint' }
  28021. ]
  28022. } );
  28023. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  28024. const t = float( t_immutable ).toVar();
  28025. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  28026. } ).setLayout( {
  28027. name: 'mx_fade',
  28028. type: 'float',
  28029. inputs: [
  28030. { name: 't', type: 'float' }
  28031. ]
  28032. } );
  28033. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28034. const x = int( x_immutable ).toVar();
  28035. const len = uint( uint( 1 ) ).toVar();
  28036. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  28037. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  28038. } ).setLayout( {
  28039. name: 'mx_hash_int_0',
  28040. type: 'uint',
  28041. inputs: [
  28042. { name: 'x', type: 'int' }
  28043. ]
  28044. } );
  28045. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28046. const y = int( y_immutable ).toVar();
  28047. const x = int( x_immutable ).toVar();
  28048. const len = uint( uint( 2 ) ).toVar();
  28049. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28050. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28051. a.addAssign( uint( x ) );
  28052. b.addAssign( uint( y ) );
  28053. return mx_bjfinal( a, b, c );
  28054. } ).setLayout( {
  28055. name: 'mx_hash_int_1',
  28056. type: 'uint',
  28057. inputs: [
  28058. { name: 'x', type: 'int' },
  28059. { name: 'y', type: 'int' }
  28060. ]
  28061. } );
  28062. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28063. const z = int( z_immutable ).toVar();
  28064. const y = int( y_immutable ).toVar();
  28065. const x = int( x_immutable ).toVar();
  28066. const len = uint( uint( 3 ) ).toVar();
  28067. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28068. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28069. a.addAssign( uint( x ) );
  28070. b.addAssign( uint( y ) );
  28071. c.addAssign( uint( z ) );
  28072. return mx_bjfinal( a, b, c );
  28073. } ).setLayout( {
  28074. name: 'mx_hash_int_2',
  28075. type: 'uint',
  28076. inputs: [
  28077. { name: 'x', type: 'int' },
  28078. { name: 'y', type: 'int' },
  28079. { name: 'z', type: 'int' }
  28080. ]
  28081. } );
  28082. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  28083. const xx = int( xx_immutable ).toVar();
  28084. const z = int( z_immutable ).toVar();
  28085. const y = int( y_immutable ).toVar();
  28086. const x = int( x_immutable ).toVar();
  28087. const len = uint( uint( 4 ) ).toVar();
  28088. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28089. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28090. a.addAssign( uint( x ) );
  28091. b.addAssign( uint( y ) );
  28092. c.addAssign( uint( z ) );
  28093. mx_bjmix( a, b, c );
  28094. a.addAssign( uint( xx ) );
  28095. return mx_bjfinal( a, b, c );
  28096. } ).setLayout( {
  28097. name: 'mx_hash_int_3',
  28098. type: 'uint',
  28099. inputs: [
  28100. { name: 'x', type: 'int' },
  28101. { name: 'y', type: 'int' },
  28102. { name: 'z', type: 'int' },
  28103. { name: 'xx', type: 'int' }
  28104. ]
  28105. } );
  28106. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  28107. const yy = int( yy_immutable ).toVar();
  28108. const xx = int( xx_immutable ).toVar();
  28109. const z = int( z_immutable ).toVar();
  28110. const y = int( y_immutable ).toVar();
  28111. const x = int( x_immutable ).toVar();
  28112. const len = uint( uint( 5 ) ).toVar();
  28113. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28114. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28115. a.addAssign( uint( x ) );
  28116. b.addAssign( uint( y ) );
  28117. c.addAssign( uint( z ) );
  28118. mx_bjmix( a, b, c );
  28119. a.addAssign( uint( xx ) );
  28120. b.addAssign( uint( yy ) );
  28121. return mx_bjfinal( a, b, c );
  28122. } ).setLayout( {
  28123. name: 'mx_hash_int_4',
  28124. type: 'uint',
  28125. inputs: [
  28126. { name: 'x', type: 'int' },
  28127. { name: 'y', type: 'int' },
  28128. { name: 'z', type: 'int' },
  28129. { name: 'xx', type: 'int' },
  28130. { name: 'yy', type: 'int' }
  28131. ]
  28132. } );
  28133. 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 ] );
  28134. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28135. const y = int( y_immutable ).toVar();
  28136. const x = int( x_immutable ).toVar();
  28137. const h = uint( mx_hash_int( x, y ) ).toVar();
  28138. const result = uvec3().toVar();
  28139. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28140. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28141. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28142. return result;
  28143. } ).setLayout( {
  28144. name: 'mx_hash_vec3_0',
  28145. type: 'uvec3',
  28146. inputs: [
  28147. { name: 'x', type: 'int' },
  28148. { name: 'y', type: 'int' }
  28149. ]
  28150. } );
  28151. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28152. const z = int( z_immutable ).toVar();
  28153. const y = int( y_immutable ).toVar();
  28154. const x = int( x_immutable ).toVar();
  28155. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  28156. const result = uvec3().toVar();
  28157. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28158. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28159. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28160. return result;
  28161. } ).setLayout( {
  28162. name: 'mx_hash_vec3_1',
  28163. type: 'uvec3',
  28164. inputs: [
  28165. { name: 'x', type: 'int' },
  28166. { name: 'y', type: 'int' },
  28167. { name: 'z', type: 'int' }
  28168. ]
  28169. } );
  28170. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  28171. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28172. const p = vec2( p_immutable ).toVar();
  28173. const X = int().toVar(), Y = int().toVar();
  28174. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28175. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28176. const u = float( mx_fade( fx ) ).toVar();
  28177. const v = float( mx_fade( fy ) ).toVar();
  28178. 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();
  28179. return mx_gradient_scale2d( result );
  28180. } ).setLayout( {
  28181. name: 'mx_perlin_noise_float_0',
  28182. type: 'float',
  28183. inputs: [
  28184. { name: 'p', type: 'vec2' }
  28185. ]
  28186. } );
  28187. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28188. const p = vec3( p_immutable ).toVar();
  28189. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28190. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28191. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28192. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28193. const u = float( mx_fade( fx ) ).toVar();
  28194. const v = float( mx_fade( fy ) ).toVar();
  28195. const w = float( mx_fade( fz ) ).toVar();
  28196. 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();
  28197. return mx_gradient_scale3d( result );
  28198. } ).setLayout( {
  28199. name: 'mx_perlin_noise_float_1',
  28200. type: 'float',
  28201. inputs: [
  28202. { name: 'p', type: 'vec3' }
  28203. ]
  28204. } );
  28205. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  28206. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28207. const p = vec2( p_immutable ).toVar();
  28208. const X = int().toVar(), Y = int().toVar();
  28209. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28210. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28211. const u = float( mx_fade( fx ) ).toVar();
  28212. const v = float( mx_fade( fy ) ).toVar();
  28213. 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();
  28214. return mx_gradient_scale2d( result );
  28215. } ).setLayout( {
  28216. name: 'mx_perlin_noise_vec3_0',
  28217. type: 'vec3',
  28218. inputs: [
  28219. { name: 'p', type: 'vec2' }
  28220. ]
  28221. } );
  28222. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28223. const p = vec3( p_immutable ).toVar();
  28224. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28225. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28226. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28227. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28228. const u = float( mx_fade( fx ) ).toVar();
  28229. const v = float( mx_fade( fy ) ).toVar();
  28230. const w = float( mx_fade( fz ) ).toVar();
  28231. 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();
  28232. return mx_gradient_scale3d( result );
  28233. } ).setLayout( {
  28234. name: 'mx_perlin_noise_vec3_1',
  28235. type: 'vec3',
  28236. inputs: [
  28237. { name: 'p', type: 'vec3' }
  28238. ]
  28239. } );
  28240. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  28241. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28242. const p = float( p_immutable ).toVar();
  28243. const ix = int( mx_floor( p ) ).toVar();
  28244. return mx_bits_to_01( mx_hash_int( ix ) );
  28245. } ).setLayout( {
  28246. name: 'mx_cell_noise_float_0',
  28247. type: 'float',
  28248. inputs: [
  28249. { name: 'p', type: 'float' }
  28250. ]
  28251. } );
  28252. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28253. const p = vec2( p_immutable ).toVar();
  28254. const ix = int( mx_floor( p.x ) ).toVar();
  28255. const iy = int( mx_floor( p.y ) ).toVar();
  28256. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  28257. } ).setLayout( {
  28258. name: 'mx_cell_noise_float_1',
  28259. type: 'float',
  28260. inputs: [
  28261. { name: 'p', type: 'vec2' }
  28262. ]
  28263. } );
  28264. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28265. const p = vec3( p_immutable ).toVar();
  28266. const ix = int( mx_floor( p.x ) ).toVar();
  28267. const iy = int( mx_floor( p.y ) ).toVar();
  28268. const iz = int( mx_floor( p.z ) ).toVar();
  28269. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  28270. } ).setLayout( {
  28271. name: 'mx_cell_noise_float_2',
  28272. type: 'float',
  28273. inputs: [
  28274. { name: 'p', type: 'vec3' }
  28275. ]
  28276. } );
  28277. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28278. const p = vec4( p_immutable ).toVar();
  28279. const ix = int( mx_floor( p.x ) ).toVar();
  28280. const iy = int( mx_floor( p.y ) ).toVar();
  28281. const iz = int( mx_floor( p.z ) ).toVar();
  28282. const iw = int( mx_floor( p.w ) ).toVar();
  28283. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  28284. } ).setLayout( {
  28285. name: 'mx_cell_noise_float_3',
  28286. type: 'float',
  28287. inputs: [
  28288. { name: 'p', type: 'vec4' }
  28289. ]
  28290. } );
  28291. 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 ] );
  28292. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28293. const p = float( p_immutable ).toVar();
  28294. const ix = int( mx_floor( p ) ).toVar();
  28295. 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 ) ) ) );
  28296. } ).setLayout( {
  28297. name: 'mx_cell_noise_vec3_0',
  28298. type: 'vec3',
  28299. inputs: [
  28300. { name: 'p', type: 'float' }
  28301. ]
  28302. } );
  28303. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28304. const p = vec2( p_immutable ).toVar();
  28305. const ix = int( mx_floor( p.x ) ).toVar();
  28306. const iy = int( mx_floor( p.y ) ).toVar();
  28307. 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 ) ) ) );
  28308. } ).setLayout( {
  28309. name: 'mx_cell_noise_vec3_1',
  28310. type: 'vec3',
  28311. inputs: [
  28312. { name: 'p', type: 'vec2' }
  28313. ]
  28314. } );
  28315. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28316. const p = vec3( p_immutable ).toVar();
  28317. const ix = int( mx_floor( p.x ) ).toVar();
  28318. const iy = int( mx_floor( p.y ) ).toVar();
  28319. const iz = int( mx_floor( p.z ) ).toVar();
  28320. 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 ) ) ) );
  28321. } ).setLayout( {
  28322. name: 'mx_cell_noise_vec3_2',
  28323. type: 'vec3',
  28324. inputs: [
  28325. { name: 'p', type: 'vec3' }
  28326. ]
  28327. } );
  28328. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28329. const p = vec4( p_immutable ).toVar();
  28330. const ix = int( mx_floor( p.x ) ).toVar();
  28331. const iy = int( mx_floor( p.y ) ).toVar();
  28332. const iz = int( mx_floor( p.z ) ).toVar();
  28333. const iw = int( mx_floor( p.w ) ).toVar();
  28334. 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 ) ) ) );
  28335. } ).setLayout( {
  28336. name: 'mx_cell_noise_vec3_3',
  28337. type: 'vec3',
  28338. inputs: [
  28339. { name: 'p', type: 'vec4' }
  28340. ]
  28341. } );
  28342. 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 ] );
  28343. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28344. const diminish = float( diminish_immutable ).toVar();
  28345. const lacunarity = float( lacunarity_immutable ).toVar();
  28346. const octaves = int( octaves_immutable ).toVar();
  28347. const p = vec3( p_immutable ).toVar();
  28348. const result = float( 0.0 ).toVar();
  28349. const amplitude = float( 1.0 ).toVar();
  28350. Loop( octaves, () => {
  28351. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  28352. amplitude.mulAssign( diminish );
  28353. p.mulAssign( lacunarity );
  28354. } );
  28355. return result;
  28356. } ).setLayout( {
  28357. name: 'mx_fractal_noise_float',
  28358. type: 'float',
  28359. inputs: [
  28360. { name: 'p', type: 'vec3' },
  28361. { name: 'octaves', type: 'int' },
  28362. { name: 'lacunarity', type: 'float' },
  28363. { name: 'diminish', type: 'float' }
  28364. ]
  28365. } );
  28366. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28367. const diminish = float( diminish_immutable ).toVar();
  28368. const lacunarity = float( lacunarity_immutable ).toVar();
  28369. const octaves = int( octaves_immutable ).toVar();
  28370. const p = vec3( p_immutable ).toVar();
  28371. const result = vec3( 0.0 ).toVar();
  28372. const amplitude = float( 1.0 ).toVar();
  28373. Loop( octaves, () => {
  28374. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  28375. amplitude.mulAssign( diminish );
  28376. p.mulAssign( lacunarity );
  28377. } );
  28378. return result;
  28379. } ).setLayout( {
  28380. name: 'mx_fractal_noise_vec3',
  28381. type: 'vec3',
  28382. inputs: [
  28383. { name: 'p', type: 'vec3' },
  28384. { name: 'octaves', type: 'int' },
  28385. { name: 'lacunarity', type: 'float' },
  28386. { name: 'diminish', type: 'float' }
  28387. ]
  28388. } );
  28389. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28390. const diminish = float( diminish_immutable ).toVar();
  28391. const lacunarity = float( lacunarity_immutable ).toVar();
  28392. const octaves = int( octaves_immutable ).toVar();
  28393. const p = vec3( p_immutable ).toVar();
  28394. 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 ) );
  28395. } ).setLayout( {
  28396. name: 'mx_fractal_noise_vec2',
  28397. type: 'vec2',
  28398. inputs: [
  28399. { name: 'p', type: 'vec3' },
  28400. { name: 'octaves', type: 'int' },
  28401. { name: 'lacunarity', type: 'float' },
  28402. { name: 'diminish', type: 'float' }
  28403. ]
  28404. } );
  28405. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28406. const diminish = float( diminish_immutable ).toVar();
  28407. const lacunarity = float( lacunarity_immutable ).toVar();
  28408. const octaves = int( octaves_immutable ).toVar();
  28409. const p = vec3( p_immutable ).toVar();
  28410. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  28411. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  28412. return vec4( c, f );
  28413. } ).setLayout( {
  28414. name: 'mx_fractal_noise_vec4',
  28415. type: 'vec4',
  28416. inputs: [
  28417. { name: 'p', type: 'vec3' },
  28418. { name: 'octaves', type: 'int' },
  28419. { name: 'lacunarity', type: 'float' },
  28420. { name: 'diminish', type: 'float' }
  28421. ]
  28422. } );
  28423. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  28424. const metric = int( metric_immutable ).toVar();
  28425. const jitter = float( jitter_immutable ).toVar();
  28426. const yoff = int( yoff_immutable ).toVar();
  28427. const xoff = int( xoff_immutable ).toVar();
  28428. const y = int( y_immutable ).toVar();
  28429. const x = int( x_immutable ).toVar();
  28430. const p = vec2( p_immutable ).toVar();
  28431. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  28432. const off = vec2( tmp.x, tmp.y ).toVar();
  28433. off.subAssign( 0.5 );
  28434. off.mulAssign( jitter );
  28435. off.addAssign( 0.5 );
  28436. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  28437. const diff = vec2( cellpos.sub( p ) ).toVar();
  28438. If( metric.equal( int( 2 ) ), () => {
  28439. return abs( diff.x ).add( abs( diff.y ) );
  28440. } );
  28441. If( metric.equal( int( 3 ) ), () => {
  28442. return max$1( abs( diff.x ), abs( diff.y ) );
  28443. } );
  28444. return dot( diff, diff );
  28445. } ).setLayout( {
  28446. name: 'mx_worley_distance_0',
  28447. type: 'float',
  28448. inputs: [
  28449. { name: 'p', type: 'vec2' },
  28450. { name: 'x', type: 'int' },
  28451. { name: 'y', type: 'int' },
  28452. { name: 'xoff', type: 'int' },
  28453. { name: 'yoff', type: 'int' },
  28454. { name: 'jitter', type: 'float' },
  28455. { name: 'metric', type: 'int' }
  28456. ]
  28457. } );
  28458. 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 ] ) => {
  28459. const metric = int( metric_immutable ).toVar();
  28460. const jitter = float( jitter_immutable ).toVar();
  28461. const zoff = int( zoff_immutable ).toVar();
  28462. const yoff = int( yoff_immutable ).toVar();
  28463. const xoff = int( xoff_immutable ).toVar();
  28464. const z = int( z_immutable ).toVar();
  28465. const y = int( y_immutable ).toVar();
  28466. const x = int( x_immutable ).toVar();
  28467. const p = vec3( p_immutable ).toVar();
  28468. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  28469. off.subAssign( 0.5 );
  28470. off.mulAssign( jitter );
  28471. off.addAssign( 0.5 );
  28472. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  28473. const diff = vec3( cellpos.sub( p ) ).toVar();
  28474. If( metric.equal( int( 2 ) ), () => {
  28475. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  28476. } );
  28477. If( metric.equal( int( 3 ) ), () => {
  28478. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  28479. } );
  28480. return dot( diff, diff );
  28481. } ).setLayout( {
  28482. name: 'mx_worley_distance_1',
  28483. type: 'float',
  28484. inputs: [
  28485. { name: 'p', type: 'vec3' },
  28486. { name: 'x', type: 'int' },
  28487. { name: 'y', type: 'int' },
  28488. { name: 'z', type: 'int' },
  28489. { name: 'xoff', type: 'int' },
  28490. { name: 'yoff', type: 'int' },
  28491. { name: 'zoff', type: 'int' },
  28492. { name: 'jitter', type: 'float' },
  28493. { name: 'metric', type: 'int' }
  28494. ]
  28495. } );
  28496. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  28497. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28498. const metric = int( metric_immutable ).toVar();
  28499. const jitter = float( jitter_immutable ).toVar();
  28500. const p = vec2( p_immutable ).toVar();
  28501. const X = int().toVar(), Y = int().toVar();
  28502. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  28503. const sqdist = float( 1e6 ).toVar();
  28504. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28505. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28506. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  28507. sqdist.assign( min$1( sqdist, dist ) );
  28508. } );
  28509. } );
  28510. If( metric.equal( int( 0 ) ), () => {
  28511. sqdist.assign( sqrt( sqdist ) );
  28512. } );
  28513. return sqdist;
  28514. } ).setLayout( {
  28515. name: 'mx_worley_noise_float_0',
  28516. type: 'float',
  28517. inputs: [
  28518. { name: 'p', type: 'vec2' },
  28519. { name: 'jitter', type: 'float' },
  28520. { name: 'metric', type: 'int' }
  28521. ]
  28522. } );
  28523. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28524. const metric = int( metric_immutable ).toVar();
  28525. const jitter = float( jitter_immutable ).toVar();
  28526. const p = vec2( p_immutable ).toVar();
  28527. const X = int().toVar(), Y = int().toVar();
  28528. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  28529. const sqdist = vec2( 1e6, 1e6 ).toVar();
  28530. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28531. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28532. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  28533. If( dist.lessThan( sqdist.x ), () => {
  28534. sqdist.y.assign( sqdist.x );
  28535. sqdist.x.assign( dist );
  28536. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28537. sqdist.y.assign( dist );
  28538. } );
  28539. } );
  28540. } );
  28541. If( metric.equal( int( 0 ) ), () => {
  28542. sqdist.assign( sqrt( sqdist ) );
  28543. } );
  28544. return sqdist;
  28545. } ).setLayout( {
  28546. name: 'mx_worley_noise_vec2_0',
  28547. type: 'vec2',
  28548. inputs: [
  28549. { name: 'p', type: 'vec2' },
  28550. { name: 'jitter', type: 'float' },
  28551. { name: 'metric', type: 'int' }
  28552. ]
  28553. } );
  28554. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28555. const metric = int( metric_immutable ).toVar();
  28556. const jitter = float( jitter_immutable ).toVar();
  28557. const p = vec2( p_immutable ).toVar();
  28558. const X = int().toVar(), Y = int().toVar();
  28559. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  28560. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  28561. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28562. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28563. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  28564. If( dist.lessThan( sqdist.x ), () => {
  28565. sqdist.z.assign( sqdist.y );
  28566. sqdist.y.assign( sqdist.x );
  28567. sqdist.x.assign( dist );
  28568. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28569. sqdist.z.assign( sqdist.y );
  28570. sqdist.y.assign( dist );
  28571. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  28572. sqdist.z.assign( dist );
  28573. } );
  28574. } );
  28575. } );
  28576. If( metric.equal( int( 0 ) ), () => {
  28577. sqdist.assign( sqrt( sqdist ) );
  28578. } );
  28579. return sqdist;
  28580. } ).setLayout( {
  28581. name: 'mx_worley_noise_vec3_0',
  28582. type: 'vec3',
  28583. inputs: [
  28584. { name: 'p', type: 'vec2' },
  28585. { name: 'jitter', type: 'float' },
  28586. { name: 'metric', type: 'int' }
  28587. ]
  28588. } );
  28589. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28590. const metric = int( metric_immutable ).toVar();
  28591. const jitter = float( jitter_immutable ).toVar();
  28592. const p = vec3( p_immutable ).toVar();
  28593. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28594. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  28595. const sqdist = float( 1e6 ).toVar();
  28596. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28597. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28598. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  28599. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  28600. sqdist.assign( min$1( sqdist, dist ) );
  28601. } );
  28602. } );
  28603. } );
  28604. If( metric.equal( int( 0 ) ), () => {
  28605. sqdist.assign( sqrt( sqdist ) );
  28606. } );
  28607. return sqdist;
  28608. } ).setLayout( {
  28609. name: 'mx_worley_noise_float_1',
  28610. type: 'float',
  28611. inputs: [
  28612. { name: 'p', type: 'vec3' },
  28613. { name: 'jitter', type: 'float' },
  28614. { name: 'metric', type: 'int' }
  28615. ]
  28616. } );
  28617. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  28618. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28619. const metric = int( metric_immutable ).toVar();
  28620. const jitter = float( jitter_immutable ).toVar();
  28621. const p = vec3( p_immutable ).toVar();
  28622. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28623. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  28624. const sqdist = vec2( 1e6, 1e6 ).toVar();
  28625. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28626. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28627. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  28628. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  28629. If( dist.lessThan( sqdist.x ), () => {
  28630. sqdist.y.assign( sqdist.x );
  28631. sqdist.x.assign( dist );
  28632. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28633. sqdist.y.assign( dist );
  28634. } );
  28635. } );
  28636. } );
  28637. } );
  28638. If( metric.equal( int( 0 ) ), () => {
  28639. sqdist.assign( sqrt( sqdist ) );
  28640. } );
  28641. return sqdist;
  28642. } ).setLayout( {
  28643. name: 'mx_worley_noise_vec2_1',
  28644. type: 'vec2',
  28645. inputs: [
  28646. { name: 'p', type: 'vec3' },
  28647. { name: 'jitter', type: 'float' },
  28648. { name: 'metric', type: 'int' }
  28649. ]
  28650. } );
  28651. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  28652. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28653. const metric = int( metric_immutable ).toVar();
  28654. const jitter = float( jitter_immutable ).toVar();
  28655. const p = vec3( p_immutable ).toVar();
  28656. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28657. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  28658. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  28659. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28660. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28661. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  28662. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  28663. If( dist.lessThan( sqdist.x ), () => {
  28664. sqdist.z.assign( sqdist.y );
  28665. sqdist.y.assign( sqdist.x );
  28666. sqdist.x.assign( dist );
  28667. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28668. sqdist.z.assign( sqdist.y );
  28669. sqdist.y.assign( dist );
  28670. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  28671. sqdist.z.assign( dist );
  28672. } );
  28673. } );
  28674. } );
  28675. } );
  28676. If( metric.equal( int( 0 ) ), () => {
  28677. sqdist.assign( sqrt( sqdist ) );
  28678. } );
  28679. return sqdist;
  28680. } ).setLayout( {
  28681. name: 'mx_worley_noise_vec3_1',
  28682. type: 'vec3',
  28683. inputs: [
  28684. { name: 'p', type: 'vec3' },
  28685. { name: 'jitter', type: 'float' },
  28686. { name: 'metric', type: 'int' }
  28687. ]
  28688. } );
  28689. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  28690. // Three.js Transpiler
  28691. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  28692. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  28693. const s = hsv.y;
  28694. const v = hsv.z;
  28695. const result = vec3().toVar();
  28696. If( s.lessThan( 0.0001 ), () => {
  28697. result.assign( vec3( v, v, v ) );
  28698. } ).Else( () => {
  28699. let h = hsv.x;
  28700. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  28701. const hi = int( trunc( h ) );
  28702. const f = h.sub( float( hi ) );
  28703. const p = v.mul( s.oneMinus() );
  28704. const q = v.mul( s.mul( f ).oneMinus() );
  28705. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  28706. If( hi.equal( int( 0 ) ), () => {
  28707. result.assign( vec3( v, t, p ) );
  28708. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  28709. result.assign( vec3( q, v, p ) );
  28710. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  28711. result.assign( vec3( p, v, t ) );
  28712. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  28713. result.assign( vec3( p, q, v ) );
  28714. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  28715. result.assign( vec3( t, p, v ) );
  28716. } ).Else( () => {
  28717. result.assign( vec3( v, p, q ) );
  28718. } );
  28719. } );
  28720. return result;
  28721. } ).setLayout( {
  28722. name: 'mx_hsvtorgb',
  28723. type: 'vec3',
  28724. inputs: [
  28725. { name: 'hsv', type: 'vec3' }
  28726. ]
  28727. } );
  28728. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  28729. const c = vec3( c_immutable ).toVar();
  28730. const r = float( c.x ).toVar();
  28731. const g = float( c.y ).toVar();
  28732. const b = float( c.z ).toVar();
  28733. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  28734. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  28735. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  28736. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  28737. v.assign( maxcomp );
  28738. If( maxcomp.greaterThan( 0.0 ), () => {
  28739. s.assign( delta.div( maxcomp ) );
  28740. } ).Else( () => {
  28741. s.assign( 0.0 );
  28742. } );
  28743. If( s.lessThanEqual( 0.0 ), () => {
  28744. h.assign( 0.0 );
  28745. } ).Else( () => {
  28746. If( r.greaterThanEqual( maxcomp ), () => {
  28747. h.assign( g.sub( b ).div( delta ) );
  28748. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  28749. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  28750. } ).Else( () => {
  28751. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  28752. } );
  28753. h.mulAssign( 1.0 / 6.0 );
  28754. If( h.lessThan( 0.0 ), () => {
  28755. h.addAssign( 1.0 );
  28756. } );
  28757. } );
  28758. return vec3( h, s, v );
  28759. } ).setLayout( {
  28760. name: 'mx_rgbtohsv',
  28761. type: 'vec3',
  28762. inputs: [
  28763. { name: 'c', type: 'vec3' }
  28764. ]
  28765. } );
  28766. // Three.js Transpiler
  28767. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  28768. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  28769. const color = vec3( color_immutable ).toVar();
  28770. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  28771. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  28772. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  28773. return mix( linSeg, powSeg, isAbove );
  28774. } ).setLayout( {
  28775. name: 'mx_srgb_texture_to_lin_rec709',
  28776. type: 'vec3',
  28777. inputs: [
  28778. { name: 'color', type: 'vec3' }
  28779. ]
  28780. } );
  28781. const mx_aastep = ( threshold, value ) => {
  28782. threshold = float( threshold );
  28783. value = float( value );
  28784. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  28785. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  28786. };
  28787. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  28788. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  28789. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  28790. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  28791. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  28792. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  28793. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  28794. const mx_safepower = ( in1, in2 = 1 ) => {
  28795. in1 = float( in1 );
  28796. return in1.abs().pow( in2 ).mul( in1.sign() );
  28797. };
  28798. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  28799. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  28800. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  28801. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  28802. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  28803. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  28804. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  28805. return noise_vec4.mul( amplitude ).add( pivot );
  28806. };
  28807. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  28808. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  28809. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  28810. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  28811. 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 );
  28812. 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 );
  28813. 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 );
  28814. 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 );
  28815. /**
  28816. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  28817. *
  28818. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  28819. *
  28820. * ```js
  28821. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  28822. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  28823. * ```
  28824. *
  28825. * @tsl
  28826. * @function
  28827. * @param {Node<vec3>} normal - The normal to correct.
  28828. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  28829. * @param {Node<vec3>} cubePos - The cube position.
  28830. * @return {Node<vec3>} The parallax corrected normal.
  28831. */
  28832. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  28833. const nDir = normalize( normal ).toVar( 'nDir' );
  28834. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  28835. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  28836. const rbminmax = vec3().toVar( 'rbminmax' );
  28837. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  28838. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  28839. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  28840. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  28841. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  28842. return boxIntersection.sub( cubePos );
  28843. } );
  28844. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  28845. // normal is assumed to have unit length
  28846. const x = normal.x, y = normal.y, z = normal.z;
  28847. // band 0
  28848. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  28849. // band 1
  28850. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  28851. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  28852. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  28853. // band 2
  28854. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  28855. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  28856. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  28857. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  28858. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  28859. return result;
  28860. } );
  28861. // constants
  28862. var TSL = /*#__PURE__*/Object.freeze({
  28863. __proto__: null,
  28864. BRDF_GGX: BRDF_GGX,
  28865. BRDF_Lambert: BRDF_Lambert,
  28866. BasicPointShadowFilter: BasicPointShadowFilter,
  28867. BasicShadowFilter: BasicShadowFilter,
  28868. Break: Break,
  28869. Const: Const,
  28870. Continue: Continue,
  28871. DFGApprox: DFGApprox,
  28872. D_GGX: D_GGX,
  28873. Discard: Discard,
  28874. EPSILON: EPSILON,
  28875. F_Schlick: F_Schlick,
  28876. Fn: Fn,
  28877. INFINITY: INFINITY,
  28878. If: If,
  28879. Loop: Loop,
  28880. NodeAccess: NodeAccess,
  28881. NodeShaderStage: NodeShaderStage,
  28882. NodeType: NodeType,
  28883. NodeUpdateType: NodeUpdateType,
  28884. PCFShadowFilter: PCFShadowFilter,
  28885. PCFSoftShadowFilter: PCFSoftShadowFilter,
  28886. PI: PI,
  28887. PI2: PI2,
  28888. PointShadowFilter: PointShadowFilter,
  28889. Return: Return,
  28890. Schlick_to_F0: Schlick_to_F0,
  28891. ScriptableNodeResources: ScriptableNodeResources,
  28892. ShaderNode: ShaderNode,
  28893. TBNViewMatrix: TBNViewMatrix,
  28894. VSMShadowFilter: VSMShadowFilter,
  28895. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  28896. Var: Var,
  28897. abs: abs,
  28898. acesFilmicToneMapping: acesFilmicToneMapping,
  28899. acos: acos,
  28900. add: add,
  28901. addMethodChaining: addMethodChaining,
  28902. addNodeElement: addNodeElement,
  28903. agxToneMapping: agxToneMapping,
  28904. all: all,
  28905. alphaT: alphaT,
  28906. and: and,
  28907. anisotropy: anisotropy,
  28908. anisotropyB: anisotropyB,
  28909. anisotropyT: anisotropyT,
  28910. any: any,
  28911. append: append,
  28912. array: array,
  28913. arrayBuffer: arrayBuffer,
  28914. asin: asin,
  28915. assign: assign,
  28916. atan: atan,
  28917. atan2: atan2,
  28918. atomicAdd: atomicAdd,
  28919. atomicAnd: atomicAnd,
  28920. atomicFunc: atomicFunc,
  28921. atomicLoad: atomicLoad,
  28922. atomicMax: atomicMax,
  28923. atomicMin: atomicMin,
  28924. atomicOr: atomicOr,
  28925. atomicStore: atomicStore,
  28926. atomicSub: atomicSub,
  28927. atomicXor: atomicXor,
  28928. attenuationColor: attenuationColor,
  28929. attenuationDistance: attenuationDistance,
  28930. attribute: attribute,
  28931. attributeArray: attributeArray,
  28932. backgroundBlurriness: backgroundBlurriness,
  28933. backgroundIntensity: backgroundIntensity,
  28934. backgroundRotation: backgroundRotation,
  28935. batch: batch,
  28936. billboarding: billboarding,
  28937. bitAnd: bitAnd,
  28938. bitNot: bitNot,
  28939. bitOr: bitOr,
  28940. bitXor: bitXor,
  28941. bitangentGeometry: bitangentGeometry,
  28942. bitangentLocal: bitangentLocal,
  28943. bitangentView: bitangentView,
  28944. bitangentWorld: bitangentWorld,
  28945. bitcast: bitcast,
  28946. blendBurn: blendBurn,
  28947. blendColor: blendColor,
  28948. blendDodge: blendDodge,
  28949. blendOverlay: blendOverlay,
  28950. blendScreen: blendScreen,
  28951. blur: blur,
  28952. bool: bool,
  28953. buffer: buffer,
  28954. bufferAttribute: bufferAttribute,
  28955. bumpMap: bumpMap,
  28956. burn: burn,
  28957. bvec2: bvec2,
  28958. bvec3: bvec3,
  28959. bvec4: bvec4,
  28960. bypass: bypass,
  28961. cache: cache,
  28962. call: call,
  28963. cameraFar: cameraFar,
  28964. cameraIndex: cameraIndex,
  28965. cameraNear: cameraNear,
  28966. cameraNormalMatrix: cameraNormalMatrix,
  28967. cameraPosition: cameraPosition,
  28968. cameraProjectionMatrix: cameraProjectionMatrix,
  28969. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  28970. cameraViewMatrix: cameraViewMatrix,
  28971. cameraWorldMatrix: cameraWorldMatrix,
  28972. cbrt: cbrt,
  28973. cdl: cdl,
  28974. ceil: ceil,
  28975. checker: checker,
  28976. cineonToneMapping: cineonToneMapping,
  28977. clamp: clamp,
  28978. clearcoat: clearcoat,
  28979. clearcoatRoughness: clearcoatRoughness,
  28980. code: code,
  28981. color: color,
  28982. colorSpaceToWorking: colorSpaceToWorking,
  28983. colorToDirection: colorToDirection,
  28984. compute: compute,
  28985. cond: cond,
  28986. context: context,
  28987. convert: convert,
  28988. convertColorSpace: convertColorSpace,
  28989. convertToTexture: convertToTexture,
  28990. cos: cos,
  28991. cross: cross,
  28992. cubeTexture: cubeTexture,
  28993. cubeToUV: cubeToUV,
  28994. dFdx: dFdx,
  28995. dFdy: dFdy,
  28996. dashSize: dashSize,
  28997. defaultBuildStages: defaultBuildStages,
  28998. defaultShaderStages: defaultShaderStages,
  28999. defined: defined,
  29000. degrees: degrees,
  29001. deltaTime: deltaTime,
  29002. densityFog: densityFog,
  29003. densityFogFactor: densityFogFactor,
  29004. depth: depth,
  29005. depthPass: depthPass,
  29006. difference: difference,
  29007. diffuseColor: diffuseColor,
  29008. directPointLight: directPointLight,
  29009. directionToColor: directionToColor,
  29010. dispersion: dispersion,
  29011. distance: distance,
  29012. div: div,
  29013. dodge: dodge,
  29014. dot: dot,
  29015. drawIndex: drawIndex,
  29016. dynamicBufferAttribute: dynamicBufferAttribute,
  29017. element: element,
  29018. emissive: emissive,
  29019. equal: equal,
  29020. equals: equals,
  29021. equirectUV: equirectUV,
  29022. exp: exp,
  29023. exp2: exp2,
  29024. expression: expression,
  29025. faceDirection: faceDirection,
  29026. faceForward: faceForward,
  29027. faceforward: faceforward,
  29028. float: float,
  29029. floor: floor,
  29030. fog: fog,
  29031. fract: fract,
  29032. frameGroup: frameGroup,
  29033. frameId: frameId,
  29034. frontFacing: frontFacing,
  29035. fwidth: fwidth,
  29036. gain: gain,
  29037. gapSize: gapSize,
  29038. getConstNodeType: getConstNodeType,
  29039. getCurrentStack: getCurrentStack,
  29040. getDirection: getDirection,
  29041. getDistanceAttenuation: getDistanceAttenuation,
  29042. getGeometryRoughness: getGeometryRoughness,
  29043. getNormalFromDepth: getNormalFromDepth,
  29044. getParallaxCorrectNormal: getParallaxCorrectNormal,
  29045. getRoughness: getRoughness,
  29046. getScreenPosition: getScreenPosition,
  29047. getShIrradianceAt: getShIrradianceAt,
  29048. getTextureIndex: getTextureIndex,
  29049. getViewPosition: getViewPosition,
  29050. globalId: globalId,
  29051. glsl: glsl,
  29052. glslFn: glslFn,
  29053. grayscale: grayscale,
  29054. greaterThan: greaterThan,
  29055. greaterThanEqual: greaterThanEqual,
  29056. hash: hash,
  29057. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  29058. highpModelViewMatrix: highpModelViewMatrix,
  29059. hue: hue,
  29060. instance: instance,
  29061. instanceIndex: instanceIndex,
  29062. instancedArray: instancedArray,
  29063. instancedBufferAttribute: instancedBufferAttribute,
  29064. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  29065. instancedMesh: instancedMesh,
  29066. int: int,
  29067. inverseSqrt: inverseSqrt,
  29068. inversesqrt: inversesqrt,
  29069. invocationLocalIndex: invocationLocalIndex,
  29070. invocationSubgroupIndex: invocationSubgroupIndex,
  29071. ior: ior,
  29072. iridescence: iridescence,
  29073. iridescenceIOR: iridescenceIOR,
  29074. iridescenceThickness: iridescenceThickness,
  29075. ivec2: ivec2,
  29076. ivec3: ivec3,
  29077. ivec4: ivec4,
  29078. js: js,
  29079. label: label,
  29080. length: length,
  29081. lengthSq: lengthSq,
  29082. lessThan: lessThan,
  29083. lessThanEqual: lessThanEqual,
  29084. lightPosition: lightPosition,
  29085. lightProjectionUV: lightProjectionUV,
  29086. lightShadowMatrix: lightShadowMatrix,
  29087. lightTargetDirection: lightTargetDirection,
  29088. lightTargetPosition: lightTargetPosition,
  29089. lightViewPosition: lightViewPosition,
  29090. lightingContext: lightingContext,
  29091. lights: lights,
  29092. linearDepth: linearDepth,
  29093. linearToneMapping: linearToneMapping,
  29094. localId: localId,
  29095. log: log,
  29096. log2: log2,
  29097. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  29098. loop: loop,
  29099. luminance: luminance,
  29100. mat2: mat2,
  29101. mat3: mat3,
  29102. mat4: mat4,
  29103. matcapUV: matcapUV,
  29104. materialAO: materialAO,
  29105. materialAlphaTest: materialAlphaTest,
  29106. materialAnisotropy: materialAnisotropy,
  29107. materialAnisotropyVector: materialAnisotropyVector,
  29108. materialAttenuationColor: materialAttenuationColor,
  29109. materialAttenuationDistance: materialAttenuationDistance,
  29110. materialClearcoat: materialClearcoat,
  29111. materialClearcoatNormal: materialClearcoatNormal,
  29112. materialClearcoatRoughness: materialClearcoatRoughness,
  29113. materialColor: materialColor,
  29114. materialDispersion: materialDispersion,
  29115. materialEmissive: materialEmissive,
  29116. materialEnvIntensity: materialEnvIntensity,
  29117. materialEnvRotation: materialEnvRotation,
  29118. materialIOR: materialIOR,
  29119. materialIridescence: materialIridescence,
  29120. materialIridescenceIOR: materialIridescenceIOR,
  29121. materialIridescenceThickness: materialIridescenceThickness,
  29122. materialLightMap: materialLightMap,
  29123. materialLineDashOffset: materialLineDashOffset,
  29124. materialLineDashSize: materialLineDashSize,
  29125. materialLineGapSize: materialLineGapSize,
  29126. materialLineScale: materialLineScale,
  29127. materialLineWidth: materialLineWidth,
  29128. materialMetalness: materialMetalness,
  29129. materialNormal: materialNormal,
  29130. materialOpacity: materialOpacity,
  29131. materialPointSize: materialPointSize,
  29132. materialReference: materialReference,
  29133. materialReflectivity: materialReflectivity,
  29134. materialRefractionRatio: materialRefractionRatio,
  29135. materialRotation: materialRotation,
  29136. materialRoughness: materialRoughness,
  29137. materialSheen: materialSheen,
  29138. materialSheenRoughness: materialSheenRoughness,
  29139. materialShininess: materialShininess,
  29140. materialSpecular: materialSpecular,
  29141. materialSpecularColor: materialSpecularColor,
  29142. materialSpecularIntensity: materialSpecularIntensity,
  29143. materialSpecularStrength: materialSpecularStrength,
  29144. materialThickness: materialThickness,
  29145. materialTransmission: materialTransmission,
  29146. max: max$1,
  29147. maxMipLevel: maxMipLevel,
  29148. mediumpModelViewMatrix: mediumpModelViewMatrix,
  29149. metalness: metalness,
  29150. min: min$1,
  29151. mix: mix,
  29152. mixElement: mixElement,
  29153. mod: mod,
  29154. modInt: modInt,
  29155. modelDirection: modelDirection,
  29156. modelNormalMatrix: modelNormalMatrix,
  29157. modelPosition: modelPosition,
  29158. modelRadius: modelRadius,
  29159. modelScale: modelScale,
  29160. modelViewMatrix: modelViewMatrix,
  29161. modelViewPosition: modelViewPosition,
  29162. modelViewProjection: modelViewProjection,
  29163. modelWorldMatrix: modelWorldMatrix,
  29164. modelWorldMatrixInverse: modelWorldMatrixInverse,
  29165. morphReference: morphReference,
  29166. mrt: mrt,
  29167. mul: mul,
  29168. mx_aastep: mx_aastep,
  29169. mx_cell_noise_float: mx_cell_noise_float,
  29170. mx_contrast: mx_contrast,
  29171. mx_fractal_noise_float: mx_fractal_noise_float,
  29172. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  29173. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  29174. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  29175. mx_hsvtorgb: mx_hsvtorgb,
  29176. mx_noise_float: mx_noise_float,
  29177. mx_noise_vec3: mx_noise_vec3,
  29178. mx_noise_vec4: mx_noise_vec4,
  29179. mx_ramplr: mx_ramplr,
  29180. mx_ramptb: mx_ramptb,
  29181. mx_rgbtohsv: mx_rgbtohsv,
  29182. mx_safepower: mx_safepower,
  29183. mx_splitlr: mx_splitlr,
  29184. mx_splittb: mx_splittb,
  29185. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  29186. mx_transform_uv: mx_transform_uv,
  29187. mx_worley_noise_float: mx_worley_noise_float,
  29188. mx_worley_noise_vec2: mx_worley_noise_vec2,
  29189. mx_worley_noise_vec3: mx_worley_noise_vec3,
  29190. negate: negate,
  29191. neutralToneMapping: neutralToneMapping,
  29192. nodeArray: nodeArray,
  29193. nodeImmutable: nodeImmutable,
  29194. nodeObject: nodeObject,
  29195. nodeObjects: nodeObjects,
  29196. nodeProxy: nodeProxy,
  29197. normalFlat: normalFlat,
  29198. normalGeometry: normalGeometry,
  29199. normalLocal: normalLocal,
  29200. normalMap: normalMap,
  29201. normalView: normalView,
  29202. normalWorld: normalWorld,
  29203. normalize: normalize,
  29204. not: not,
  29205. notEqual: notEqual,
  29206. numWorkgroups: numWorkgroups,
  29207. objectDirection: objectDirection,
  29208. objectGroup: objectGroup,
  29209. objectPosition: objectPosition,
  29210. objectRadius: objectRadius,
  29211. objectScale: objectScale,
  29212. objectViewPosition: objectViewPosition,
  29213. objectWorldMatrix: objectWorldMatrix,
  29214. oneMinus: oneMinus,
  29215. or: or,
  29216. orthographicDepthToViewZ: orthographicDepthToViewZ,
  29217. oscSawtooth: oscSawtooth,
  29218. oscSine: oscSine,
  29219. oscSquare: oscSquare,
  29220. oscTriangle: oscTriangle,
  29221. output: output,
  29222. outputStruct: outputStruct,
  29223. overlay: overlay,
  29224. overloadingFn: overloadingFn,
  29225. parabola: parabola,
  29226. parallaxDirection: parallaxDirection,
  29227. parallaxUV: parallaxUV,
  29228. parameter: parameter,
  29229. pass: pass,
  29230. passTexture: passTexture,
  29231. pcurve: pcurve,
  29232. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  29233. pmremTexture: pmremTexture,
  29234. pointShadow: pointShadow,
  29235. pointUV: pointUV,
  29236. pointWidth: pointWidth,
  29237. positionGeometry: positionGeometry,
  29238. positionLocal: positionLocal,
  29239. positionPrevious: positionPrevious,
  29240. positionView: positionView,
  29241. positionViewDirection: positionViewDirection,
  29242. positionWorld: positionWorld,
  29243. positionWorldDirection: positionWorldDirection,
  29244. posterize: posterize,
  29245. pow: pow,
  29246. pow2: pow2,
  29247. pow3: pow3,
  29248. pow4: pow4,
  29249. property: property,
  29250. radians: radians,
  29251. rand: rand,
  29252. range: range,
  29253. rangeFog: rangeFog,
  29254. rangeFogFactor: rangeFogFactor,
  29255. reciprocal: reciprocal,
  29256. reference: reference,
  29257. referenceBuffer: referenceBuffer,
  29258. reflect: reflect,
  29259. reflectVector: reflectVector,
  29260. reflectView: reflectView,
  29261. reflector: reflector,
  29262. refract: refract,
  29263. refractVector: refractVector,
  29264. refractView: refractView,
  29265. reinhardToneMapping: reinhardToneMapping,
  29266. remainder: remainder,
  29267. remap: remap,
  29268. remapClamp: remapClamp,
  29269. renderGroup: renderGroup,
  29270. renderOutput: renderOutput,
  29271. rendererReference: rendererReference,
  29272. rotate: rotate,
  29273. rotateUV: rotateUV,
  29274. roughness: roughness,
  29275. round: round,
  29276. rtt: rtt,
  29277. sRGBTransferEOTF: sRGBTransferEOTF,
  29278. sRGBTransferOETF: sRGBTransferOETF,
  29279. sampler: sampler,
  29280. samplerComparison: samplerComparison,
  29281. saturate: saturate,
  29282. saturation: saturation,
  29283. screen: screen,
  29284. screenCoordinate: screenCoordinate,
  29285. screenSize: screenSize,
  29286. screenUV: screenUV,
  29287. scriptable: scriptable,
  29288. scriptableValue: scriptableValue,
  29289. select: select,
  29290. setCurrentStack: setCurrentStack,
  29291. shaderStages: shaderStages,
  29292. shadow: shadow,
  29293. shadowPositionWorld: shadowPositionWorld,
  29294. shapeCircle: shapeCircle,
  29295. sharedUniformGroup: sharedUniformGroup,
  29296. sheen: sheen,
  29297. sheenRoughness: sheenRoughness,
  29298. shiftLeft: shiftLeft,
  29299. shiftRight: shiftRight,
  29300. shininess: shininess,
  29301. sign: sign,
  29302. sin: sin,
  29303. sinc: sinc,
  29304. skinning: skinning,
  29305. skinningReference: skinningReference,
  29306. smoothstep: smoothstep,
  29307. smoothstepElement: smoothstepElement,
  29308. specularColor: specularColor,
  29309. specularF90: specularF90,
  29310. spherizeUV: spherizeUV,
  29311. split: split,
  29312. spritesheetUV: spritesheetUV,
  29313. sqrt: sqrt,
  29314. stack: stack,
  29315. step: step,
  29316. storage: storage,
  29317. storageBarrier: storageBarrier,
  29318. storageObject: storageObject,
  29319. storageTexture: storageTexture,
  29320. string: string,
  29321. struct: struct,
  29322. sub: sub,
  29323. subgroupIndex: subgroupIndex,
  29324. subgroupSize: subgroupSize,
  29325. tan: tan,
  29326. tangentGeometry: tangentGeometry,
  29327. tangentLocal: tangentLocal,
  29328. tangentView: tangentView,
  29329. tangentWorld: tangentWorld,
  29330. temp: temp,
  29331. texture: texture,
  29332. texture3D: texture3D,
  29333. textureBarrier: textureBarrier,
  29334. textureBicubic: textureBicubic,
  29335. textureCubeUV: textureCubeUV,
  29336. textureLoad: textureLoad,
  29337. textureSize: textureSize,
  29338. textureStore: textureStore,
  29339. thickness: thickness,
  29340. time: time,
  29341. timerDelta: timerDelta,
  29342. timerGlobal: timerGlobal,
  29343. timerLocal: timerLocal,
  29344. toOutputColorSpace: toOutputColorSpace,
  29345. toWorkingColorSpace: toWorkingColorSpace,
  29346. toneMapping: toneMapping,
  29347. toneMappingExposure: toneMappingExposure,
  29348. toonOutlinePass: toonOutlinePass,
  29349. transformDirection: transformDirection,
  29350. transformNormal: transformNormal,
  29351. transformNormalToView: transformNormalToView,
  29352. transformedBentNormalView: transformedBentNormalView,
  29353. transformedBitangentView: transformedBitangentView,
  29354. transformedBitangentWorld: transformedBitangentWorld,
  29355. transformedClearcoatNormalView: transformedClearcoatNormalView,
  29356. transformedNormalView: transformedNormalView,
  29357. transformedNormalWorld: transformedNormalWorld,
  29358. transformedTangentView: transformedTangentView,
  29359. transformedTangentWorld: transformedTangentWorld,
  29360. transmission: transmission,
  29361. transpose: transpose,
  29362. triNoise3D: triNoise3D,
  29363. triplanarTexture: triplanarTexture,
  29364. triplanarTextures: triplanarTextures,
  29365. trunc: trunc,
  29366. tslFn: tslFn,
  29367. uint: uint,
  29368. uniform: uniform,
  29369. uniformArray: uniformArray,
  29370. uniformGroup: uniformGroup,
  29371. uniforms: uniforms,
  29372. userData: userData,
  29373. uv: uv,
  29374. uvec2: uvec2,
  29375. uvec3: uvec3,
  29376. uvec4: uvec4,
  29377. varying: varying,
  29378. varyingProperty: varyingProperty,
  29379. vec2: vec2,
  29380. vec3: vec3,
  29381. vec4: vec4,
  29382. vectorComponents: vectorComponents,
  29383. velocity: velocity,
  29384. vertexColor: vertexColor,
  29385. vertexIndex: vertexIndex,
  29386. vertexStage: vertexStage,
  29387. vibrance: vibrance,
  29388. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  29389. viewZToOrthographicDepth: viewZToOrthographicDepth,
  29390. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  29391. viewport: viewport,
  29392. viewportBottomLeft: viewportBottomLeft,
  29393. viewportCoordinate: viewportCoordinate,
  29394. viewportDepthTexture: viewportDepthTexture,
  29395. viewportLinearDepth: viewportLinearDepth,
  29396. viewportMipTexture: viewportMipTexture,
  29397. viewportResolution: viewportResolution,
  29398. viewportSafeUV: viewportSafeUV,
  29399. viewportSharedTexture: viewportSharedTexture,
  29400. viewportSize: viewportSize,
  29401. viewportTexture: viewportTexture,
  29402. viewportTopLeft: viewportTopLeft,
  29403. viewportUV: viewportUV,
  29404. wgsl: wgsl,
  29405. wgslFn: wgslFn,
  29406. workgroupArray: workgroupArray,
  29407. workgroupBarrier: workgroupBarrier,
  29408. workgroupId: workgroupId,
  29409. workingToColorSpace: workingToColorSpace,
  29410. xor: xor
  29411. });
  29412. const _clearColor = /*@__PURE__*/ new Color4();
  29413. /**
  29414. * This renderer module manages the background.
  29415. *
  29416. * @private
  29417. * @augments DataMap
  29418. */
  29419. class Background extends DataMap {
  29420. /**
  29421. * Constructs a new background management component.
  29422. *
  29423. * @param {Renderer} renderer - The renderer.
  29424. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  29425. */
  29426. constructor( renderer, nodes ) {
  29427. super();
  29428. /**
  29429. * The renderer.
  29430. *
  29431. * @type {Renderer}
  29432. */
  29433. this.renderer = renderer;
  29434. /**
  29435. * Renderer component for managing nodes related logic.
  29436. *
  29437. * @type {Nodes}
  29438. */
  29439. this.nodes = nodes;
  29440. }
  29441. /**
  29442. * Updates the background for the given scene. Depending on how `Scene.background`
  29443. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  29444. * or add a mesh to the render list for rendering the background as a textured plane
  29445. * or skybox.
  29446. *
  29447. * @param {Scene} scene - The scene.
  29448. * @param {RenderList} renderList - The current render list.
  29449. * @param {RenderContext} renderContext - The current render context.
  29450. */
  29451. update( scene, renderList, renderContext ) {
  29452. const renderer = this.renderer;
  29453. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  29454. let forceClear = false;
  29455. if ( background === null ) {
  29456. // no background settings, use clear color configuration from the renderer
  29457. renderer._clearColor.getRGB( _clearColor );
  29458. _clearColor.a = renderer._clearColor.a;
  29459. } else if ( background.isColor === true ) {
  29460. // background is an opaque color
  29461. background.getRGB( _clearColor );
  29462. _clearColor.a = 1;
  29463. forceClear = true;
  29464. } else if ( background.isNode === true ) {
  29465. const sceneData = this.get( scene );
  29466. const backgroundNode = background;
  29467. _clearColor.copy( renderer._clearColor );
  29468. let backgroundMesh = sceneData.backgroundMesh;
  29469. if ( backgroundMesh === undefined ) {
  29470. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  29471. // @TODO: Add Texture2D support using node context
  29472. getUV: () => backgroundRotation.mul( normalWorld ),
  29473. getTextureLevel: () => backgroundBlurriness
  29474. } );
  29475. let viewProj = modelViewProjection;
  29476. viewProj = viewProj.setZ( viewProj.w );
  29477. const nodeMaterial = new NodeMaterial();
  29478. nodeMaterial.name = 'Background.material';
  29479. nodeMaterial.side = BackSide;
  29480. nodeMaterial.depthTest = false;
  29481. nodeMaterial.depthWrite = false;
  29482. nodeMaterial.allowOverride = false;
  29483. nodeMaterial.fog = false;
  29484. nodeMaterial.lights = false;
  29485. nodeMaterial.vertexNode = viewProj;
  29486. nodeMaterial.colorNode = backgroundMeshNode;
  29487. sceneData.backgroundMeshNode = backgroundMeshNode;
  29488. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  29489. backgroundMesh.frustumCulled = false;
  29490. backgroundMesh.name = 'Background.mesh';
  29491. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  29492. this.matrixWorld.copyPosition( camera.matrixWorld );
  29493. };
  29494. }
  29495. const backgroundCacheKey = backgroundNode.getCacheKey();
  29496. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  29497. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  29498. sceneData.backgroundMeshNode.needsUpdate = true;
  29499. backgroundMesh.material.needsUpdate = true;
  29500. sceneData.backgroundCacheKey = backgroundCacheKey;
  29501. }
  29502. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  29503. } else {
  29504. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  29505. }
  29506. //
  29507. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  29508. if ( environmentBlendMode === 'additive' ) {
  29509. _clearColor.set( 0, 0, 0, 1 );
  29510. } else if ( environmentBlendMode === 'alpha-blend' ) {
  29511. _clearColor.set( 0, 0, 0, 0 );
  29512. }
  29513. //
  29514. if ( renderer.autoClear === true || forceClear === true ) {
  29515. const clearColorValue = renderContext.clearColorValue;
  29516. clearColorValue.r = _clearColor.r;
  29517. clearColorValue.g = _clearColor.g;
  29518. clearColorValue.b = _clearColor.b;
  29519. clearColorValue.a = _clearColor.a;
  29520. // premultiply alpha
  29521. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  29522. clearColorValue.r *= clearColorValue.a;
  29523. clearColorValue.g *= clearColorValue.a;
  29524. clearColorValue.b *= clearColorValue.a;
  29525. }
  29526. //
  29527. renderContext.depthClearValue = renderer._clearDepth;
  29528. renderContext.stencilClearValue = renderer._clearStencil;
  29529. renderContext.clearColor = renderer.autoClearColor === true;
  29530. renderContext.clearDepth = renderer.autoClearDepth === true;
  29531. renderContext.clearStencil = renderer.autoClearStencil === true;
  29532. } else {
  29533. renderContext.clearColor = false;
  29534. renderContext.clearDepth = false;
  29535. renderContext.clearStencil = false;
  29536. }
  29537. }
  29538. }
  29539. let _id$6 = 0;
  29540. /**
  29541. * A bind group represents a collection of bindings and thus a collection
  29542. * or resources. Bind groups are assigned to pipelines to provide them
  29543. * with the required resources (like uniform buffers or textures).
  29544. *
  29545. * @private
  29546. */
  29547. class BindGroup {
  29548. /**
  29549. * Constructs a new bind group.
  29550. *
  29551. * @param {string} name - The bind group's name.
  29552. * @param {Array<Binding>} bindings - An array of bindings.
  29553. * @param {number} index - The group index.
  29554. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  29555. */
  29556. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  29557. /**
  29558. * The bind group's name.
  29559. *
  29560. * @type {string}
  29561. */
  29562. this.name = name;
  29563. /**
  29564. * An array of bindings.
  29565. *
  29566. * @type {Array<Binding>}
  29567. */
  29568. this.bindings = bindings;
  29569. /**
  29570. * The group index.
  29571. *
  29572. * @type {number}
  29573. */
  29574. this.index = index;
  29575. /**
  29576. * An array of reference bindings.
  29577. *
  29578. * @type {Array<Binding>}
  29579. */
  29580. this.bindingsReference = bindingsReference;
  29581. /**
  29582. * The group's ID.
  29583. *
  29584. * @type {number}
  29585. */
  29586. this.id = _id$6 ++;
  29587. }
  29588. }
  29589. /**
  29590. * This module represents the state of a node builder after it was
  29591. * used to build the nodes for a render object. The state holds the
  29592. * results of the build for further processing in the renderer.
  29593. *
  29594. * Render objects with identical cache keys share the same node builder state.
  29595. *
  29596. * @private
  29597. */
  29598. class NodeBuilderState {
  29599. /**
  29600. * Constructs a new node builder state.
  29601. *
  29602. * @param {string} vertexShader - The native vertex shader code.
  29603. * @param {string} fragmentShader - The native fragment shader code.
  29604. * @param {string} computeShader - The native compute shader code.
  29605. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  29606. * @param {Array<BindGroup>} bindings - An array of bind groups.
  29607. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  29608. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  29609. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  29610. * @param {NodeMaterialObserver} observer - A node material observer.
  29611. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  29612. */
  29613. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  29614. /**
  29615. * The native vertex shader code.
  29616. *
  29617. * @type {string}
  29618. */
  29619. this.vertexShader = vertexShader;
  29620. /**
  29621. * The native fragment shader code.
  29622. *
  29623. * @type {string}
  29624. */
  29625. this.fragmentShader = fragmentShader;
  29626. /**
  29627. * The native compute shader code.
  29628. *
  29629. * @type {string}
  29630. */
  29631. this.computeShader = computeShader;
  29632. /**
  29633. * An array with transform attribute objects.
  29634. * Only relevant when using compute shaders with WebGL 2.
  29635. *
  29636. * @type {Array<Object>}
  29637. */
  29638. this.transforms = transforms;
  29639. /**
  29640. * An array of node attributes representing
  29641. * the attributes of the shaders.
  29642. *
  29643. * @type {Array<NodeAttribute>}
  29644. */
  29645. this.nodeAttributes = nodeAttributes;
  29646. /**
  29647. * An array of bind groups representing the uniform or storage
  29648. * buffers, texture or samplers of the shader.
  29649. *
  29650. * @type {Array<BindGroup>}
  29651. */
  29652. this.bindings = bindings;
  29653. /**
  29654. * An array of nodes that implement their `update()` method.
  29655. *
  29656. * @type {Array<Node>}
  29657. */
  29658. this.updateNodes = updateNodes;
  29659. /**
  29660. * An array of nodes that implement their `updateBefore()` method.
  29661. *
  29662. * @type {Array<Node>}
  29663. */
  29664. this.updateBeforeNodes = updateBeforeNodes;
  29665. /**
  29666. * An array of nodes that implement their `updateAfter()` method.
  29667. *
  29668. * @type {Array<Node>}
  29669. */
  29670. this.updateAfterNodes = updateAfterNodes;
  29671. /**
  29672. * A node material observer.
  29673. *
  29674. * @type {NodeMaterialObserver}
  29675. */
  29676. this.observer = observer;
  29677. /**
  29678. * How often this state is used by render objects.
  29679. *
  29680. * @type {number}
  29681. */
  29682. this.usedTimes = 0;
  29683. }
  29684. /**
  29685. * This method is used to create a array of bind groups based
  29686. * on the existing bind groups of this state. Shared groups are
  29687. * not cloned.
  29688. *
  29689. * @return {Array<BindGroup>} A array of bind groups.
  29690. */
  29691. createBindings() {
  29692. const bindings = [];
  29693. for ( const instanceGroup of this.bindings ) {
  29694. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  29695. if ( shared !== true ) {
  29696. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  29697. bindings.push( bindingsGroup );
  29698. for ( const instanceBinding of instanceGroup.bindings ) {
  29699. bindingsGroup.bindings.push( instanceBinding.clone() );
  29700. }
  29701. } else {
  29702. bindings.push( instanceGroup );
  29703. }
  29704. }
  29705. return bindings;
  29706. }
  29707. }
  29708. /**
  29709. * {@link NodeBuilder} is going to create instances of this class during the build process
  29710. * of nodes. They represent the final shader attributes that are going to be generated
  29711. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  29712. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  29713. */
  29714. class NodeAttribute {
  29715. /**
  29716. * Constructs a new node attribute.
  29717. *
  29718. * @param {string} name - The name of the attribute.
  29719. * @param {string} type - The type of the attribute.
  29720. * @param {?Node} node - An optional reference to the node.
  29721. */
  29722. constructor( name, type, node = null ) {
  29723. /**
  29724. * This flag can be used for type testing.
  29725. *
  29726. * @type {boolean}
  29727. * @readonly
  29728. * @default true
  29729. */
  29730. this.isNodeAttribute = true;
  29731. /**
  29732. * The name of the attribute.
  29733. *
  29734. * @type {string}
  29735. */
  29736. this.name = name;
  29737. /**
  29738. * The type of the attribute.
  29739. *
  29740. * @type {string}
  29741. */
  29742. this.type = type;
  29743. /**
  29744. * An optional reference to the node.
  29745. *
  29746. * @type {?Node}
  29747. * @default null
  29748. */
  29749. this.node = node;
  29750. }
  29751. }
  29752. /**
  29753. * {@link NodeBuilder} is going to create instances of this class during the build process
  29754. * of nodes. They represent the final shader uniforms that are going to be generated
  29755. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  29756. * for this purpose.
  29757. */
  29758. class NodeUniform {
  29759. /**
  29760. * Constructs a new node uniform.
  29761. *
  29762. * @param {string} name - The name of the uniform.
  29763. * @param {string} type - The type of the uniform.
  29764. * @param {UniformNode} node - An reference to the node.
  29765. */
  29766. constructor( name, type, node ) {
  29767. /**
  29768. * This flag can be used for type testing.
  29769. *
  29770. * @type {boolean}
  29771. * @readonly
  29772. * @default true
  29773. */
  29774. this.isNodeUniform = true;
  29775. /**
  29776. * The name of the uniform.
  29777. *
  29778. * @type {string}
  29779. */
  29780. this.name = name;
  29781. /**
  29782. * The type of the uniform.
  29783. *
  29784. * @type {string}
  29785. */
  29786. this.type = type;
  29787. /**
  29788. * An reference to the node.
  29789. *
  29790. * @type {UniformNode}
  29791. */
  29792. this.node = node.getSelf();
  29793. }
  29794. /**
  29795. * The value of the uniform node.
  29796. *
  29797. * @type {any}
  29798. */
  29799. get value() {
  29800. return this.node.value;
  29801. }
  29802. set value( val ) {
  29803. this.node.value = val;
  29804. }
  29805. /**
  29806. * The id of the uniform node.
  29807. *
  29808. * @type {number}
  29809. */
  29810. get id() {
  29811. return this.node.id;
  29812. }
  29813. /**
  29814. * The uniform node's group.
  29815. *
  29816. * @type {UniformGroupNode}
  29817. */
  29818. get groupNode() {
  29819. return this.node.groupNode;
  29820. }
  29821. }
  29822. /**
  29823. * {@link NodeBuilder} is going to create instances of this class during the build process
  29824. * of nodes. They represent the final shader variables that are going to be generated
  29825. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  29826. * this purpose.
  29827. */
  29828. class NodeVar {
  29829. /**
  29830. * Constructs a new node variable.
  29831. *
  29832. * @param {string} name - The name of the variable.
  29833. * @param {string} type - The type of the variable.
  29834. * @param {boolean} [readOnly=false] - The read-only flag.
  29835. * @param {?number} [count=null] - The size.
  29836. */
  29837. constructor( name, type, readOnly = false, count = null ) {
  29838. /**
  29839. * This flag can be used for type testing.
  29840. *
  29841. * @type {boolean}
  29842. * @readonly
  29843. * @default true
  29844. */
  29845. this.isNodeVar = true;
  29846. /**
  29847. * The name of the variable.
  29848. *
  29849. * @type {string}
  29850. */
  29851. this.name = name;
  29852. /**
  29853. * The type of the variable.
  29854. *
  29855. * @type {string}
  29856. */
  29857. this.type = type;
  29858. /**
  29859. * The read-only flag.
  29860. *
  29861. * @type {boolean}
  29862. */
  29863. this.readOnly = readOnly;
  29864. /**
  29865. * The size.
  29866. *
  29867. * @type {?number}
  29868. */
  29869. this.count = count;
  29870. }
  29871. }
  29872. /**
  29873. * {@link NodeBuilder} is going to create instances of this class during the build process
  29874. * of nodes. They represent the final shader varyings that are going to be generated
  29875. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  29876. * this purpose.
  29877. *
  29878. * @augments NodeVar
  29879. */
  29880. class NodeVarying extends NodeVar {
  29881. /**
  29882. * Constructs a new node varying.
  29883. *
  29884. * @param {string} name - The name of the varying.
  29885. * @param {string} type - The type of the varying.
  29886. */
  29887. constructor( name, type ) {
  29888. super( name, type );
  29889. /**
  29890. * Whether this varying requires interpolation or not. This property can be used
  29891. * to check if the varying can be optimized for a variable.
  29892. *
  29893. * @type {boolean}
  29894. * @default false
  29895. */
  29896. this.needsInterpolation = false;
  29897. /**
  29898. * This flag can be used for type testing.
  29899. *
  29900. * @type {boolean}
  29901. * @readonly
  29902. * @default true
  29903. */
  29904. this.isNodeVarying = true;
  29905. }
  29906. }
  29907. /**
  29908. * {@link NodeBuilder} is going to create instances of this class during the build process
  29909. * of nodes. They represent user-defined, native shader code portions that are going to be
  29910. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  29911. * for this purpose.
  29912. */
  29913. class NodeCode {
  29914. /**
  29915. * Constructs a new code node.
  29916. *
  29917. * @param {string} name - The name of the code.
  29918. * @param {string} type - The node type.
  29919. * @param {string} [code=''] - The native shader code.
  29920. */
  29921. constructor( name, type, code = '' ) {
  29922. /**
  29923. * The name of the code.
  29924. *
  29925. * @type {string}
  29926. */
  29927. this.name = name;
  29928. /**
  29929. * The node type.
  29930. *
  29931. * @type {string}
  29932. */
  29933. this.type = type;
  29934. /**
  29935. * The native shader code.
  29936. *
  29937. * @type {string}
  29938. * @default ''
  29939. */
  29940. this.code = code;
  29941. Object.defineProperty( this, 'isNodeCode', { value: true } );
  29942. }
  29943. }
  29944. let _id$5 = 0;
  29945. /**
  29946. * This utility class is used in {@link NodeBuilder} as an internal
  29947. * cache data structure for node data.
  29948. */
  29949. class NodeCache {
  29950. /**
  29951. * Constructs a new node cache.
  29952. *
  29953. * @param {?NodeCache} parent - A reference to a parent cache.
  29954. */
  29955. constructor( parent = null ) {
  29956. /**
  29957. * The id of the cache.
  29958. *
  29959. * @type {number}
  29960. * @readonly
  29961. */
  29962. this.id = _id$5 ++;
  29963. /**
  29964. * A weak map for managing node data.
  29965. *
  29966. * @type {WeakMap<Node, Object>}
  29967. */
  29968. this.nodesData = new WeakMap();
  29969. /**
  29970. * Reference to a parent node cache.
  29971. *
  29972. * @type {?NodeCache}
  29973. * @default null
  29974. */
  29975. this.parent = parent;
  29976. }
  29977. /**
  29978. * Returns the data for the given node.
  29979. *
  29980. * @param {Node} node - The node.
  29981. * @return {?Object} The data for the node.
  29982. */
  29983. getData( node ) {
  29984. let data = this.nodesData.get( node );
  29985. if ( data === undefined && this.parent !== null ) {
  29986. data = this.parent.getData( node );
  29987. }
  29988. return data;
  29989. }
  29990. /**
  29991. * Sets the data for a given node.
  29992. *
  29993. * @param {Node} node - The node.
  29994. * @param {Object} data - The data that should be cached.
  29995. */
  29996. setData( node, data ) {
  29997. this.nodesData.set( node, data );
  29998. }
  29999. }
  30000. class StructType {
  30001. constructor( name, members ) {
  30002. this.name = name;
  30003. this.members = members;
  30004. this.output = false;
  30005. }
  30006. }
  30007. /**
  30008. * Abstract base class for uniforms.
  30009. *
  30010. * @abstract
  30011. * @private
  30012. */
  30013. class Uniform {
  30014. /**
  30015. * Constructs a new uniform.
  30016. *
  30017. * @param {string} name - The uniform's name.
  30018. * @param {any} value - The uniform's value.
  30019. */
  30020. constructor( name, value ) {
  30021. /**
  30022. * The uniform's name.
  30023. *
  30024. * @type {string}
  30025. */
  30026. this.name = name;
  30027. /**
  30028. * The uniform's value.
  30029. *
  30030. * @type {any}
  30031. */
  30032. this.value = value;
  30033. /**
  30034. * Used to build the uniform buffer according to the STD140 layout.
  30035. * Derived uniforms will set this property to a data type specific
  30036. * value.
  30037. *
  30038. * @type {number}
  30039. */
  30040. this.boundary = 0;
  30041. /**
  30042. * The item size. Derived uniforms will set this property to a data
  30043. * type specific value.
  30044. *
  30045. * @type {number}
  30046. */
  30047. this.itemSize = 0;
  30048. /**
  30049. * This property is set by {@link UniformsGroup} and marks
  30050. * the start position in the uniform buffer.
  30051. *
  30052. * @type {number}
  30053. */
  30054. this.offset = 0;
  30055. }
  30056. /**
  30057. * Sets the uniform's value.
  30058. *
  30059. * @param {any} value - The value to set.
  30060. */
  30061. setValue( value ) {
  30062. this.value = value;
  30063. }
  30064. /**
  30065. * Returns the uniform's value.
  30066. *
  30067. * @return {any} The value.
  30068. */
  30069. getValue() {
  30070. return this.value;
  30071. }
  30072. }
  30073. /**
  30074. * Represents a Number uniform.
  30075. *
  30076. * @private
  30077. * @augments Uniform
  30078. */
  30079. class NumberUniform extends Uniform {
  30080. /**
  30081. * Constructs a new Number uniform.
  30082. *
  30083. * @param {string} name - The uniform's name.
  30084. * @param {number} value - The uniform's value.
  30085. */
  30086. constructor( name, value = 0 ) {
  30087. super( name, value );
  30088. /**
  30089. * This flag can be used for type testing.
  30090. *
  30091. * @type {boolean}
  30092. * @readonly
  30093. * @default true
  30094. */
  30095. this.isNumberUniform = true;
  30096. this.boundary = 4;
  30097. this.itemSize = 1;
  30098. }
  30099. }
  30100. /**
  30101. * Represents a Vector2 uniform.
  30102. *
  30103. * @private
  30104. * @augments Uniform
  30105. */
  30106. class Vector2Uniform extends Uniform {
  30107. /**
  30108. * Constructs a new Number uniform.
  30109. *
  30110. * @param {string} name - The uniform's name.
  30111. * @param {Vector2} value - The uniform's value.
  30112. */
  30113. constructor( name, value = new Vector2() ) {
  30114. super( name, value );
  30115. /**
  30116. * This flag can be used for type testing.
  30117. *
  30118. * @type {boolean}
  30119. * @readonly
  30120. * @default true
  30121. */
  30122. this.isVector2Uniform = true;
  30123. this.boundary = 8;
  30124. this.itemSize = 2;
  30125. }
  30126. }
  30127. /**
  30128. * Represents a Vector3 uniform.
  30129. *
  30130. * @private
  30131. * @augments Uniform
  30132. */
  30133. class Vector3Uniform extends Uniform {
  30134. /**
  30135. * Constructs a new Number uniform.
  30136. *
  30137. * @param {string} name - The uniform's name.
  30138. * @param {Vector3} value - The uniform's value.
  30139. */
  30140. constructor( name, value = new Vector3() ) {
  30141. super( name, value );
  30142. /**
  30143. * This flag can be used for type testing.
  30144. *
  30145. * @type {boolean}
  30146. * @readonly
  30147. * @default true
  30148. */
  30149. this.isVector3Uniform = true;
  30150. this.boundary = 16;
  30151. this.itemSize = 3;
  30152. }
  30153. }
  30154. /**
  30155. * Represents a Vector4 uniform.
  30156. *
  30157. * @private
  30158. * @augments Uniform
  30159. */
  30160. class Vector4Uniform extends Uniform {
  30161. /**
  30162. * Constructs a new Number uniform.
  30163. *
  30164. * @param {string} name - The uniform's name.
  30165. * @param {Vector4} value - The uniform's value.
  30166. */
  30167. constructor( name, value = new Vector4() ) {
  30168. super( name, value );
  30169. /**
  30170. * This flag can be used for type testing.
  30171. *
  30172. * @type {boolean}
  30173. * @readonly
  30174. * @default true
  30175. */
  30176. this.isVector4Uniform = true;
  30177. this.boundary = 16;
  30178. this.itemSize = 4;
  30179. }
  30180. }
  30181. /**
  30182. * Represents a Color uniform.
  30183. *
  30184. * @private
  30185. * @augments Uniform
  30186. */
  30187. class ColorUniform extends Uniform {
  30188. /**
  30189. * Constructs a new Number uniform.
  30190. *
  30191. * @param {string} name - The uniform's name.
  30192. * @param {Color} value - The uniform's value.
  30193. */
  30194. constructor( name, value = new Color() ) {
  30195. super( name, value );
  30196. /**
  30197. * This flag can be used for type testing.
  30198. *
  30199. * @type {boolean}
  30200. * @readonly
  30201. * @default true
  30202. */
  30203. this.isColorUniform = true;
  30204. this.boundary = 16;
  30205. this.itemSize = 3;
  30206. }
  30207. }
  30208. /**
  30209. * Represents a Matrix2 uniform.
  30210. *
  30211. * @private
  30212. * @augments Uniform
  30213. */
  30214. class Matrix2Uniform extends Uniform {
  30215. /**
  30216. * Constructs a new Number uniform.
  30217. *
  30218. * @param {string} name - The uniform's name.
  30219. * @param {Matrix2} value - The uniform's value.
  30220. */
  30221. constructor( name, value = new Matrix2() ) {
  30222. super( name, value );
  30223. /**
  30224. * This flag can be used for type testing.
  30225. *
  30226. * @type {boolean}
  30227. * @readonly
  30228. * @default true
  30229. */
  30230. this.isMatrix2Uniform = true;
  30231. this.boundary = 16;
  30232. this.itemSize = 4;
  30233. }
  30234. }
  30235. /**
  30236. * Represents a Matrix3 uniform.
  30237. *
  30238. * @private
  30239. * @augments Uniform
  30240. */
  30241. class Matrix3Uniform extends Uniform {
  30242. /**
  30243. * Constructs a new Number uniform.
  30244. *
  30245. * @param {string} name - The uniform's name.
  30246. * @param {Matrix3} value - The uniform's value.
  30247. */
  30248. constructor( name, value = new Matrix3() ) {
  30249. super( name, value );
  30250. /**
  30251. * This flag can be used for type testing.
  30252. *
  30253. * @type {boolean}
  30254. * @readonly
  30255. * @default true
  30256. */
  30257. this.isMatrix3Uniform = true;
  30258. this.boundary = 48;
  30259. this.itemSize = 12;
  30260. }
  30261. }
  30262. /**
  30263. * Represents a Matrix4 uniform.
  30264. *
  30265. * @private
  30266. * @augments Uniform
  30267. */
  30268. class Matrix4Uniform extends Uniform {
  30269. /**
  30270. * Constructs a new Number uniform.
  30271. *
  30272. * @param {string} name - The uniform's name.
  30273. * @param {Matrix4} value - The uniform's value.
  30274. */
  30275. constructor( name, value = new Matrix4() ) {
  30276. super( name, value );
  30277. /**
  30278. * This flag can be used for type testing.
  30279. *
  30280. * @type {boolean}
  30281. * @readonly
  30282. * @default true
  30283. */
  30284. this.isMatrix4Uniform = true;
  30285. this.boundary = 64;
  30286. this.itemSize = 16;
  30287. }
  30288. }
  30289. /**
  30290. * A special form of Number uniform binding type.
  30291. * It's value is managed by a node object.
  30292. *
  30293. * @private
  30294. * @augments NumberUniform
  30295. */
  30296. class NumberNodeUniform extends NumberUniform {
  30297. /**
  30298. * Constructs a new node-based Number uniform.
  30299. *
  30300. * @param {NodeUniform} nodeUniform - The node uniform.
  30301. */
  30302. constructor( nodeUniform ) {
  30303. super( nodeUniform.name, nodeUniform.value );
  30304. /**
  30305. * The node uniform.
  30306. *
  30307. * @type {NodeUniform}
  30308. */
  30309. this.nodeUniform = nodeUniform;
  30310. }
  30311. /**
  30312. * Overwritten to return the value of the node uniform.
  30313. *
  30314. * @return {number} The value.
  30315. */
  30316. getValue() {
  30317. return this.nodeUniform.value;
  30318. }
  30319. /**
  30320. * Returns the node uniform data type.
  30321. *
  30322. * @return {string} The data type.
  30323. */
  30324. getType() {
  30325. return this.nodeUniform.type;
  30326. }
  30327. }
  30328. /**
  30329. * A special form of Vector2 uniform binding type.
  30330. * It's value is managed by a node object.
  30331. *
  30332. * @private
  30333. * @augments Vector2Uniform
  30334. */
  30335. class Vector2NodeUniform extends Vector2Uniform {
  30336. /**
  30337. * Constructs a new node-based Vector2 uniform.
  30338. *
  30339. * @param {NodeUniform} nodeUniform - The node uniform.
  30340. */
  30341. constructor( nodeUniform ) {
  30342. super( nodeUniform.name, nodeUniform.value );
  30343. /**
  30344. * The node uniform.
  30345. *
  30346. * @type {NodeUniform}
  30347. */
  30348. this.nodeUniform = nodeUniform;
  30349. }
  30350. /**
  30351. * Overwritten to return the value of the node uniform.
  30352. *
  30353. * @return {Vector2} The value.
  30354. */
  30355. getValue() {
  30356. return this.nodeUniform.value;
  30357. }
  30358. /**
  30359. * Returns the node uniform data type.
  30360. *
  30361. * @return {string} The data type.
  30362. */
  30363. getType() {
  30364. return this.nodeUniform.type;
  30365. }
  30366. }
  30367. /**
  30368. * A special form of Vector3 uniform binding type.
  30369. * It's value is managed by a node object.
  30370. *
  30371. * @private
  30372. * @augments Vector3Uniform
  30373. */
  30374. class Vector3NodeUniform extends Vector3Uniform {
  30375. /**
  30376. * Constructs a new node-based Vector3 uniform.
  30377. *
  30378. * @param {NodeUniform} nodeUniform - The node uniform.
  30379. */
  30380. constructor( nodeUniform ) {
  30381. super( nodeUniform.name, nodeUniform.value );
  30382. /**
  30383. * The node uniform.
  30384. *
  30385. * @type {NodeUniform}
  30386. */
  30387. this.nodeUniform = nodeUniform;
  30388. }
  30389. /**
  30390. * Overwritten to return the value of the node uniform.
  30391. *
  30392. * @return {Vector3} The value.
  30393. */
  30394. getValue() {
  30395. return this.nodeUniform.value;
  30396. }
  30397. /**
  30398. * Returns the node uniform data type.
  30399. *
  30400. * @return {string} The data type.
  30401. */
  30402. getType() {
  30403. return this.nodeUniform.type;
  30404. }
  30405. }
  30406. /**
  30407. * A special form of Vector4 uniform binding type.
  30408. * It's value is managed by a node object.
  30409. *
  30410. * @private
  30411. * @augments Vector4Uniform
  30412. */
  30413. class Vector4NodeUniform extends Vector4Uniform {
  30414. /**
  30415. * Constructs a new node-based Vector4 uniform.
  30416. *
  30417. * @param {NodeUniform} nodeUniform - The node uniform.
  30418. */
  30419. constructor( nodeUniform ) {
  30420. super( nodeUniform.name, nodeUniform.value );
  30421. /**
  30422. * The node uniform.
  30423. *
  30424. * @type {NodeUniform}
  30425. */
  30426. this.nodeUniform = nodeUniform;
  30427. }
  30428. /**
  30429. * Overwritten to return the value of the node uniform.
  30430. *
  30431. * @return {Vector4} The value.
  30432. */
  30433. getValue() {
  30434. return this.nodeUniform.value;
  30435. }
  30436. /**
  30437. * Returns the node uniform data type.
  30438. *
  30439. * @return {string} The data type.
  30440. */
  30441. getType() {
  30442. return this.nodeUniform.type;
  30443. }
  30444. }
  30445. /**
  30446. * A special form of Color uniform binding type.
  30447. * It's value is managed by a node object.
  30448. *
  30449. * @private
  30450. * @augments ColorUniform
  30451. */
  30452. class ColorNodeUniform extends ColorUniform {
  30453. /**
  30454. * Constructs a new node-based Color uniform.
  30455. *
  30456. * @param {NodeUniform} nodeUniform - The node uniform.
  30457. */
  30458. constructor( nodeUniform ) {
  30459. super( nodeUniform.name, nodeUniform.value );
  30460. /**
  30461. * The node uniform.
  30462. *
  30463. * @type {NodeUniform}
  30464. */
  30465. this.nodeUniform = nodeUniform;
  30466. }
  30467. /**
  30468. * Overwritten to return the value of the node uniform.
  30469. *
  30470. * @return {Color} The value.
  30471. */
  30472. getValue() {
  30473. return this.nodeUniform.value;
  30474. }
  30475. /**
  30476. * Returns the node uniform data type.
  30477. *
  30478. * @return {string} The data type.
  30479. */
  30480. getType() {
  30481. return this.nodeUniform.type;
  30482. }
  30483. }
  30484. /**
  30485. * A special form of Matrix2 uniform binding type.
  30486. * It's value is managed by a node object.
  30487. *
  30488. * @private
  30489. * @augments Matrix2Uniform
  30490. */
  30491. class Matrix2NodeUniform extends Matrix2Uniform {
  30492. /**
  30493. * Constructs a new node-based Matrix2 uniform.
  30494. *
  30495. * @param {NodeUniform} nodeUniform - The node uniform.
  30496. */
  30497. constructor( nodeUniform ) {
  30498. super( nodeUniform.name, nodeUniform.value );
  30499. /**
  30500. * The node uniform.
  30501. *
  30502. * @type {NodeUniform}
  30503. */
  30504. this.nodeUniform = nodeUniform;
  30505. }
  30506. /**
  30507. * Overwritten to return the value of the node uniform.
  30508. *
  30509. * @return {Matrix2} The value.
  30510. */
  30511. getValue() {
  30512. return this.nodeUniform.value;
  30513. }
  30514. /**
  30515. * Returns the node uniform data type.
  30516. *
  30517. * @return {string} The data type.
  30518. */
  30519. getType() {
  30520. return this.nodeUniform.type;
  30521. }
  30522. }
  30523. /**
  30524. * A special form of Matrix3 uniform binding type.
  30525. * It's value is managed by a node object.
  30526. *
  30527. * @private
  30528. * @augments Matrix3Uniform
  30529. */
  30530. class Matrix3NodeUniform extends Matrix3Uniform {
  30531. /**
  30532. * Constructs a new node-based Matrix3 uniform.
  30533. *
  30534. * @param {NodeUniform} nodeUniform - The node uniform.
  30535. */
  30536. constructor( nodeUniform ) {
  30537. super( nodeUniform.name, nodeUniform.value );
  30538. /**
  30539. * The node uniform.
  30540. *
  30541. * @type {NodeUniform}
  30542. */
  30543. this.nodeUniform = nodeUniform;
  30544. }
  30545. /**
  30546. * Overwritten to return the value of the node uniform.
  30547. *
  30548. * @return {Matrix3} The value.
  30549. */
  30550. getValue() {
  30551. return this.nodeUniform.value;
  30552. }
  30553. /**
  30554. * Returns the node uniform data type.
  30555. *
  30556. * @return {string} The data type.
  30557. */
  30558. getType() {
  30559. return this.nodeUniform.type;
  30560. }
  30561. }
  30562. /**
  30563. * A special form of Matrix4 uniform binding type.
  30564. * It's value is managed by a node object.
  30565. *
  30566. * @private
  30567. * @augments Matrix4Uniform
  30568. */
  30569. class Matrix4NodeUniform extends Matrix4Uniform {
  30570. /**
  30571. * Constructs a new node-based Matrix4 uniform.
  30572. *
  30573. * @param {NodeUniform} nodeUniform - The node uniform.
  30574. */
  30575. constructor( nodeUniform ) {
  30576. super( nodeUniform.name, nodeUniform.value );
  30577. /**
  30578. * The node uniform.
  30579. *
  30580. * @type {NodeUniform}
  30581. */
  30582. this.nodeUniform = nodeUniform;
  30583. }
  30584. /**
  30585. * Overwritten to return the value of the node uniform.
  30586. *
  30587. * @return {Matrix4} The value.
  30588. */
  30589. getValue() {
  30590. return this.nodeUniform.value;
  30591. }
  30592. /**
  30593. * Returns the node uniform data type.
  30594. *
  30595. * @return {string} The data type.
  30596. */
  30597. getType() {
  30598. return this.nodeUniform.type;
  30599. }
  30600. }
  30601. const rendererCache = new WeakMap();
  30602. const typeFromArray = new Map( [
  30603. [ Int8Array, 'int' ],
  30604. [ Int16Array, 'int' ],
  30605. [ Int32Array, 'int' ],
  30606. [ Uint8Array, 'uint' ],
  30607. [ Uint16Array, 'uint' ],
  30608. [ Uint32Array, 'uint' ],
  30609. [ Float32Array, 'float' ]
  30610. ] );
  30611. const toFloat = ( value ) => {
  30612. if ( /e/g.test( value ) ) {
  30613. return String( value ).replace( /\+/g, '' );
  30614. } else {
  30615. value = Number( value );
  30616. return value + ( value % 1 ? '' : '.0' );
  30617. }
  30618. };
  30619. /**
  30620. * Base class for builders which generate a shader program based
  30621. * on a 3D object and its node material definition.
  30622. */
  30623. class NodeBuilder {
  30624. /**
  30625. * Constructs a new node builder.
  30626. *
  30627. * @param {Object3D} object - The 3D object.
  30628. * @param {Renderer} renderer - The current renderer.
  30629. * @param {NodeParser} parser - A reference to a node parser.
  30630. */
  30631. constructor( object, renderer, parser ) {
  30632. /**
  30633. * The 3D object.
  30634. *
  30635. * @type {Object3D}
  30636. */
  30637. this.object = object;
  30638. /**
  30639. * The material of the 3D object.
  30640. *
  30641. * @type {?Material}
  30642. */
  30643. this.material = ( object && object.material ) || null;
  30644. /**
  30645. * The geometry of the 3D object.
  30646. *
  30647. * @type {?BufferGeometry}
  30648. */
  30649. this.geometry = ( object && object.geometry ) || null;
  30650. /**
  30651. * The current renderer.
  30652. *
  30653. * @type {Renderer}
  30654. */
  30655. this.renderer = renderer;
  30656. /**
  30657. * A reference to a node parser.
  30658. *
  30659. * @type {NodeParser}
  30660. */
  30661. this.parser = parser;
  30662. /**
  30663. * The scene the 3D object belongs to.
  30664. *
  30665. * @type {?Scene}
  30666. * @default null
  30667. */
  30668. this.scene = null;
  30669. /**
  30670. * The camera the 3D object is rendered with.
  30671. *
  30672. * @type {?Camera}
  30673. * @default null
  30674. */
  30675. this.camera = null;
  30676. /**
  30677. * A list of all nodes the builder is processing
  30678. * for this 3D object.
  30679. *
  30680. * @type {Array<Node>}
  30681. */
  30682. this.nodes = [];
  30683. /**
  30684. * A list of all sequential nodes.
  30685. *
  30686. * @type {Array<Node>}
  30687. */
  30688. this.sequentialNodes = [];
  30689. /**
  30690. * A list of all nodes which {@link Node#update} method should be executed.
  30691. *
  30692. * @type {Array<Node>}
  30693. */
  30694. this.updateNodes = [];
  30695. /**
  30696. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  30697. *
  30698. * @type {Array<Node>}
  30699. */
  30700. this.updateBeforeNodes = [];
  30701. /**
  30702. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  30703. *
  30704. * @type {Array<Node>}
  30705. */
  30706. this.updateAfterNodes = [];
  30707. /**
  30708. * A dictionary that assigns each node to a unique hash.
  30709. *
  30710. * @type {Object<number,Node>}
  30711. */
  30712. this.hashNodes = {};
  30713. /**
  30714. * A reference to a node material observer.
  30715. *
  30716. * @type {?NodeMaterialObserver}
  30717. * @default null
  30718. */
  30719. this.observer = null;
  30720. /**
  30721. * A reference to the current lights node.
  30722. *
  30723. * @type {?LightsNode}
  30724. * @default null
  30725. */
  30726. this.lightsNode = null;
  30727. /**
  30728. * A reference to the current environment node.
  30729. *
  30730. * @type {?Node}
  30731. * @default null
  30732. */
  30733. this.environmentNode = null;
  30734. /**
  30735. * A reference to the current fog node.
  30736. *
  30737. * @type {?FogNode}
  30738. * @default null
  30739. */
  30740. this.fogNode = null;
  30741. /**
  30742. * The current clipping context.
  30743. *
  30744. * @type {?ClippingContext}
  30745. */
  30746. this.clippingContext = null;
  30747. /**
  30748. * The generated vertex shader.
  30749. *
  30750. * @type {?string}
  30751. */
  30752. this.vertexShader = null;
  30753. /**
  30754. * The generated fragment shader.
  30755. *
  30756. * @type {?string}
  30757. */
  30758. this.fragmentShader = null;
  30759. /**
  30760. * The generated compute shader.
  30761. *
  30762. * @type {?string}
  30763. */
  30764. this.computeShader = null;
  30765. /**
  30766. * Nodes used in the primary flow of code generation.
  30767. *
  30768. * @type {Object<string,Array<Node>>}
  30769. */
  30770. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30771. /**
  30772. * Nodes code from `.flowNodes`.
  30773. *
  30774. * @type {Object<string,string>}
  30775. */
  30776. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30777. /**
  30778. * This dictionary holds the node uniforms of the builder.
  30779. * The uniforms are maintained in an array for each shader stage.
  30780. *
  30781. * @type {Object}
  30782. */
  30783. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30784. /**
  30785. * This dictionary holds the output structs of the builder.
  30786. * The structs are maintained in an array for each shader stage.
  30787. *
  30788. * @type {Object}
  30789. */
  30790. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30791. /**
  30792. * This dictionary holds the bindings for each shader stage.
  30793. *
  30794. * @type {Object}
  30795. */
  30796. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30797. /**
  30798. * This dictionary maintains the binding indices per bind group.
  30799. *
  30800. * @type {Object}
  30801. */
  30802. this.bindingsIndexes = {};
  30803. /**
  30804. * Reference to the array of bind groups.
  30805. *
  30806. * @type {?Array<BindGroup>}
  30807. */
  30808. this.bindGroups = null;
  30809. /**
  30810. * This array holds the node attributes of this builder
  30811. * created via {@link AttributeNode}.
  30812. *
  30813. * @type {Array<NodeAttribute>}
  30814. */
  30815. this.attributes = [];
  30816. /**
  30817. * This array holds the node attributes of this builder
  30818. * created via {@link BufferAttributeNode}.
  30819. *
  30820. * @type {Array<NodeAttribute>}
  30821. */
  30822. this.bufferAttributes = [];
  30823. /**
  30824. * This array holds the node varyings of this builder.
  30825. *
  30826. * @type {Array<NodeVarying>}
  30827. */
  30828. this.varyings = [];
  30829. /**
  30830. * This dictionary holds the (native) node codes of this builder.
  30831. * The codes are maintained in an array for each shader stage.
  30832. *
  30833. * @type {Object<string,Array<NodeCode>>}
  30834. */
  30835. this.codes = {};
  30836. /**
  30837. * This dictionary holds the node variables of this builder.
  30838. * The variables are maintained in an array for each shader stage.
  30839. * This dictionary is also used to count the number of variables
  30840. * according to their type (const, vars).
  30841. *
  30842. * @type {Object<string,Array<NodeVar>|number>}
  30843. */
  30844. this.vars = {};
  30845. /**
  30846. * Current code flow.
  30847. * All code generated in this stack will be stored in `.flow`.
  30848. *
  30849. * @type {{code: string}}
  30850. */
  30851. this.flow = { code: '' };
  30852. /**
  30853. * A chain of nodes.
  30854. * Used to check recursive calls in node-graph.
  30855. *
  30856. * @type {Array<Node>}
  30857. */
  30858. this.chaining = [];
  30859. /**
  30860. * The current stack.
  30861. * This reflects the current process in the code block hierarchy,
  30862. * it is useful to know if the current process is inside a conditional for example.
  30863. *
  30864. * @type {StackNode}
  30865. */
  30866. this.stack = stack();
  30867. /**
  30868. * List of stack nodes.
  30869. * The current stack hierarchy is stored in an array.
  30870. *
  30871. * @type {Array<StackNode>}
  30872. */
  30873. this.stacks = [];
  30874. /**
  30875. * A tab value. Used for shader string generation.
  30876. *
  30877. * @type {string}
  30878. * @default '\t'
  30879. */
  30880. this.tab = '\t';
  30881. /**
  30882. * Reference to the current function node.
  30883. *
  30884. * @type {?FunctionNode}
  30885. * @default null
  30886. */
  30887. this.currentFunctionNode = null;
  30888. /**
  30889. * The builder's context.
  30890. *
  30891. * @type {Object}
  30892. */
  30893. this.context = {
  30894. material: this.material
  30895. };
  30896. /**
  30897. * The builder's cache.
  30898. *
  30899. * @type {NodeCache}
  30900. */
  30901. this.cache = new NodeCache();
  30902. /**
  30903. * Since the {@link NodeBuilder#cache} might be temporarily
  30904. * overwritten by other caches, this member retains the reference
  30905. * to the builder's own cache.
  30906. *
  30907. * @type {NodeCache}
  30908. * @default this.cache
  30909. */
  30910. this.globalCache = this.cache;
  30911. this.flowsData = new WeakMap();
  30912. /**
  30913. * The current shader stage.
  30914. *
  30915. * @type {?('vertex'|'fragment'|'compute'|'any')}
  30916. */
  30917. this.shaderStage = null;
  30918. /**
  30919. * The current build stage.
  30920. *
  30921. * @type {?('setup'|'analyze'|'generate')}
  30922. */
  30923. this.buildStage = null;
  30924. /**
  30925. * Whether comparison in shader code are generated with methods or not.
  30926. *
  30927. * @type {boolean}
  30928. * @default false
  30929. */
  30930. this.useComparisonMethod = false;
  30931. }
  30932. /**
  30933. * Returns the bind groups of the current renderer.
  30934. *
  30935. * @return {ChainMap} The cache.
  30936. */
  30937. getBindGroupsCache() {
  30938. let bindGroupsCache = rendererCache.get( this.renderer );
  30939. if ( bindGroupsCache === undefined ) {
  30940. bindGroupsCache = new ChainMap();
  30941. rendererCache.set( this.renderer, bindGroupsCache );
  30942. }
  30943. return bindGroupsCache;
  30944. }
  30945. /**
  30946. * Factory method for creating an instance of {@link RenderTarget} with the given
  30947. * dimensions and options.
  30948. *
  30949. * @param {number} width - The width of the render target.
  30950. * @param {number} height - The height of the render target.
  30951. * @param {Object} options - The options of the render target.
  30952. * @return {RenderTarget} The render target.
  30953. */
  30954. createRenderTarget( width, height, options ) {
  30955. return new RenderTarget( width, height, options );
  30956. }
  30957. /**
  30958. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  30959. * dimensions and options.
  30960. *
  30961. * @param {number} size - The size of the cube render target.
  30962. * @param {Object} options - The options of the cube render target.
  30963. * @return {CubeRenderTarget} The cube render target.
  30964. */
  30965. createCubeRenderTarget( size, options ) {
  30966. return new CubeRenderTarget( size, options );
  30967. }
  30968. /**
  30969. * Whether the given node is included in the internal array of nodes or not.
  30970. *
  30971. * @param {Node} node - The node to test.
  30972. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  30973. */
  30974. includes( node ) {
  30975. return this.nodes.includes( node );
  30976. }
  30977. /**
  30978. * Returns the output struct name which is required by
  30979. * {@link OutputStructNode}.
  30980. *
  30981. * @abstract
  30982. * @return {string} The name of the output struct.
  30983. */
  30984. getOutputStructName() {}
  30985. /**
  30986. * Returns a bind group for the given group name and binding.
  30987. *
  30988. * @private
  30989. * @param {string} groupName - The group name.
  30990. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  30991. * @return {BindGroup} The bind group
  30992. */
  30993. _getBindGroup( groupName, bindings ) {
  30994. const bindGroupsCache = this.getBindGroupsCache();
  30995. //
  30996. const bindingsArray = [];
  30997. let sharedGroup = true;
  30998. for ( const binding of bindings ) {
  30999. bindingsArray.push( binding );
  31000. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  31001. }
  31002. //
  31003. let bindGroup;
  31004. if ( sharedGroup ) {
  31005. bindGroup = bindGroupsCache.get( bindingsArray );
  31006. if ( bindGroup === undefined ) {
  31007. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31008. bindGroupsCache.set( bindingsArray, bindGroup );
  31009. }
  31010. } else {
  31011. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31012. }
  31013. return bindGroup;
  31014. }
  31015. /**
  31016. * Returns an array of node uniform groups for the given group name and shader stage.
  31017. *
  31018. * @param {string} groupName - The group name.
  31019. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31020. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  31021. */
  31022. getBindGroupArray( groupName, shaderStage ) {
  31023. const bindings = this.bindings[ shaderStage ];
  31024. let bindGroup = bindings[ groupName ];
  31025. if ( bindGroup === undefined ) {
  31026. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31027. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31028. }
  31029. bindings[ groupName ] = bindGroup = [];
  31030. }
  31031. return bindGroup;
  31032. }
  31033. /**
  31034. * Returns a list bindings of all shader stages separated by groups.
  31035. *
  31036. * @return {Array<BindGroup>} The list of bindings.
  31037. */
  31038. getBindings() {
  31039. let bindingsGroups = this.bindGroups;
  31040. if ( bindingsGroups === null ) {
  31041. const groups = {};
  31042. const bindings = this.bindings;
  31043. for ( const shaderStage of shaderStages ) {
  31044. for ( const groupName in bindings[ shaderStage ] ) {
  31045. const uniforms = bindings[ shaderStage ][ groupName ];
  31046. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31047. groupUniforms.push( ...uniforms );
  31048. }
  31049. }
  31050. bindingsGroups = [];
  31051. for ( const groupName in groups ) {
  31052. const group = groups[ groupName ];
  31053. const bindingsGroup = this._getBindGroup( groupName, group );
  31054. bindingsGroups.push( bindingsGroup );
  31055. }
  31056. this.bindGroups = bindingsGroups;
  31057. }
  31058. return bindingsGroups;
  31059. }
  31060. /**
  31061. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  31062. */
  31063. sortBindingGroups() {
  31064. const bindingsGroups = this.getBindings();
  31065. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  31066. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  31067. const bindingGroup = bindingsGroups[ i ];
  31068. this.bindingsIndexes[ bindingGroup.name ].group = i;
  31069. bindingGroup.index = i;
  31070. }
  31071. }
  31072. /**
  31073. * The builder maintains each node in a hash-based dictionary.
  31074. * This method sets the given node (value) with the given hash (key) into this dictionary.
  31075. *
  31076. * @param {Node} node - The node to add.
  31077. * @param {number} hash - The hash of the node.
  31078. */
  31079. setHashNode( node, hash ) {
  31080. this.hashNodes[ hash ] = node;
  31081. }
  31082. /**
  31083. * Adds a node to this builder.
  31084. *
  31085. * @param {Node} node - The node to add.
  31086. */
  31087. addNode( node ) {
  31088. if ( this.nodes.includes( node ) === false ) {
  31089. this.nodes.push( node );
  31090. this.setHashNode( node, node.getHash( this ) );
  31091. }
  31092. }
  31093. /**
  31094. * It is used to add Nodes that will be used as FRAME and RENDER events,
  31095. * and need to follow a certain sequence in the calls to work correctly.
  31096. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  31097. *
  31098. * @param {Node} node - The node to add.
  31099. */
  31100. addSequentialNode( node ) {
  31101. if ( this.sequentialNodes.includes( node ) === false ) {
  31102. this.sequentialNodes.push( node );
  31103. }
  31104. }
  31105. /**
  31106. * Checks the update types of nodes
  31107. */
  31108. buildUpdateNodes() {
  31109. for ( const node of this.nodes ) {
  31110. const updateType = node.getUpdateType();
  31111. if ( updateType !== NodeUpdateType.NONE ) {
  31112. this.updateNodes.push( node.getSelf() );
  31113. }
  31114. }
  31115. for ( const node of this.sequentialNodes ) {
  31116. const updateBeforeType = node.getUpdateBeforeType();
  31117. const updateAfterType = node.getUpdateAfterType();
  31118. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  31119. this.updateBeforeNodes.push( node.getSelf() );
  31120. }
  31121. if ( updateAfterType !== NodeUpdateType.NONE ) {
  31122. this.updateAfterNodes.push( node.getSelf() );
  31123. }
  31124. }
  31125. }
  31126. /**
  31127. * A reference the current node which is the
  31128. * last node in the chain of nodes.
  31129. *
  31130. * @type {Node}
  31131. */
  31132. get currentNode() {
  31133. return this.chaining[ this.chaining.length - 1 ];
  31134. }
  31135. /**
  31136. * Whether the given texture is filtered or not.
  31137. *
  31138. * @param {Texture} texture - The texture to check.
  31139. * @return {boolean} Whether the given texture is filtered or not.
  31140. */
  31141. isFilteredTexture( texture ) {
  31142. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  31143. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  31144. }
  31145. /**
  31146. * Adds the given node to the internal node chain.
  31147. * This is used to check recursive calls in node-graph.
  31148. *
  31149. * @param {Node} node - The node to add.
  31150. */
  31151. addChain( node ) {
  31152. /*
  31153. if ( this.chaining.indexOf( node ) !== - 1 ) {
  31154. console.warn( 'Recursive node: ', node );
  31155. }
  31156. */
  31157. this.chaining.push( node );
  31158. }
  31159. /**
  31160. * Removes the given node from the internal node chain.
  31161. *
  31162. * @param {Node} node - The node to remove.
  31163. */
  31164. removeChain( node ) {
  31165. const lastChain = this.chaining.pop();
  31166. if ( lastChain !== node ) {
  31167. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  31168. }
  31169. }
  31170. /**
  31171. * Returns the native shader method name for a given generic name. E.g.
  31172. * the method name `textureDimensions` matches the WGSL name but must be
  31173. * resolved to `textureSize` in GLSL.
  31174. *
  31175. * @abstract
  31176. * @param {string} method - The method name to resolve.
  31177. * @return {string} The resolved method name.
  31178. */
  31179. getMethod( method ) {
  31180. return method;
  31181. }
  31182. /**
  31183. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  31184. *
  31185. * @param {number} hash - The hash of the node.
  31186. * @return {Node} The found node.
  31187. */
  31188. getNodeFromHash( hash ) {
  31189. return this.hashNodes[ hash ];
  31190. }
  31191. /**
  31192. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  31193. *
  31194. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  31195. * @param {Node} node - The node to add.
  31196. * @return {Node} The node.
  31197. */
  31198. addFlow( shaderStage, node ) {
  31199. this.flowNodes[ shaderStage ].push( node );
  31200. return node;
  31201. }
  31202. /**
  31203. * Sets builder's context.
  31204. *
  31205. * @param {Object} context - The context to set.
  31206. */
  31207. setContext( context ) {
  31208. this.context = context;
  31209. }
  31210. /**
  31211. * Returns the builder's current context.
  31212. *
  31213. * @return {Object} The builder's current context.
  31214. */
  31215. getContext() {
  31216. return this.context;
  31217. }
  31218. /**
  31219. * Gets a context used in shader construction that can be shared across different materials.
  31220. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  31221. *
  31222. * @return {Object} The builder's current context without material.
  31223. */
  31224. getSharedContext() {
  31225. ({ ...this.context });
  31226. return this.context;
  31227. }
  31228. /**
  31229. * Sets builder's cache.
  31230. *
  31231. * @param {NodeCache} cache - The cache to set.
  31232. */
  31233. setCache( cache ) {
  31234. this.cache = cache;
  31235. }
  31236. /**
  31237. * Returns the builder's current cache.
  31238. *
  31239. * @return {NodeCache} The builder's current cache.
  31240. */
  31241. getCache() {
  31242. return this.cache;
  31243. }
  31244. /**
  31245. * Returns a cache for the given node.
  31246. *
  31247. * @param {Node} node - The node.
  31248. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  31249. * @return {NodeCache} The cache.
  31250. */
  31251. getCacheFromNode( node, parent = true ) {
  31252. const data = this.getDataFromNode( node );
  31253. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31254. return data.cache;
  31255. }
  31256. /**
  31257. * Whether the requested feature is available or not.
  31258. *
  31259. * @abstract
  31260. * @param {string} name - The requested feature.
  31261. * @return {boolean} Whether the requested feature is supported or not.
  31262. */
  31263. isAvailable( /*name*/ ) {
  31264. return false;
  31265. }
  31266. /**
  31267. * Returns the vertexIndex input variable as a native shader string.
  31268. *
  31269. * @abstract
  31270. * @return {string} The instanceIndex shader string.
  31271. */
  31272. getVertexIndex() {
  31273. console.warn( 'Abstract function.' );
  31274. }
  31275. /**
  31276. * Returns the instanceIndex input variable as a native shader string.
  31277. *
  31278. * @abstract
  31279. * @return {string} The instanceIndex shader string.
  31280. */
  31281. getInstanceIndex() {
  31282. console.warn( 'Abstract function.' );
  31283. }
  31284. /**
  31285. * Returns the drawIndex input variable as a native shader string.
  31286. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  31287. *
  31288. * @abstract
  31289. * @return {?string} The drawIndex shader string.
  31290. */
  31291. getDrawIndex() {
  31292. console.warn( 'Abstract function.' );
  31293. }
  31294. /**
  31295. * Returns the frontFacing input variable as a native shader string.
  31296. *
  31297. * @abstract
  31298. * @return {string} The frontFacing shader string.
  31299. */
  31300. getFrontFacing() {
  31301. console.warn( 'Abstract function.' );
  31302. }
  31303. /**
  31304. * Returns the fragCoord input variable as a native shader string.
  31305. *
  31306. * @abstract
  31307. * @return {string} The fragCoord shader string.
  31308. */
  31309. getFragCoord() {
  31310. console.warn( 'Abstract function.' );
  31311. }
  31312. /**
  31313. * Whether to flip texture data along its vertical axis or not. WebGL needs
  31314. * this method evaluate to `true`, WebGPU to `false`.
  31315. *
  31316. * @abstract
  31317. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  31318. */
  31319. isFlipY() {
  31320. return false;
  31321. }
  31322. /**
  31323. * Calling this method increases the usage count for the given node by one.
  31324. *
  31325. * @param {Node} node - The node to increase the usage count for.
  31326. * @return {number} The updated usage count.
  31327. */
  31328. increaseUsage( node ) {
  31329. const nodeData = this.getDataFromNode( node );
  31330. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31331. return nodeData.usageCount;
  31332. }
  31333. /**
  31334. * Generates a texture sample shader string for the given texture data.
  31335. *
  31336. * @abstract
  31337. * @param {Texture} texture - The texture.
  31338. * @param {string} textureProperty - The texture property name.
  31339. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31340. * @return {string} The generated shader string.
  31341. */
  31342. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31343. console.warn( 'Abstract function.' );
  31344. }
  31345. /**
  31346. * Generates a texture LOD shader string for the given texture data.
  31347. *
  31348. * @abstract
  31349. * @param {Texture} texture - The texture.
  31350. * @param {string} textureProperty - The texture property name.
  31351. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31352. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  31353. * @param {string} levelSnippet - Snippet defining the mip level.
  31354. * @return {string} The generated shader string.
  31355. */
  31356. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  31357. console.warn( 'Abstract function.' );
  31358. }
  31359. /**
  31360. * Generates the array declaration string.
  31361. *
  31362. * @param {string} type - The type.
  31363. * @param {?number} [count] - The count.
  31364. * @return {string} The generated value as a shader string.
  31365. */
  31366. generateArrayDeclaration( type, count ) {
  31367. return this.getType( type ) + '[ ' + count + ' ]';
  31368. }
  31369. /**
  31370. * Generates the array shader string for the given type and value.
  31371. *
  31372. * @param {string} type - The type.
  31373. * @param {?number} [count] - The count.
  31374. * @param {?Array<Node>} [values=null] - The default values.
  31375. * @return {string} The generated value as a shader string.
  31376. */
  31377. generateArray( type, count, values = null ) {
  31378. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  31379. for ( let i = 0; i < count; i ++ ) {
  31380. const value = values ? values[ i ] : null;
  31381. if ( value !== null ) {
  31382. snippet += value.build( this, type );
  31383. } else {
  31384. snippet += this.generateConst( type );
  31385. }
  31386. if ( i < count - 1 ) snippet += ', ';
  31387. }
  31388. snippet += ' )';
  31389. return snippet;
  31390. }
  31391. /**
  31392. * Generates the struct shader string.
  31393. *
  31394. * @param {string} type - The type.
  31395. * @param {Array<Object>} [membersLayout] - The count.
  31396. * @param {?Array<Node>} [values=null] - The default values.
  31397. * @return {string} The generated value as a shader string.
  31398. */
  31399. generateStruct( type, membersLayout, values = null ) {
  31400. const snippets = [];
  31401. for ( const member of membersLayout ) {
  31402. const { name, type } = member;
  31403. if ( values && values[ name ] && values[ name ].isNode ) {
  31404. snippets.push( values[ name ].build( this, type ) );
  31405. } else {
  31406. snippets.push( this.generateConst( type ) );
  31407. }
  31408. }
  31409. return type + '( ' + snippets.join( ', ' ) + ' )';
  31410. }
  31411. /**
  31412. * Generates the shader string for the given type and value.
  31413. *
  31414. * @param {string} type - The type.
  31415. * @param {?any} [value=null] - The value.
  31416. * @return {string} The generated value as a shader string.
  31417. */
  31418. generateConst( type, value = null ) {
  31419. if ( value === null ) {
  31420. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31421. else if ( type === 'bool' ) value = false;
  31422. else if ( type === 'color' ) value = new Color();
  31423. else if ( type === 'vec2' ) value = new Vector2();
  31424. else if ( type === 'vec3' ) value = new Vector3();
  31425. else if ( type === 'vec4' ) value = new Vector4();
  31426. }
  31427. if ( type === 'float' ) return toFloat( value );
  31428. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31429. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31430. if ( type === 'bool' ) return value ? 'true' : 'false';
  31431. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31432. const typeLength = this.getTypeLength( type );
  31433. const componentType = this.getComponentType( type );
  31434. const generateConst = value => this.generateConst( componentType, value );
  31435. if ( typeLength === 2 ) {
  31436. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31437. } else if ( typeLength === 3 ) {
  31438. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31439. } else if ( typeLength === 4 && type !== 'mat2' ) {
  31440. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31441. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  31442. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31443. } else if ( typeLength > 4 ) {
  31444. return `${ this.getType( type ) }()`;
  31445. }
  31446. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31447. }
  31448. /**
  31449. * It might be necessary to convert certain data types to different ones
  31450. * so this method can be used to hide the conversion.
  31451. *
  31452. * @param {string} type - The type.
  31453. * @return {string} The updated type.
  31454. */
  31455. getType( type ) {
  31456. if ( type === 'color' ) return 'vec3';
  31457. return type;
  31458. }
  31459. /**
  31460. * Whether the given attribute name is defined in the geometry or not.
  31461. *
  31462. * @param {string} name - The attribute name.
  31463. * @return {boolean} Whether the given attribute name is defined in the geometry.
  31464. */
  31465. hasGeometryAttribute( name ) {
  31466. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31467. }
  31468. /**
  31469. * Returns a node attribute for the given name and type.
  31470. *
  31471. * @param {string} name - The attribute's name.
  31472. * @param {string} type - The attribute's type.
  31473. * @return {NodeAttribute} The node attribute.
  31474. */
  31475. getAttribute( name, type ) {
  31476. const attributes = this.attributes;
  31477. // find attribute
  31478. for ( const attribute of attributes ) {
  31479. if ( attribute.name === name ) {
  31480. return attribute;
  31481. }
  31482. }
  31483. // create a new if no exist
  31484. const attribute = new NodeAttribute( name, type );
  31485. attributes.push( attribute );
  31486. return attribute;
  31487. }
  31488. /**
  31489. * Returns for the given node and shader stage the property name for the shader.
  31490. *
  31491. * @param {Node} node - The node.
  31492. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31493. * @return {string} The property name.
  31494. */
  31495. getPropertyName( node/*, shaderStage*/ ) {
  31496. return node.name;
  31497. }
  31498. /**
  31499. * Whether the given type is a vector type or not.
  31500. *
  31501. * @param {string} type - The type to check.
  31502. * @return {boolean} Whether the given type is a vector type or not.
  31503. */
  31504. isVector( type ) {
  31505. return /vec\d/.test( type );
  31506. }
  31507. /**
  31508. * Whether the given type is a matrix type or not.
  31509. *
  31510. * @param {string} type - The type to check.
  31511. * @return {boolean} Whether the given type is a matrix type or not.
  31512. */
  31513. isMatrix( type ) {
  31514. return /mat\d/.test( type );
  31515. }
  31516. /**
  31517. * Whether the given type is a reference type or not.
  31518. *
  31519. * @param {string} type - The type to check.
  31520. * @return {boolean} Whether the given type is a reference type or not.
  31521. */
  31522. isReference( type ) {
  31523. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31524. }
  31525. /**
  31526. * Checks if the given texture requires a manual conversion to the working color space.
  31527. *
  31528. * @abstract
  31529. * @param {Texture} texture - The texture to check.
  31530. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  31531. */
  31532. needsToWorkingColorSpace( /*texture*/ ) {
  31533. return false;
  31534. }
  31535. /**
  31536. * Returns the component type of a given texture.
  31537. *
  31538. * @param {Texture} texture - The texture.
  31539. * @return {string} The component type.
  31540. */
  31541. getComponentTypeFromTexture( texture ) {
  31542. const type = texture.type;
  31543. if ( texture.isDataTexture ) {
  31544. if ( type === IntType ) return 'int';
  31545. if ( type === UnsignedIntType ) return 'uint';
  31546. }
  31547. return 'float';
  31548. }
  31549. /**
  31550. * Returns the element type for a given type.
  31551. *
  31552. * @param {string} type - The type.
  31553. * @return {string} The element type.
  31554. */
  31555. getElementType( type ) {
  31556. if ( type === 'mat2' ) return 'vec2';
  31557. if ( type === 'mat3' ) return 'vec3';
  31558. if ( type === 'mat4' ) return 'vec4';
  31559. return this.getComponentType( type );
  31560. }
  31561. /**
  31562. * Returns the component type for a given type.
  31563. *
  31564. * @param {string} type - The type.
  31565. * @return {string} The component type.
  31566. */
  31567. getComponentType( type ) {
  31568. type = this.getVectorType( type );
  31569. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31570. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31571. if ( componentType === null ) return null;
  31572. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31573. if ( componentType[ 1 ] === 'i' ) return 'int';
  31574. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31575. return 'float';
  31576. }
  31577. /**
  31578. * Returns the vector type for a given type.
  31579. *
  31580. * @param {string} type - The type.
  31581. * @return {string} The vector type.
  31582. */
  31583. getVectorType( type ) {
  31584. if ( type === 'color' ) return 'vec3';
  31585. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31586. return type;
  31587. }
  31588. /**
  31589. * Returns the data type for the given the length and component type.
  31590. *
  31591. * @param {number} length - The length.
  31592. * @param {string} [componentType='float'] - The component type.
  31593. * @return {string} The type.
  31594. */
  31595. getTypeFromLength( length, componentType = 'float' ) {
  31596. if ( length === 1 ) return componentType;
  31597. let baseType = getTypeFromLength( length );
  31598. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31599. // fix edge case for mat2x2 being same size as vec4
  31600. if ( /mat2/.test( componentType ) === true ) {
  31601. baseType = baseType.replace( 'vec', 'mat' );
  31602. }
  31603. return prefix + baseType;
  31604. }
  31605. /**
  31606. * Returns the type for a given typed array.
  31607. *
  31608. * @param {TypedArray} array - The typed array.
  31609. * @return {string} The type.
  31610. */
  31611. getTypeFromArray( array ) {
  31612. return typeFromArray.get( array.constructor );
  31613. }
  31614. /**
  31615. * Returns the type for a given buffer attribute.
  31616. *
  31617. * @param {BufferAttribute} attribute - The buffer attribute.
  31618. * @return {string} The type.
  31619. */
  31620. getTypeFromAttribute( attribute ) {
  31621. let dataAttribute = attribute;
  31622. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31623. const array = dataAttribute.array;
  31624. const itemSize = attribute.itemSize;
  31625. const normalized = attribute.normalized;
  31626. let arrayType;
  31627. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31628. arrayType = this.getTypeFromArray( array );
  31629. }
  31630. return this.getTypeFromLength( itemSize, arrayType );
  31631. }
  31632. /**
  31633. * Returns the length for the given data type.
  31634. *
  31635. * @param {string} type - The data type.
  31636. * @return {number} The length.
  31637. */
  31638. getTypeLength( type ) {
  31639. const vecType = this.getVectorType( type );
  31640. const vecNum = /vec([2-4])/.exec( vecType );
  31641. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31642. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31643. if ( /mat2/.test( type ) === true ) return 4;
  31644. if ( /mat3/.test( type ) === true ) return 9;
  31645. if ( /mat4/.test( type ) === true ) return 16;
  31646. return 0;
  31647. }
  31648. /**
  31649. * Returns the vector type for a given matrix type.
  31650. *
  31651. * @param {string} type - The matrix type.
  31652. * @return {string} The vector type.
  31653. */
  31654. getVectorFromMatrix( type ) {
  31655. return type.replace( 'mat', 'vec' );
  31656. }
  31657. /**
  31658. * For a given type this method changes the component type to the
  31659. * given value. E.g. `vec4` should be changed to the new component type
  31660. * `uint` which results in `uvec4`.
  31661. *
  31662. * @param {string} type - The type.
  31663. * @param {string} newComponentType - The new component type.
  31664. * @return {string} The new type.
  31665. */
  31666. changeComponentType( type, newComponentType ) {
  31667. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31668. }
  31669. /**
  31670. * Returns the integer type pendant for the given type.
  31671. *
  31672. * @param {string} type - The type.
  31673. * @return {string} The integer type.
  31674. */
  31675. getIntegerType( type ) {
  31676. const componentType = this.getComponentType( type );
  31677. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31678. return this.changeComponentType( type, 'int' );
  31679. }
  31680. /**
  31681. * Adds a stack node to the internal stack.
  31682. *
  31683. * @return {StackNode} The added stack node.
  31684. */
  31685. addStack() {
  31686. this.stack = stack( this.stack );
  31687. this.stacks.push( getCurrentStack() || this.stack );
  31688. setCurrentStack( this.stack );
  31689. return this.stack;
  31690. }
  31691. /**
  31692. * Removes the last stack node from the internal stack.
  31693. *
  31694. * @return {StackNode} The removed stack node.
  31695. */
  31696. removeStack() {
  31697. const lastStack = this.stack;
  31698. this.stack = lastStack.parent;
  31699. setCurrentStack( this.stacks.pop() );
  31700. return lastStack;
  31701. }
  31702. /**
  31703. * The builder maintains (cached) data for each node during the building process. This method
  31704. * can be used to get these data for a specific shader stage and cache.
  31705. *
  31706. * @param {Node} node - The node to get the data for.
  31707. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31708. * @param {?NodeCache} cache - An optional cache.
  31709. * @return {Object} The node data.
  31710. */
  31711. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31712. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31713. let nodeData = cache.getData( node );
  31714. if ( nodeData === undefined ) {
  31715. nodeData = {};
  31716. cache.setData( node, nodeData );
  31717. }
  31718. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31719. return nodeData[ shaderStage ];
  31720. }
  31721. /**
  31722. * Returns the properties for the given node and shader stage.
  31723. *
  31724. * @param {Node} node - The node to get the properties for.
  31725. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  31726. * @return {Object} The node properties.
  31727. */
  31728. getNodeProperties( node, shaderStage = 'any' ) {
  31729. const nodeData = this.getDataFromNode( node, shaderStage );
  31730. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31731. }
  31732. /**
  31733. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  31734. *
  31735. * @param {BufferAttributeNode} node - The buffer attribute node.
  31736. * @param {string} type - The node type.
  31737. * @return {NodeAttribute} The node attribute.
  31738. */
  31739. getBufferAttributeFromNode( node, type ) {
  31740. const nodeData = this.getDataFromNode( node );
  31741. let bufferAttribute = nodeData.bufferAttribute;
  31742. if ( bufferAttribute === undefined ) {
  31743. const index = this.uniforms.index ++;
  31744. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31745. this.bufferAttributes.push( bufferAttribute );
  31746. nodeData.bufferAttribute = bufferAttribute;
  31747. }
  31748. return bufferAttribute;
  31749. }
  31750. /**
  31751. * Returns an instance of {@link StructType} for the given output struct node.
  31752. *
  31753. * @param {OutputStructNode} node - The output struct node.
  31754. * @param {Array<Object>} membersLayout - The output struct types.
  31755. * @param {?string} [name=null] - The name of the struct.
  31756. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31757. * @return {StructType} The struct type attribute.
  31758. */
  31759. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  31760. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31761. let structType = nodeData.structType;
  31762. if ( structType === undefined ) {
  31763. const index = this.structs.index ++;
  31764. if ( name === null ) name = 'StructType' + index;
  31765. structType = new StructType( name, membersLayout );
  31766. this.structs[ shaderStage ].push( structType );
  31767. nodeData.structType = structType;
  31768. }
  31769. return structType;
  31770. }
  31771. /**
  31772. * Returns an instance of {@link StructType} for the given output struct node.
  31773. *
  31774. * @param {OutputStructNode} node - The output struct node.
  31775. * @param {Array<Object>} membersLayout - The output struct types.
  31776. * @return {StructType} The struct type attribute.
  31777. */
  31778. getOutputStructTypeFromNode( node, membersLayout ) {
  31779. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  31780. structType.output = true;
  31781. return structType;
  31782. }
  31783. /**
  31784. * Returns an instance of {@link NodeUniform} for the given uniform node.
  31785. *
  31786. * @param {UniformNode} node - The uniform node.
  31787. * @param {string} type - The uniform type.
  31788. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31789. * @param {?string} name - The name of the uniform.
  31790. * @return {NodeUniform} The node uniform.
  31791. */
  31792. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31793. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31794. let nodeUniform = nodeData.uniform;
  31795. if ( nodeUniform === undefined ) {
  31796. const index = this.uniforms.index ++;
  31797. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31798. this.uniforms[ shaderStage ].push( nodeUniform );
  31799. nodeData.uniform = nodeUniform;
  31800. }
  31801. return nodeUniform;
  31802. }
  31803. /**
  31804. * Returns the array length.
  31805. *
  31806. * @param {Node} node - The node.
  31807. * @return {?number} The array length.
  31808. */
  31809. getArrayCount( node ) {
  31810. let count = null;
  31811. if ( node.isArrayNode ) count = node.count;
  31812. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  31813. return count;
  31814. }
  31815. /**
  31816. * Returns an instance of {@link NodeVar} for the given variable node.
  31817. *
  31818. * @param {VarNode} node - The variable node.
  31819. * @param {?string} name - The variable's name.
  31820. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  31821. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31822. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  31823. *
  31824. * @return {NodeVar} The node variable.
  31825. */
  31826. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  31827. const nodeData = this.getDataFromNode( node, shaderStage );
  31828. let nodeVar = nodeData.variable;
  31829. if ( nodeVar === undefined ) {
  31830. const idNS = readOnly ? '_const' : '_var';
  31831. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31832. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  31833. if ( name === null ) {
  31834. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  31835. this.vars[ idNS ] ++;
  31836. }
  31837. //
  31838. const count = this.getArrayCount( node );
  31839. nodeVar = new NodeVar( name, type, readOnly, count );
  31840. if ( ! readOnly ) {
  31841. vars.push( nodeVar );
  31842. }
  31843. nodeData.variable = nodeVar;
  31844. }
  31845. return nodeVar;
  31846. }
  31847. /**
  31848. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  31849. *
  31850. * @param {Node} node - The varying node.
  31851. * @return {boolean} Returns true if deterministic.
  31852. */
  31853. isDeterministic( node ) {
  31854. if ( node.isMathNode ) {
  31855. return this.isDeterministic( node.aNode ) &&
  31856. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  31857. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  31858. } else if ( node.isOperatorNode ) {
  31859. return this.isDeterministic( node.aNode ) &&
  31860. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  31861. } else if ( node.isArrayNode ) {
  31862. if ( node.values !== null ) {
  31863. for ( const n of node.values ) {
  31864. if ( ! this.isDeterministic( n ) ) {
  31865. return false;
  31866. }
  31867. }
  31868. }
  31869. return true;
  31870. } else if ( node.isConstNode ) {
  31871. return true;
  31872. }
  31873. return false;
  31874. }
  31875. /**
  31876. * Returns an instance of {@link NodeVarying} for the given varying node.
  31877. *
  31878. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  31879. * @param {?string} name - The varying's name.
  31880. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  31881. * @return {NodeVar} The node varying.
  31882. */
  31883. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31884. const nodeData = this.getDataFromNode( node, 'any' );
  31885. let nodeVarying = nodeData.varying;
  31886. if ( nodeVarying === undefined ) {
  31887. const varyings = this.varyings;
  31888. const index = varyings.length;
  31889. if ( name === null ) name = 'nodeVarying' + index;
  31890. nodeVarying = new NodeVarying( name, type );
  31891. varyings.push( nodeVarying );
  31892. nodeData.varying = nodeVarying;
  31893. }
  31894. return nodeVarying;
  31895. }
  31896. /**
  31897. * Returns an instance of {@link NodeCode} for the given code node.
  31898. *
  31899. * @param {CodeNode} node - The code node.
  31900. * @param {string} type - The node type.
  31901. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31902. * @return {NodeCode} The node code.
  31903. */
  31904. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31905. const nodeData = this.getDataFromNode( node );
  31906. let nodeCode = nodeData.code;
  31907. if ( nodeCode === undefined ) {
  31908. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31909. const index = codes.length;
  31910. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31911. codes.push( nodeCode );
  31912. nodeData.code = nodeCode;
  31913. }
  31914. return nodeCode;
  31915. }
  31916. /**
  31917. * Adds a code flow based on the code-block hierarchy.
  31918. * This is used so that code-blocks like If,Else create their variables locally if the Node
  31919. * is only used inside one of these conditionals in the current shader stage.
  31920. *
  31921. * @param {Node} node - The node to add.
  31922. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  31923. */
  31924. addFlowCodeHierarchy( node, nodeBlock ) {
  31925. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31926. let needsFlowCode = true;
  31927. let nodeBlockHierarchy = nodeBlock;
  31928. while ( nodeBlockHierarchy ) {
  31929. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31930. needsFlowCode = false;
  31931. break;
  31932. }
  31933. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31934. }
  31935. if ( needsFlowCode ) {
  31936. for ( const flowCode of flowCodes ) {
  31937. this.addLineFlowCode( flowCode );
  31938. }
  31939. }
  31940. }
  31941. /**
  31942. * Add a inline-code to the current flow code-block.
  31943. *
  31944. * @param {Node} node - The node to add.
  31945. * @param {string} code - The code to add.
  31946. * @param {Node} nodeBlock - Current ConditionalNode
  31947. */
  31948. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31949. const nodeData = this.getDataFromNode( node );
  31950. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31951. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31952. flowCodes.push( code );
  31953. codeBlock.set( nodeBlock, true );
  31954. }
  31955. /**
  31956. * Add a inline-code to the current flow.
  31957. *
  31958. * @param {string} code - The code to add.
  31959. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  31960. * @return {NodeBuilder} A reference to this node builder.
  31961. */
  31962. addLineFlowCode( code, node = null ) {
  31963. if ( code === '' ) return this;
  31964. if ( node !== null && this.context.nodeBlock ) {
  31965. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31966. }
  31967. code = this.tab + code;
  31968. if ( ! /;\s*$/.test( code ) ) {
  31969. code = code + ';\n';
  31970. }
  31971. this.flow.code += code;
  31972. return this;
  31973. }
  31974. /**
  31975. * Adds a code to the current code flow.
  31976. *
  31977. * @param {string} code - Shader code.
  31978. * @return {NodeBuilder} A reference to this node builder.
  31979. */
  31980. addFlowCode( code ) {
  31981. this.flow.code += code;
  31982. return this;
  31983. }
  31984. /**
  31985. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  31986. * Typically used in codes with If,Else.
  31987. *
  31988. * @return {NodeBuilder} A reference to this node builder.
  31989. */
  31990. addFlowTab() {
  31991. this.tab += '\t';
  31992. return this;
  31993. }
  31994. /**
  31995. * Removes a tab.
  31996. *
  31997. * @return {NodeBuilder} A reference to this node builder.
  31998. */
  31999. removeFlowTab() {
  32000. this.tab = this.tab.slice( 0, - 1 );
  32001. return this;
  32002. }
  32003. /**
  32004. * Gets the current flow data based on a Node.
  32005. *
  32006. * @param {Node} node - Node that the flow was started.
  32007. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32008. * @return {Object} The flow data.
  32009. */
  32010. getFlowData( node/*, shaderStage*/ ) {
  32011. return this.flowsData.get( node );
  32012. }
  32013. /**
  32014. * Executes the node flow based on a root node to generate the final shader code.
  32015. *
  32016. * @param {Node} node - The node to execute.
  32017. * @return {Object} The code flow.
  32018. */
  32019. flowNode( node ) {
  32020. const output = node.getNodeType( this );
  32021. const flowData = this.flowChildNode( node, output );
  32022. this.flowsData.set( node, flowData );
  32023. return flowData;
  32024. }
  32025. /**
  32026. * Includes a node in the current function node.
  32027. *
  32028. * @param {Node} node - The node to include.
  32029. * @returns {void}
  32030. */
  32031. addInclude( node ) {
  32032. if ( this.currentFunctionNode !== null ) {
  32033. this.currentFunctionNode.includes.push( node );
  32034. }
  32035. }
  32036. /**
  32037. * Returns the native shader operator name for a given generic name.
  32038. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32039. *
  32040. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  32041. * @return {FunctionNode} The build function node.
  32042. */
  32043. buildFunctionNode( shaderNode ) {
  32044. const fn = new FunctionNode();
  32045. const previous = this.currentFunctionNode;
  32046. this.currentFunctionNode = fn;
  32047. fn.code = this.buildFunctionCode( shaderNode );
  32048. this.currentFunctionNode = previous;
  32049. return fn;
  32050. }
  32051. /**
  32052. * Generates a code flow based on a TSL function: Fn().
  32053. *
  32054. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  32055. * @return {Object}
  32056. */
  32057. flowShaderNode( shaderNode ) {
  32058. const layout = shaderNode.layout;
  32059. const inputs = {
  32060. [ Symbol.iterator ]() {
  32061. let index = 0;
  32062. const values = Object.values( this );
  32063. return {
  32064. next: () => ( {
  32065. value: values[ index ],
  32066. done: index ++ >= values.length
  32067. } )
  32068. };
  32069. }
  32070. };
  32071. for ( const input of layout.inputs ) {
  32072. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  32073. }
  32074. //
  32075. shaderNode.layout = null;
  32076. const callNode = shaderNode.call( inputs );
  32077. const flowData = this.flowStagesNode( callNode, layout.type );
  32078. shaderNode.layout = layout;
  32079. return flowData;
  32080. }
  32081. /**
  32082. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  32083. *
  32084. * @param {Node} node - The node to execute.
  32085. * @param {?string} output - Expected output type. For example 'vec3'.
  32086. * @return {Object}
  32087. */
  32088. flowStagesNode( node, output = null ) {
  32089. const previousFlow = this.flow;
  32090. const previousVars = this.vars;
  32091. const previousCache = this.cache;
  32092. const previousBuildStage = this.buildStage;
  32093. const previousStack = this.stack;
  32094. const flow = {
  32095. code: ''
  32096. };
  32097. this.flow = flow;
  32098. this.vars = {};
  32099. this.cache = new NodeCache();
  32100. this.stack = stack();
  32101. for ( const buildStage of defaultBuildStages ) {
  32102. this.setBuildStage( buildStage );
  32103. flow.result = node.build( this, output );
  32104. }
  32105. flow.vars = this.getVars( this.shaderStage );
  32106. this.flow = previousFlow;
  32107. this.vars = previousVars;
  32108. this.cache = previousCache;
  32109. this.stack = previousStack;
  32110. this.setBuildStage( previousBuildStage );
  32111. return flow;
  32112. }
  32113. /**
  32114. * Returns the native shader operator name for a given generic name.
  32115. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32116. *
  32117. * @abstract
  32118. * @param {string} op - The operator name to resolve.
  32119. * @return {?string} The resolved operator name.
  32120. */
  32121. getFunctionOperator( /* op */ ) {
  32122. return null;
  32123. }
  32124. /**
  32125. * Builds the given shader node.
  32126. *
  32127. * @abstract
  32128. * @param {ShaderNodeInternal} shaderNode - The shader node.
  32129. * @return {string} The function code.
  32130. */
  32131. buildFunctionCode( /* shaderNode */ ) {
  32132. console.warn( 'Abstract function.' );
  32133. }
  32134. /**
  32135. * Generates a code flow based on a child Node.
  32136. *
  32137. * @param {Node} node - The node to execute.
  32138. * @param {?string} output - Expected output type. For example 'vec3'.
  32139. * @return {Object} The code flow.
  32140. */
  32141. flowChildNode( node, output = null ) {
  32142. const previousFlow = this.flow;
  32143. const flow = {
  32144. code: ''
  32145. };
  32146. this.flow = flow;
  32147. flow.result = node.build( this, output );
  32148. this.flow = previousFlow;
  32149. return flow;
  32150. }
  32151. /**
  32152. * Executes a flow of code in a different stage.
  32153. *
  32154. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  32155. * return the value in fragment-stage even if it is being executed in an input fragment.
  32156. *
  32157. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32158. * @param {Node} node - The node to execute.
  32159. * @param {?string} output - Expected output type. For example 'vec3'.
  32160. * @param {?string} propertyName - The property name to assign the result.
  32161. * @return {Object}
  32162. */
  32163. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  32164. const previousShaderStage = this.shaderStage;
  32165. this.setShaderStage( shaderStage );
  32166. const flowData = this.flowChildNode( node, output );
  32167. if ( propertyName !== null ) {
  32168. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  32169. }
  32170. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  32171. this.setShaderStage( previousShaderStage );
  32172. return flowData;
  32173. }
  32174. /**
  32175. * Returns an array holding all node attributes of this node builder.
  32176. *
  32177. * @return {Array<NodeAttribute>} The node attributes of this builder.
  32178. */
  32179. getAttributesArray() {
  32180. return this.attributes.concat( this.bufferAttributes );
  32181. }
  32182. /**
  32183. * Returns the attribute definitions as a shader string for the given shader stage.
  32184. *
  32185. * @abstract
  32186. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32187. * @return {string} The attribute code section.
  32188. */
  32189. getAttributes( /*shaderStage*/ ) {
  32190. console.warn( 'Abstract function.' );
  32191. }
  32192. /**
  32193. * Returns the varying definitions as a shader string for the given shader stage.
  32194. *
  32195. * @abstract
  32196. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32197. * @return {string} The varying code section.
  32198. */
  32199. getVaryings( /*shaderStage*/ ) {
  32200. console.warn( 'Abstract function.' );
  32201. }
  32202. /**
  32203. * Returns a single variable definition as a shader string for the given variable type and name.
  32204. *
  32205. * @param {string} type - The variable's type.
  32206. * @param {string} name - The variable's name.
  32207. * @param {?number} [count=null] - The array length.
  32208. * @return {string} The shader string.
  32209. */
  32210. getVar( type, name, count = null ) {
  32211. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  32212. }
  32213. /**
  32214. * Returns the variable definitions as a shader string for the given shader stage.
  32215. *
  32216. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32217. * @return {string} The variable code section.
  32218. */
  32219. getVars( shaderStage ) {
  32220. let snippet = '';
  32221. const vars = this.vars[ shaderStage ];
  32222. if ( vars !== undefined ) {
  32223. for ( const variable of vars ) {
  32224. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  32225. }
  32226. }
  32227. return snippet;
  32228. }
  32229. /**
  32230. * Returns the uniform definitions as a shader string for the given shader stage.
  32231. *
  32232. * @abstract
  32233. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32234. * @return {string} The uniform code section.
  32235. */
  32236. getUniforms( /*shaderStage*/ ) {
  32237. console.warn( 'Abstract function.' );
  32238. }
  32239. /**
  32240. * Returns the native code definitions as a shader string for the given shader stage.
  32241. *
  32242. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32243. * @return {string} The native code section.
  32244. */
  32245. getCodes( shaderStage ) {
  32246. const codes = this.codes[ shaderStage ];
  32247. let code = '';
  32248. if ( codes !== undefined ) {
  32249. for ( const nodeCode of codes ) {
  32250. code += nodeCode.code + '\n';
  32251. }
  32252. }
  32253. return code;
  32254. }
  32255. /**
  32256. * Returns the hash of this node builder.
  32257. *
  32258. * @return {string} The hash.
  32259. */
  32260. getHash() {
  32261. return this.vertexShader + this.fragmentShader + this.computeShader;
  32262. }
  32263. /**
  32264. * Sets the current shader stage.
  32265. *
  32266. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  32267. */
  32268. setShaderStage( shaderStage ) {
  32269. this.shaderStage = shaderStage;
  32270. }
  32271. /**
  32272. * Returns the current shader stage.
  32273. *
  32274. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  32275. */
  32276. getShaderStage() {
  32277. return this.shaderStage;
  32278. }
  32279. /**
  32280. * Sets the current build stage.
  32281. *
  32282. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  32283. */
  32284. setBuildStage( buildStage ) {
  32285. this.buildStage = buildStage;
  32286. }
  32287. /**
  32288. * Returns the current build stage.
  32289. *
  32290. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  32291. */
  32292. getBuildStage() {
  32293. return this.buildStage;
  32294. }
  32295. /**
  32296. * Controls the code build of the shader stages.
  32297. *
  32298. * @abstract
  32299. */
  32300. buildCode() {
  32301. console.warn( 'Abstract function.' );
  32302. }
  32303. /**
  32304. * Central build method which controls the build for the given object.
  32305. *
  32306. * @return {NodeBuilder} A reference to this node builder.
  32307. */
  32308. build() {
  32309. const { object, material, renderer } = this;
  32310. if ( material !== null ) {
  32311. let nodeMaterial = renderer.library.fromMaterial( material );
  32312. if ( nodeMaterial === null ) {
  32313. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  32314. nodeMaterial = new NodeMaterial();
  32315. }
  32316. nodeMaterial.build( this );
  32317. } else {
  32318. this.addFlow( 'compute', object );
  32319. }
  32320. // setup() -> stage 1: create possible new nodes and returns an output reference node
  32321. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  32322. // generate() -> stage 3: generate shader
  32323. for ( const buildStage of defaultBuildStages ) {
  32324. this.setBuildStage( buildStage );
  32325. if ( this.context.vertex && this.context.vertex.isNode ) {
  32326. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  32327. }
  32328. for ( const shaderStage of shaderStages ) {
  32329. this.setShaderStage( shaderStage );
  32330. const flowNodes = this.flowNodes[ shaderStage ];
  32331. for ( const node of flowNodes ) {
  32332. if ( buildStage === 'generate' ) {
  32333. this.flowNode( node );
  32334. } else {
  32335. node.build( this );
  32336. }
  32337. }
  32338. }
  32339. }
  32340. this.setBuildStage( null );
  32341. this.setShaderStage( null );
  32342. // stage 4: build code for a specific output
  32343. this.buildCode();
  32344. this.buildUpdateNodes();
  32345. return this;
  32346. }
  32347. /**
  32348. * Returns a uniform representation which is later used for UBO generation and rendering.
  32349. *
  32350. * @param {NodeUniform} uniformNode - The uniform node.
  32351. * @param {string} type - The requested type.
  32352. * @return {Uniform} The uniform.
  32353. */
  32354. getNodeUniform( uniformNode, type ) {
  32355. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  32356. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  32357. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  32358. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  32359. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  32360. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  32361. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  32362. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  32363. throw new Error( `Uniform "${type}" not declared.` );
  32364. }
  32365. /**
  32366. * Formats the given shader snippet from a given type into another one. E.g.
  32367. * this method might be used to convert a simple float string `"1.0"` into a
  32368. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  32369. *
  32370. * @param {string} snippet - The shader snippet.
  32371. * @param {string} fromType - The source type.
  32372. * @param {string} toType - The target type.
  32373. * @return {string} The updated shader string.
  32374. */
  32375. format( snippet, fromType, toType ) {
  32376. fromType = this.getVectorType( fromType );
  32377. toType = this.getVectorType( toType );
  32378. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  32379. return snippet;
  32380. }
  32381. const fromTypeLength = this.getTypeLength( fromType );
  32382. const toTypeLength = this.getTypeLength( toType );
  32383. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  32384. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  32385. }
  32386. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  32387. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  32388. }
  32389. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  32390. // @TODO: ignore for now
  32391. return snippet;
  32392. }
  32393. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  32394. // @TODO: ignore for now
  32395. return snippet;
  32396. }
  32397. if ( fromTypeLength === toTypeLength ) {
  32398. return `${ this.getType( toType ) }( ${ snippet } )`;
  32399. }
  32400. if ( fromTypeLength > toTypeLength ) {
  32401. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  32402. }
  32403. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  32404. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  32405. }
  32406. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  32407. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  32408. }
  32409. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  32410. // convert a number value to vector type, e.g:
  32411. // vec3( 1u ) -> vec3( float( 1u ) )
  32412. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  32413. }
  32414. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  32415. }
  32416. /**
  32417. * Returns a signature with the engine's current revision.
  32418. *
  32419. * @return {string} The signature.
  32420. */
  32421. getSignature() {
  32422. return `// Three.js r${ REVISION } - Node System\n`;
  32423. }
  32424. // Deprecated
  32425. /**
  32426. * @function
  32427. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  32428. *
  32429. * @param {string} [type='NodeMaterial'] - The node material type.
  32430. * @throws {Error}
  32431. */
  32432. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  32433. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  32434. }
  32435. }
  32436. /**
  32437. * Management class for updating nodes. The module tracks metrics like
  32438. * the elapsed time, delta time, the render and frame ID to correctly
  32439. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  32440. * and {@link Node#updateAfter} depending on the node's configuration.
  32441. */
  32442. class NodeFrame {
  32443. /**
  32444. * Constructs a new node fame.
  32445. */
  32446. constructor() {
  32447. /**
  32448. * The elapsed time in seconds.
  32449. *
  32450. * @type {number}
  32451. * @default 0
  32452. */
  32453. this.time = 0;
  32454. /**
  32455. * The delta time in seconds.
  32456. *
  32457. * @type {number}
  32458. * @default 0
  32459. */
  32460. this.deltaTime = 0;
  32461. /**
  32462. * The frame ID.
  32463. *
  32464. * @type {number}
  32465. * @default 0
  32466. */
  32467. this.frameId = 0;
  32468. /**
  32469. * The render ID.
  32470. *
  32471. * @type {number}
  32472. * @default 0
  32473. */
  32474. this.renderId = 0;
  32475. /**
  32476. * Used to control the {@link Node#update} call.
  32477. *
  32478. * @type {WeakMap<Node, Object>}
  32479. */
  32480. this.updateMap = new WeakMap();
  32481. /**
  32482. * Used to control the {@link Node#updateBefore} call.
  32483. *
  32484. * @type {WeakMap<Node, Object>}
  32485. */
  32486. this.updateBeforeMap = new WeakMap();
  32487. /**
  32488. * Used to control the {@link Node#updateAfter} call.
  32489. *
  32490. * @type {WeakMap<Node, Object>}
  32491. */
  32492. this.updateAfterMap = new WeakMap();
  32493. /**
  32494. * A reference to the current renderer.
  32495. *
  32496. * @type {?Renderer}
  32497. * @default null
  32498. */
  32499. this.renderer = null;
  32500. /**
  32501. * A reference to the current material.
  32502. *
  32503. * @type {?Material}
  32504. * @default null
  32505. */
  32506. this.material = null;
  32507. /**
  32508. * A reference to the current camera.
  32509. *
  32510. * @type {?Camera}
  32511. * @default null
  32512. */
  32513. this.camera = null;
  32514. /**
  32515. * A reference to the current 3D object.
  32516. *
  32517. * @type {?Object3D}
  32518. * @default null
  32519. */
  32520. this.object = null;
  32521. /**
  32522. * A reference to the current scene.
  32523. *
  32524. * @type {?Scene}
  32525. * @default null
  32526. */
  32527. this.scene = null;
  32528. }
  32529. /**
  32530. * Returns a dictionary for a given node and update map which
  32531. * is used to correctly call node update methods per frame or render.
  32532. *
  32533. * @private
  32534. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  32535. * @param {Node} nodeRef - The reference to the current node.
  32536. * @return {Object<string,WeakMap>} The dictionary.
  32537. */
  32538. _getMaps( referenceMap, nodeRef ) {
  32539. let maps = referenceMap.get( nodeRef );
  32540. if ( maps === undefined ) {
  32541. maps = {
  32542. renderMap: new WeakMap(),
  32543. frameMap: new WeakMap()
  32544. };
  32545. referenceMap.set( nodeRef, maps );
  32546. }
  32547. return maps;
  32548. }
  32549. /**
  32550. * This method executes the {@link Node#updateBefore} for the given node.
  32551. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  32552. * is only executed once per frame, render or object depending on the update
  32553. * type.
  32554. *
  32555. * @param {Node} node - The node that should be updated.
  32556. */
  32557. updateBeforeNode( node ) {
  32558. const updateType = node.getUpdateBeforeType();
  32559. const reference = node.updateReference( this );
  32560. if ( updateType === NodeUpdateType.FRAME ) {
  32561. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  32562. if ( frameMap.get( reference ) !== this.frameId ) {
  32563. if ( node.updateBefore( this ) !== false ) {
  32564. frameMap.set( reference, this.frameId );
  32565. }
  32566. }
  32567. } else if ( updateType === NodeUpdateType.RENDER ) {
  32568. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  32569. if ( renderMap.get( reference ) !== this.renderId ) {
  32570. if ( node.updateBefore( this ) !== false ) {
  32571. renderMap.set( reference, this.renderId );
  32572. }
  32573. }
  32574. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32575. node.updateBefore( this );
  32576. }
  32577. }
  32578. /**
  32579. * This method executes the {@link Node#updateAfter} for the given node.
  32580. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  32581. * is only executed once per frame, render or object depending on the update
  32582. * type.
  32583. *
  32584. * @param {Node} node - The node that should be updated.
  32585. */
  32586. updateAfterNode( node ) {
  32587. const updateType = node.getUpdateAfterType();
  32588. const reference = node.updateReference( this );
  32589. if ( updateType === NodeUpdateType.FRAME ) {
  32590. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  32591. if ( frameMap.get( reference ) !== this.frameId ) {
  32592. if ( node.updateAfter( this ) !== false ) {
  32593. frameMap.set( reference, this.frameId );
  32594. }
  32595. }
  32596. } else if ( updateType === NodeUpdateType.RENDER ) {
  32597. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  32598. if ( renderMap.get( reference ) !== this.renderId ) {
  32599. if ( node.updateAfter( this ) !== false ) {
  32600. renderMap.set( reference, this.renderId );
  32601. }
  32602. }
  32603. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32604. node.updateAfter( this );
  32605. }
  32606. }
  32607. /**
  32608. * This method executes the {@link Node#update} for the given node.
  32609. * It makes sure {@link Node#updateType} is honored meaning the update
  32610. * is only executed once per frame, render or object depending on the update
  32611. * type.
  32612. *
  32613. * @param {Node} node - The node that should be updated.
  32614. */
  32615. updateNode( node ) {
  32616. const updateType = node.getUpdateType();
  32617. const reference = node.updateReference( this );
  32618. if ( updateType === NodeUpdateType.FRAME ) {
  32619. const { frameMap } = this._getMaps( this.updateMap, reference );
  32620. if ( frameMap.get( reference ) !== this.frameId ) {
  32621. if ( node.update( this ) !== false ) {
  32622. frameMap.set( reference, this.frameId );
  32623. }
  32624. }
  32625. } else if ( updateType === NodeUpdateType.RENDER ) {
  32626. const { renderMap } = this._getMaps( this.updateMap, reference );
  32627. if ( renderMap.get( reference ) !== this.renderId ) {
  32628. if ( node.update( this ) !== false ) {
  32629. renderMap.set( reference, this.renderId );
  32630. }
  32631. }
  32632. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32633. node.update( this );
  32634. }
  32635. }
  32636. /**
  32637. * Updates the internal state of the node frame. This method is
  32638. * called by the renderer in its internal animation loop.
  32639. */
  32640. update() {
  32641. this.frameId ++;
  32642. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  32643. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  32644. this.lastTime = performance.now();
  32645. this.time += this.deltaTime;
  32646. }
  32647. }
  32648. /**
  32649. * Describes the input of a {@link NodeFunction}.
  32650. */
  32651. class NodeFunctionInput {
  32652. /**
  32653. * Constructs a new node function input.
  32654. *
  32655. * @param {string} type - The input type.
  32656. * @param {string} name - The input name.
  32657. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  32658. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  32659. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  32660. */
  32661. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  32662. /**
  32663. * The input type.
  32664. *
  32665. * @type {string}
  32666. */
  32667. this.type = type;
  32668. /**
  32669. * The input name.
  32670. *
  32671. * @type {string}
  32672. */
  32673. this.name = name;
  32674. /**
  32675. * If the input is an Array, count will be the length.
  32676. *
  32677. * @type {?number}
  32678. * @default null
  32679. */
  32680. this.count = count;
  32681. /**
  32682. *The parameter qualifier (only relevant for GLSL).
  32683. *
  32684. * @type {('in'|'out'|'inout')}
  32685. * @default ''
  32686. */
  32687. this.qualifier = qualifier;
  32688. /**
  32689. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  32690. *
  32691. * @type {boolean}
  32692. * @default false
  32693. */
  32694. this.isConst = isConst;
  32695. }
  32696. }
  32697. NodeFunctionInput.isNodeFunctionInput = true;
  32698. /**
  32699. * Module for representing directional lights as nodes.
  32700. *
  32701. * @augments AnalyticLightNode
  32702. */
  32703. class DirectionalLightNode extends AnalyticLightNode {
  32704. static get type() {
  32705. return 'DirectionalLightNode';
  32706. }
  32707. /**
  32708. * Constructs a new directional light node.
  32709. *
  32710. * @param {?DirectionalLight} [light=null] - The directional light source.
  32711. */
  32712. constructor( light = null ) {
  32713. super( light );
  32714. }
  32715. setupDirect() {
  32716. const lightColor = this.colorNode;
  32717. const lightDirection = lightTargetDirection( this.light );
  32718. return { lightDirection, lightColor };
  32719. }
  32720. }
  32721. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32722. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32723. let _ltcLib = null;
  32724. /**
  32725. * Module for representing rect area lights as nodes.
  32726. *
  32727. * @augments AnalyticLightNode
  32728. */
  32729. class RectAreaLightNode extends AnalyticLightNode {
  32730. static get type() {
  32731. return 'RectAreaLightNode';
  32732. }
  32733. /**
  32734. * Constructs a new rect area light node.
  32735. *
  32736. * @param {?RectAreaLight} [light=null] - The rect area light source.
  32737. */
  32738. constructor( light = null ) {
  32739. super( light );
  32740. /**
  32741. * Uniform node representing the half height of the are light.
  32742. *
  32743. * @type {UniformNode<vec3>}
  32744. */
  32745. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  32746. /**
  32747. * Uniform node representing the half width of the are light.
  32748. *
  32749. * @type {UniformNode<vec3>}
  32750. */
  32751. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  32752. /**
  32753. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  32754. * relies on `viewMatrix` which might vary per render call.
  32755. *
  32756. * @type {string}
  32757. * @default 'render'
  32758. */
  32759. this.updateType = NodeUpdateType.RENDER;
  32760. }
  32761. /**
  32762. * Overwritten to updated rect area light specific uniforms.
  32763. *
  32764. * @param {NodeFrame} frame - A reference to the current node frame.
  32765. */
  32766. update( frame ) {
  32767. super.update( frame );
  32768. const { light } = this;
  32769. const viewMatrix = frame.camera.matrixWorldInverse;
  32770. _matrix42.identity();
  32771. _matrix41.copy( light.matrixWorld );
  32772. _matrix41.premultiply( viewMatrix );
  32773. _matrix42.extractRotation( _matrix41 );
  32774. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32775. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32776. this.halfWidth.value.applyMatrix4( _matrix42 );
  32777. this.halfHeight.value.applyMatrix4( _matrix42 );
  32778. }
  32779. setupDirectRectArea( builder ) {
  32780. let ltc_1, ltc_2;
  32781. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32782. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  32783. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  32784. } else {
  32785. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  32786. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  32787. }
  32788. const { colorNode, light } = this;
  32789. const lightPosition = lightViewPosition( light );
  32790. return {
  32791. lightColor: colorNode,
  32792. lightPosition,
  32793. halfWidth: this.halfWidth,
  32794. halfHeight: this.halfHeight,
  32795. ltc_1,
  32796. ltc_2
  32797. };
  32798. }
  32799. /**
  32800. * Used to configure the internal BRDF approximation texture data.
  32801. *
  32802. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  32803. */
  32804. static setLTC( ltc ) {
  32805. _ltcLib = ltc;
  32806. }
  32807. }
  32808. /**
  32809. * Module for representing spot lights as nodes.
  32810. *
  32811. * @augments AnalyticLightNode
  32812. */
  32813. class SpotLightNode extends AnalyticLightNode {
  32814. static get type() {
  32815. return 'SpotLightNode';
  32816. }
  32817. /**
  32818. * Constructs a new spot light node.
  32819. *
  32820. * @param {?SpotLight} [light=null] - The spot light source.
  32821. */
  32822. constructor( light = null ) {
  32823. super( light );
  32824. /**
  32825. * Uniform node representing the cone cosine.
  32826. *
  32827. * @type {UniformNode<float>}
  32828. */
  32829. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  32830. /**
  32831. * Uniform node representing the penumbra cosine.
  32832. *
  32833. * @type {UniformNode<float>}
  32834. */
  32835. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  32836. /**
  32837. * Uniform node representing the cutoff distance.
  32838. *
  32839. * @type {UniformNode<float>}
  32840. */
  32841. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32842. /**
  32843. * Uniform node representing the decay exponent.
  32844. *
  32845. * @type {UniformNode<float>}
  32846. */
  32847. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  32848. }
  32849. /**
  32850. * Overwritten to updated spot light specific uniforms.
  32851. *
  32852. * @param {NodeFrame} frame - A reference to the current node frame.
  32853. */
  32854. update( frame ) {
  32855. super.update( frame );
  32856. const { light } = this;
  32857. this.coneCosNode.value = Math.cos( light.angle );
  32858. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32859. this.cutoffDistanceNode.value = light.distance;
  32860. this.decayExponentNode.value = light.decay;
  32861. }
  32862. /**
  32863. * Computes the spot attenuation for the given angle.
  32864. *
  32865. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32866. * @return {Node<float>} The spot attenuation.
  32867. */
  32868. getSpotAttenuation( angleCosine ) {
  32869. const { coneCosNode, penumbraCosNode } = this;
  32870. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32871. }
  32872. setupDirect( builder ) {
  32873. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32874. const lightVector = this.getLightVector( builder );
  32875. const lightDirection = lightVector.normalize();
  32876. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32877. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32878. const lightDistance = lightVector.length();
  32879. const lightAttenuation = getDistanceAttenuation( {
  32880. lightDistance,
  32881. cutoffDistance: cutoffDistanceNode,
  32882. decayExponent: decayExponentNode
  32883. } );
  32884. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32885. if ( light.map ) {
  32886. const spotLightCoord = lightProjectionUV( light, builder.context.positionWorld );
  32887. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  32888. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  32889. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  32890. }
  32891. return { lightColor, lightDirection };
  32892. }
  32893. }
  32894. /**
  32895. * An IES version of the default spot light node.
  32896. *
  32897. * @augments SpotLightNode
  32898. */
  32899. class IESSpotLightNode extends SpotLightNode {
  32900. static get type() {
  32901. return 'IESSpotLightNode';
  32902. }
  32903. /**
  32904. * Overwrites the default implementation to compute an IES conform spot attenuation.
  32905. *
  32906. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32907. * @return {Node<float>} The spot attenuation.
  32908. */
  32909. getSpotAttenuation( angleCosine ) {
  32910. const iesMap = this.light.iesMap;
  32911. let spotAttenuation = null;
  32912. if ( iesMap && iesMap.isTexture === true ) {
  32913. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32914. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32915. } else {
  32916. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32917. }
  32918. return spotAttenuation;
  32919. }
  32920. }
  32921. /**
  32922. * Module for representing ambient lights as nodes.
  32923. *
  32924. * @augments AnalyticLightNode
  32925. */
  32926. class AmbientLightNode extends AnalyticLightNode {
  32927. static get type() {
  32928. return 'AmbientLightNode';
  32929. }
  32930. /**
  32931. * Constructs a new ambient light node.
  32932. *
  32933. * @param {?AmbientLight} [light=null] - The ambient light source.
  32934. */
  32935. constructor( light = null ) {
  32936. super( light );
  32937. }
  32938. setup( { context } ) {
  32939. context.irradiance.addAssign( this.colorNode );
  32940. }
  32941. }
  32942. /**
  32943. * Module for representing hemisphere lights as nodes.
  32944. *
  32945. * @augments AnalyticLightNode
  32946. */
  32947. class HemisphereLightNode extends AnalyticLightNode {
  32948. static get type() {
  32949. return 'HemisphereLightNode';
  32950. }
  32951. /**
  32952. * Constructs a new hemisphere light node.
  32953. *
  32954. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  32955. */
  32956. constructor( light = null ) {
  32957. super( light );
  32958. /**
  32959. * Uniform node representing the light's position.
  32960. *
  32961. * @type {UniformNode<vec3>}
  32962. */
  32963. this.lightPositionNode = lightPosition( light );
  32964. /**
  32965. * A node representing the light's direction.
  32966. *
  32967. * @type {Node<vec3>}
  32968. */
  32969. this.lightDirectionNode = this.lightPositionNode.normalize();
  32970. /**
  32971. * Uniform node representing the light's ground color.
  32972. *
  32973. * @type {UniformNode<vec3>}
  32974. */
  32975. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  32976. }
  32977. /**
  32978. * Overwritten to updated hemisphere light specific uniforms.
  32979. *
  32980. * @param {NodeFrame} frame - A reference to the current node frame.
  32981. */
  32982. update( frame ) {
  32983. const { light } = this;
  32984. super.update( frame );
  32985. this.lightPositionNode.object3d = light;
  32986. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32987. }
  32988. setup( builder ) {
  32989. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32990. const dotNL = normalView.dot( lightDirectionNode );
  32991. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32992. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32993. builder.context.irradiance.addAssign( irradiance );
  32994. }
  32995. }
  32996. /**
  32997. * Module for representing light probes as nodes.
  32998. *
  32999. * @augments AnalyticLightNode
  33000. */
  33001. class LightProbeNode extends AnalyticLightNode {
  33002. static get type() {
  33003. return 'LightProbeNode';
  33004. }
  33005. /**
  33006. * Constructs a new light probe node.
  33007. *
  33008. * @param {?LightProbe} [light=null] - The light probe.
  33009. */
  33010. constructor( light = null ) {
  33011. super( light );
  33012. const array = [];
  33013. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  33014. /**
  33015. * Light probe represented as a uniform of spherical harmonics.
  33016. *
  33017. * @type {UniformArrayNode}
  33018. */
  33019. this.lightProbe = uniformArray( array );
  33020. }
  33021. /**
  33022. * Overwritten to updated light probe specific uniforms.
  33023. *
  33024. * @param {NodeFrame} frame - A reference to the current node frame.
  33025. */
  33026. update( frame ) {
  33027. const { light } = this;
  33028. super.update( frame );
  33029. //
  33030. for ( let i = 0; i < 9; i ++ ) {
  33031. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  33032. }
  33033. }
  33034. setup( builder ) {
  33035. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  33036. builder.context.irradiance.addAssign( irradiance );
  33037. }
  33038. }
  33039. /**
  33040. * Base class for node parsers. A derived parser must be implemented
  33041. * for each supported native shader language.
  33042. */
  33043. class NodeParser {
  33044. /**
  33045. * The method parses the given native code an returns a node function.
  33046. *
  33047. * @abstract
  33048. * @param {string} source - The native shader code.
  33049. * @return {NodeFunction} A node function.
  33050. */
  33051. parseFunction( /*source*/ ) {
  33052. console.warn( 'Abstract function.' );
  33053. }
  33054. }
  33055. /**
  33056. * Base class for node functions. A derived module must be implemented
  33057. * for each supported native shader language. Similar to other `Node*` modules,
  33058. * this class is only relevant during the building process and not used
  33059. * in user-level code.
  33060. */
  33061. class NodeFunction {
  33062. /**
  33063. * Constructs a new node function.
  33064. *
  33065. * @param {string} type - The node type. This type is the return type of the node function.
  33066. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  33067. * @param {string} [name=''] - The function's name.
  33068. * @param {string} [precision=''] - The precision qualifier.
  33069. */
  33070. constructor( type, inputs, name = '', precision = '' ) {
  33071. /**
  33072. * The node type. This type is the return type of the node function.
  33073. *
  33074. * @type {string}
  33075. */
  33076. this.type = type;
  33077. /**
  33078. * The function's inputs.
  33079. *
  33080. * @type {Array<NodeFunctionInput>}
  33081. */
  33082. this.inputs = inputs;
  33083. /**
  33084. * The name of the uniform.
  33085. *
  33086. * @type {string}
  33087. * @default ''
  33088. */
  33089. this.name = name;
  33090. /**
  33091. * The precision qualifier.
  33092. *
  33093. * @type {string}
  33094. * @default ''
  33095. */
  33096. this.precision = precision;
  33097. }
  33098. /**
  33099. * This method returns the native code of the node function.
  33100. *
  33101. * @abstract
  33102. * @param {string} name - The function's name.
  33103. * @return {string} A shader code.
  33104. */
  33105. getCode( /*name = this.name*/ ) {
  33106. console.warn( 'Abstract function.' );
  33107. }
  33108. }
  33109. NodeFunction.isNodeFunction = true;
  33110. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33111. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33112. const pragmaMain = '#pragma main';
  33113. const parse$1 = ( source ) => {
  33114. source = source.trim();
  33115. const pragmaMainIndex = source.indexOf( pragmaMain );
  33116. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33117. const declaration = mainCode.match( declarationRegexp$1 );
  33118. if ( declaration !== null && declaration.length === 5 ) {
  33119. // tokenizer
  33120. const inputsCode = declaration[ 4 ];
  33121. const propsMatches = [];
  33122. let nameMatch = null;
  33123. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33124. propsMatches.push( nameMatch );
  33125. }
  33126. // parser
  33127. const inputs = [];
  33128. let i = 0;
  33129. while ( i < propsMatches.length ) {
  33130. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33131. if ( isConst === true ) {
  33132. i ++;
  33133. }
  33134. let qualifier = propsMatches[ i ][ 0 ];
  33135. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33136. i ++;
  33137. } else {
  33138. qualifier = '';
  33139. }
  33140. const type = propsMatches[ i ++ ][ 0 ];
  33141. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33142. if ( Number.isNaN( count ) === false ) i ++;
  33143. else count = null;
  33144. const name = propsMatches[ i ++ ][ 0 ];
  33145. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33146. }
  33147. //
  33148. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33149. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33150. const type = declaration[ 2 ];
  33151. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33152. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  33153. return {
  33154. type,
  33155. inputs,
  33156. name,
  33157. precision,
  33158. inputsCode,
  33159. blockCode,
  33160. headerCode
  33161. };
  33162. } else {
  33163. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33164. }
  33165. };
  33166. /**
  33167. * This class represents a GLSL node function.
  33168. *
  33169. * @augments NodeFunction
  33170. */
  33171. class GLSLNodeFunction extends NodeFunction {
  33172. /**
  33173. * Constructs a new GLSL node function.
  33174. *
  33175. * @param {string} source - The GLSL source.
  33176. */
  33177. constructor( source ) {
  33178. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33179. super( type, inputs, name, precision );
  33180. this.inputsCode = inputsCode;
  33181. this.blockCode = blockCode;
  33182. this.headerCode = headerCode;
  33183. }
  33184. /**
  33185. * This method returns the GLSL code of the node function.
  33186. *
  33187. * @param {string} [name=this.name] - The function's name.
  33188. * @return {string} The shader code.
  33189. */
  33190. getCode( name = this.name ) {
  33191. let code;
  33192. const blockCode = this.blockCode;
  33193. if ( blockCode !== '' ) {
  33194. const { type, inputsCode, headerCode, precision } = this;
  33195. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33196. if ( precision !== '' ) {
  33197. declarationCode = `${ precision } ${ declarationCode }`;
  33198. }
  33199. code = headerCode + declarationCode + blockCode;
  33200. } else {
  33201. // interface function
  33202. code = '';
  33203. }
  33204. return code;
  33205. }
  33206. }
  33207. /**
  33208. * A GLSL node parser.
  33209. *
  33210. * @augments NodeParser
  33211. */
  33212. class GLSLNodeParser extends NodeParser {
  33213. /**
  33214. * The method parses the given GLSL code an returns a node function.
  33215. *
  33216. * @param {string} source - The GLSL code.
  33217. * @return {GLSLNodeFunction} A node function.
  33218. */
  33219. parseFunction( source ) {
  33220. return new GLSLNodeFunction( source );
  33221. }
  33222. }
  33223. const _outputNodeMap = new WeakMap();
  33224. const _chainKeys$2 = [];
  33225. const _cacheKeyValues = [];
  33226. /**
  33227. * This renderer module manages node-related objects and is the
  33228. * primary interface between the renderer and the node system.
  33229. *
  33230. * @private
  33231. * @augments DataMap
  33232. */
  33233. class Nodes extends DataMap {
  33234. /**
  33235. * Constructs a new nodes management component.
  33236. *
  33237. * @param {Renderer} renderer - The renderer.
  33238. * @param {Backend} backend - The renderer's backend.
  33239. */
  33240. constructor( renderer, backend ) {
  33241. super();
  33242. /**
  33243. * The renderer.
  33244. *
  33245. * @type {Renderer}
  33246. */
  33247. this.renderer = renderer;
  33248. /**
  33249. * The renderer's backend.
  33250. *
  33251. * @type {Backend}
  33252. */
  33253. this.backend = backend;
  33254. /**
  33255. * The node frame.
  33256. *
  33257. * @type {Renderer}
  33258. */
  33259. this.nodeFrame = new NodeFrame();
  33260. /**
  33261. * A cache for managing node builder states.
  33262. *
  33263. * @type {Map<number,NodeBuilderState>}
  33264. */
  33265. this.nodeBuilderCache = new Map();
  33266. /**
  33267. * A cache for managing data cache key data.
  33268. *
  33269. * @type {ChainMap}
  33270. */
  33271. this.callHashCache = new ChainMap();
  33272. /**
  33273. * A cache for managing node uniforms group data.
  33274. *
  33275. * @type {ChainMap}
  33276. */
  33277. this.groupsData = new ChainMap();
  33278. /**
  33279. * A cache for managing node objects of
  33280. * scene properties like fog or environments.
  33281. *
  33282. * @type {Object<string,WeakMap>}
  33283. */
  33284. this.cacheLib = {};
  33285. }
  33286. /**
  33287. * Returns `true` if the given node uniforms group must be updated or not.
  33288. *
  33289. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  33290. * @return {boolean} Whether the node uniforms group requires an update or not.
  33291. */
  33292. updateGroup( nodeUniformsGroup ) {
  33293. const groupNode = nodeUniformsGroup.groupNode;
  33294. const name = groupNode.name;
  33295. // objectGroup is always updated
  33296. if ( name === objectGroup.name ) return true;
  33297. // renderGroup is updated once per render/compute call
  33298. if ( name === renderGroup.name ) {
  33299. const uniformsGroupData = this.get( nodeUniformsGroup );
  33300. const renderId = this.nodeFrame.renderId;
  33301. if ( uniformsGroupData.renderId !== renderId ) {
  33302. uniformsGroupData.renderId = renderId;
  33303. return true;
  33304. }
  33305. return false;
  33306. }
  33307. // frameGroup is updated once per frame
  33308. if ( name === frameGroup.name ) {
  33309. const uniformsGroupData = this.get( nodeUniformsGroup );
  33310. const frameId = this.nodeFrame.frameId;
  33311. if ( uniformsGroupData.frameId !== frameId ) {
  33312. uniformsGroupData.frameId = frameId;
  33313. return true;
  33314. }
  33315. return false;
  33316. }
  33317. // other groups are updated just when groupNode.needsUpdate is true
  33318. _chainKeys$2[ 0 ] = groupNode;
  33319. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  33320. let groupData = this.groupsData.get( _chainKeys$2 );
  33321. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  33322. _chainKeys$2.length = 0;
  33323. if ( groupData.version !== groupNode.version ) {
  33324. groupData.version = groupNode.version;
  33325. return true;
  33326. }
  33327. return false;
  33328. }
  33329. /**
  33330. * Returns the cache key for the given render object.
  33331. *
  33332. * @param {RenderObject} renderObject - The render object.
  33333. * @return {number} The cache key.
  33334. */
  33335. getForRenderCacheKey( renderObject ) {
  33336. return renderObject.initialCacheKey;
  33337. }
  33338. /**
  33339. * Returns a node builder state for the given render object.
  33340. *
  33341. * @param {RenderObject} renderObject - The render object.
  33342. * @return {NodeBuilderState} The node builder state.
  33343. */
  33344. getForRender( renderObject ) {
  33345. const renderObjectData = this.get( renderObject );
  33346. let nodeBuilderState = renderObjectData.nodeBuilderState;
  33347. if ( nodeBuilderState === undefined ) {
  33348. const { nodeBuilderCache } = this;
  33349. const cacheKey = this.getForRenderCacheKey( renderObject );
  33350. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  33351. if ( nodeBuilderState === undefined ) {
  33352. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  33353. nodeBuilder.scene = renderObject.scene;
  33354. nodeBuilder.material = renderObject.material;
  33355. nodeBuilder.camera = renderObject.camera;
  33356. nodeBuilder.context.material = renderObject.material;
  33357. nodeBuilder.lightsNode = renderObject.lightsNode;
  33358. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  33359. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  33360. nodeBuilder.clippingContext = renderObject.clippingContext;
  33361. nodeBuilder.build();
  33362. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33363. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  33364. }
  33365. nodeBuilderState.usedTimes ++;
  33366. renderObjectData.nodeBuilderState = nodeBuilderState;
  33367. }
  33368. return nodeBuilderState;
  33369. }
  33370. /**
  33371. * Deletes the given object from the internal data map
  33372. *
  33373. * @param {any} object - The object to delete.
  33374. * @return {?Object} The deleted dictionary.
  33375. */
  33376. delete( object ) {
  33377. if ( object.isRenderObject ) {
  33378. const nodeBuilderState = this.get( object ).nodeBuilderState;
  33379. nodeBuilderState.usedTimes --;
  33380. if ( nodeBuilderState.usedTimes === 0 ) {
  33381. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  33382. }
  33383. }
  33384. return super.delete( object );
  33385. }
  33386. /**
  33387. * Returns a node builder state for the given compute node.
  33388. *
  33389. * @param {Node} computeNode - The compute node.
  33390. * @return {NodeBuilderState} The node builder state.
  33391. */
  33392. getForCompute( computeNode ) {
  33393. const computeData = this.get( computeNode );
  33394. let nodeBuilderState = computeData.nodeBuilderState;
  33395. if ( nodeBuilderState === undefined ) {
  33396. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  33397. nodeBuilder.build();
  33398. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33399. computeData.nodeBuilderState = nodeBuilderState;
  33400. }
  33401. return nodeBuilderState;
  33402. }
  33403. /**
  33404. * Creates a node builder state for the given node builder.
  33405. *
  33406. * @private
  33407. * @param {NodeBuilder} nodeBuilder - The node builder.
  33408. * @return {NodeBuilderState} The node builder state.
  33409. */
  33410. _createNodeBuilderState( nodeBuilder ) {
  33411. return new NodeBuilderState(
  33412. nodeBuilder.vertexShader,
  33413. nodeBuilder.fragmentShader,
  33414. nodeBuilder.computeShader,
  33415. nodeBuilder.getAttributesArray(),
  33416. nodeBuilder.getBindings(),
  33417. nodeBuilder.updateNodes,
  33418. nodeBuilder.updateBeforeNodes,
  33419. nodeBuilder.updateAfterNodes,
  33420. nodeBuilder.observer,
  33421. nodeBuilder.transforms
  33422. );
  33423. }
  33424. /**
  33425. * Returns an environment node for the current configured
  33426. * scene environment.
  33427. *
  33428. * @param {Scene} scene - The scene.
  33429. * @return {Node} A node representing the current scene environment.
  33430. */
  33431. getEnvironmentNode( scene ) {
  33432. this.updateEnvironment( scene );
  33433. let environmentNode = null;
  33434. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  33435. environmentNode = scene.environmentNode;
  33436. } else {
  33437. const sceneData = this.get( scene );
  33438. if ( sceneData.environmentNode ) {
  33439. environmentNode = sceneData.environmentNode;
  33440. }
  33441. }
  33442. return environmentNode;
  33443. }
  33444. /**
  33445. * Returns a background node for the current configured
  33446. * scene background.
  33447. *
  33448. * @param {Scene} scene - The scene.
  33449. * @return {Node} A node representing the current scene background.
  33450. */
  33451. getBackgroundNode( scene ) {
  33452. this.updateBackground( scene );
  33453. let backgroundNode = null;
  33454. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  33455. backgroundNode = scene.backgroundNode;
  33456. } else {
  33457. const sceneData = this.get( scene );
  33458. if ( sceneData.backgroundNode ) {
  33459. backgroundNode = sceneData.backgroundNode;
  33460. }
  33461. }
  33462. return backgroundNode;
  33463. }
  33464. /**
  33465. * Returns a fog node for the current configured scene fog.
  33466. *
  33467. * @param {Scene} scene - The scene.
  33468. * @return {Node} A node representing the current scene fog.
  33469. */
  33470. getFogNode( scene ) {
  33471. this.updateFog( scene );
  33472. return scene.fogNode || this.get( scene ).fogNode || null;
  33473. }
  33474. /**
  33475. * Returns a cache key for the given scene and lights node.
  33476. * This key is used by `RenderObject` as a part of the dynamic
  33477. * cache key (a key that must be checked every time the render
  33478. * objects is drawn).
  33479. *
  33480. * @param {Scene} scene - The scene.
  33481. * @param {LightsNode} lightsNode - The lights node.
  33482. * @return {number} The cache key.
  33483. */
  33484. getCacheKey( scene, lightsNode ) {
  33485. _chainKeys$2[ 0 ] = scene;
  33486. _chainKeys$2[ 1 ] = lightsNode;
  33487. const callId = this.renderer.info.calls;
  33488. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  33489. if ( cacheKeyData.callId !== callId ) {
  33490. const environmentNode = this.getEnvironmentNode( scene );
  33491. const fogNode = this.getFogNode( scene );
  33492. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  33493. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  33494. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  33495. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  33496. cacheKeyData.callId = callId;
  33497. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  33498. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  33499. _cacheKeyValues.length = 0;
  33500. }
  33501. _chainKeys$2.length = 0;
  33502. return cacheKeyData.cacheKey;
  33503. }
  33504. /**
  33505. * A boolean that indicates whether tone mapping should be enabled
  33506. * or not.
  33507. *
  33508. * @type {boolean}
  33509. */
  33510. get isToneMappingState() {
  33511. return this.renderer.getRenderTarget() ? false : true;
  33512. }
  33513. /**
  33514. * If a scene background is configured, this method makes sure to
  33515. * represent the background with a corresponding node-based implementation.
  33516. *
  33517. * @param {Scene} scene - The scene.
  33518. */
  33519. updateBackground( scene ) {
  33520. const sceneData = this.get( scene );
  33521. const background = scene.background;
  33522. if ( background ) {
  33523. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  33524. if ( sceneData.background !== background || forceUpdate ) {
  33525. const backgroundNode = this.getCacheNode( 'background', background, () => {
  33526. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  33527. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  33528. return pmremTexture( background );
  33529. } else {
  33530. let envMap;
  33531. if ( background.isCubeTexture === true ) {
  33532. envMap = cubeTexture( background );
  33533. } else {
  33534. envMap = texture( background );
  33535. }
  33536. return cubeMapNode( envMap );
  33537. }
  33538. } else if ( background.isTexture === true ) {
  33539. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  33540. } else if ( background.isColor !== true ) {
  33541. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  33542. }
  33543. }, forceUpdate );
  33544. sceneData.backgroundNode = backgroundNode;
  33545. sceneData.background = background;
  33546. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  33547. }
  33548. } else if ( sceneData.backgroundNode ) {
  33549. delete sceneData.backgroundNode;
  33550. delete sceneData.background;
  33551. }
  33552. }
  33553. /**
  33554. * This method is part of the caching of nodes which are used to represents the
  33555. * scene's background, fog or environment.
  33556. *
  33557. * @param {string} type - The type of object to cache.
  33558. * @param {Object} object - The object.
  33559. * @param {Function} callback - A callback that produces a node representation for the given object.
  33560. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  33561. * @return {Node} The node representation.
  33562. */
  33563. getCacheNode( type, object, callback, forceUpdate = false ) {
  33564. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  33565. let node = nodeCache.get( object );
  33566. if ( node === undefined || forceUpdate ) {
  33567. node = callback();
  33568. nodeCache.set( object, node );
  33569. }
  33570. return node;
  33571. }
  33572. /**
  33573. * If a scene fog is configured, this method makes sure to
  33574. * represent the fog with a corresponding node-based implementation.
  33575. *
  33576. * @param {Scene} scene - The scene.
  33577. */
  33578. updateFog( scene ) {
  33579. const sceneData = this.get( scene );
  33580. const sceneFog = scene.fog;
  33581. if ( sceneFog ) {
  33582. if ( sceneData.fog !== sceneFog ) {
  33583. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  33584. if ( sceneFog.isFogExp2 ) {
  33585. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33586. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  33587. return fog( color, densityFogFactor( density ) );
  33588. } else if ( sceneFog.isFog ) {
  33589. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33590. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  33591. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  33592. return fog( color, rangeFogFactor( near, far ) );
  33593. } else {
  33594. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  33595. }
  33596. } );
  33597. sceneData.fogNode = fogNode;
  33598. sceneData.fog = sceneFog;
  33599. }
  33600. } else {
  33601. delete sceneData.fogNode;
  33602. delete sceneData.fog;
  33603. }
  33604. }
  33605. /**
  33606. * If a scene environment is configured, this method makes sure to
  33607. * represent the environment with a corresponding node-based implementation.
  33608. *
  33609. * @param {Scene} scene - The scene.
  33610. */
  33611. updateEnvironment( scene ) {
  33612. const sceneData = this.get( scene );
  33613. const environment = scene.environment;
  33614. if ( environment ) {
  33615. if ( sceneData.environment !== environment ) {
  33616. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  33617. if ( environment.isCubeTexture === true ) {
  33618. return cubeTexture( environment );
  33619. } else if ( environment.isTexture === true ) {
  33620. return texture( environment );
  33621. } else {
  33622. console.error( 'Nodes: Unsupported environment configuration.', environment );
  33623. }
  33624. } );
  33625. sceneData.environmentNode = environmentNode;
  33626. sceneData.environment = environment;
  33627. }
  33628. } else if ( sceneData.environmentNode ) {
  33629. delete sceneData.environmentNode;
  33630. delete sceneData.environment;
  33631. }
  33632. }
  33633. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  33634. const nodeFrame = this.nodeFrame;
  33635. nodeFrame.renderer = renderer;
  33636. nodeFrame.scene = scene;
  33637. nodeFrame.object = object;
  33638. nodeFrame.camera = camera;
  33639. nodeFrame.material = material;
  33640. return nodeFrame;
  33641. }
  33642. getNodeFrameForRender( renderObject ) {
  33643. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  33644. }
  33645. /**
  33646. * Returns the current output cache key.
  33647. *
  33648. * @return {string} The output cache key.
  33649. */
  33650. getOutputCacheKey() {
  33651. const renderer = this.renderer;
  33652. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  33653. }
  33654. /**
  33655. * Checks if the output configuration (tone mapping and color space) for
  33656. * the given target has changed.
  33657. *
  33658. * @param {Texture} outputTarget - The output target.
  33659. * @return {boolean} Whether the output configuration has changed or not.
  33660. */
  33661. hasOutputChange( outputTarget ) {
  33662. const cacheKey = _outputNodeMap.get( outputTarget );
  33663. return cacheKey !== this.getOutputCacheKey();
  33664. }
  33665. /**
  33666. * Returns a node that represents the output configuration (tone mapping and
  33667. * color space) for the current target.
  33668. *
  33669. * @param {Texture} outputTarget - The output target.
  33670. * @return {Node} The output node.
  33671. */
  33672. getOutputNode( outputTarget ) {
  33673. const renderer = this.renderer;
  33674. const cacheKey = this.getOutputCacheKey();
  33675. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  33676. _outputNodeMap.set( outputTarget, cacheKey );
  33677. return output;
  33678. }
  33679. /**
  33680. * Triggers the call of `updateBefore()` methods
  33681. * for all nodes of the given render object.
  33682. *
  33683. * @param {RenderObject} renderObject - The render object.
  33684. */
  33685. updateBefore( renderObject ) {
  33686. const nodeBuilder = renderObject.getNodeBuilderState();
  33687. for ( const node of nodeBuilder.updateBeforeNodes ) {
  33688. // update frame state for each node
  33689. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  33690. }
  33691. }
  33692. /**
  33693. * Triggers the call of `updateAfter()` methods
  33694. * for all nodes of the given render object.
  33695. *
  33696. * @param {RenderObject} renderObject - The render object.
  33697. */
  33698. updateAfter( renderObject ) {
  33699. const nodeBuilder = renderObject.getNodeBuilderState();
  33700. for ( const node of nodeBuilder.updateAfterNodes ) {
  33701. // update frame state for each node
  33702. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  33703. }
  33704. }
  33705. /**
  33706. * Triggers the call of `update()` methods
  33707. * for all nodes of the given compute node.
  33708. *
  33709. * @param {Node} computeNode - The compute node.
  33710. */
  33711. updateForCompute( computeNode ) {
  33712. const nodeFrame = this.getNodeFrame();
  33713. const nodeBuilder = this.getForCompute( computeNode );
  33714. for ( const node of nodeBuilder.updateNodes ) {
  33715. nodeFrame.updateNode( node );
  33716. }
  33717. }
  33718. /**
  33719. * Triggers the call of `update()` methods
  33720. * for all nodes of the given compute node.
  33721. *
  33722. * @param {RenderObject} renderObject - The render object.
  33723. */
  33724. updateForRender( renderObject ) {
  33725. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33726. const nodeBuilder = renderObject.getNodeBuilderState();
  33727. for ( const node of nodeBuilder.updateNodes ) {
  33728. nodeFrame.updateNode( node );
  33729. }
  33730. }
  33731. /**
  33732. * Returns `true` if the given render object requires a refresh.
  33733. *
  33734. * @param {RenderObject} renderObject - The render object.
  33735. * @return {boolean} Whether the given render object requires a refresh or not.
  33736. */
  33737. needsRefresh( renderObject ) {
  33738. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33739. const monitor = renderObject.getMonitor();
  33740. return monitor.needsRefresh( renderObject, nodeFrame );
  33741. }
  33742. /**
  33743. * Frees the internal resources.
  33744. */
  33745. dispose() {
  33746. super.dispose();
  33747. this.nodeFrame = new NodeFrame();
  33748. this.nodeBuilderCache = new Map();
  33749. this.cacheLib = {};
  33750. }
  33751. }
  33752. const _plane = /*@__PURE__*/ new Plane();
  33753. /**
  33754. * Represents the state that is used to perform clipping via clipping planes.
  33755. * There is a default clipping context for each render context. When the
  33756. * scene holds instances of `ClippingGroup`, there will be a context for each
  33757. * group.
  33758. *
  33759. * @private
  33760. */
  33761. class ClippingContext {
  33762. /**
  33763. * Constructs a new clipping context.
  33764. *
  33765. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  33766. */
  33767. constructor( parentContext = null ) {
  33768. /**
  33769. * The clipping context's version.
  33770. *
  33771. * @type {number}
  33772. * @readonly
  33773. */
  33774. this.version = 0;
  33775. /**
  33776. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  33777. *
  33778. * @type {?boolean}
  33779. * @default null
  33780. */
  33781. this.clipIntersection = null;
  33782. /**
  33783. * The clipping context's cache key.
  33784. *
  33785. * @type {string}
  33786. */
  33787. this.cacheKey = '';
  33788. /**
  33789. * Whether the shadow pass is active or not.
  33790. *
  33791. * @type {boolean}
  33792. * @default false
  33793. */
  33794. this.shadowPass = false;
  33795. /**
  33796. * The view normal matrix.
  33797. *
  33798. * @type {Matrix3}
  33799. */
  33800. this.viewNormalMatrix = new Matrix3();
  33801. /**
  33802. * Internal cache for maintaining clipping contexts.
  33803. *
  33804. * @type {WeakMap<ClippingGroup,ClippingContext>}
  33805. */
  33806. this.clippingGroupContexts = new WeakMap();
  33807. /**
  33808. * The intersection planes.
  33809. *
  33810. * @type {Array<Vector4>}
  33811. */
  33812. this.intersectionPlanes = [];
  33813. /**
  33814. * The intersection planes.
  33815. *
  33816. * @type {Array<Vector4>}
  33817. */
  33818. this.unionPlanes = [];
  33819. /**
  33820. * The version of the clipping context's parent context.
  33821. *
  33822. * @type {?number}
  33823. * @readonly
  33824. */
  33825. this.parentVersion = null;
  33826. if ( parentContext !== null ) {
  33827. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  33828. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  33829. this.shadowPass = parentContext.shadowPass;
  33830. this.viewMatrix = parentContext.viewMatrix;
  33831. }
  33832. }
  33833. /**
  33834. * Projects the given source clipping planes and writes the result into the
  33835. * destination array.
  33836. *
  33837. * @param {Array<Plane>} source - The source clipping planes.
  33838. * @param {Array<Vector4>} destination - The destination.
  33839. * @param {number} offset - The offset.
  33840. */
  33841. projectPlanes( source, destination, offset ) {
  33842. const l = source.length;
  33843. for ( let i = 0; i < l; i ++ ) {
  33844. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  33845. const v = destination[ offset + i ];
  33846. const normal = _plane.normal;
  33847. v.x = - normal.x;
  33848. v.y = - normal.y;
  33849. v.z = - normal.z;
  33850. v.w = _plane.constant;
  33851. }
  33852. }
  33853. /**
  33854. * Updates the root clipping context of a scene.
  33855. *
  33856. * @param {Scene} scene - The scene.
  33857. * @param {Camera} camera - The camera that is used to render the scene.
  33858. */
  33859. updateGlobal( scene, camera ) {
  33860. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  33861. this.viewMatrix = camera.matrixWorldInverse;
  33862. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  33863. }
  33864. /**
  33865. * Updates the clipping context.
  33866. *
  33867. * @param {ClippingContext} parentContext - The parent context.
  33868. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  33869. */
  33870. update( parentContext, clippingGroup ) {
  33871. let update = false;
  33872. if ( parentContext.version !== this.parentVersion ) {
  33873. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  33874. this.unionPlanes = Array.from( parentContext.unionPlanes );
  33875. this.parentVersion = parentContext.version;
  33876. }
  33877. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  33878. this.clipIntersection = clippingGroup.clipIntersection;
  33879. if ( this.clipIntersection ) {
  33880. this.unionPlanes.length = parentContext.unionPlanes.length;
  33881. } else {
  33882. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  33883. }
  33884. }
  33885. const srcClippingPlanes = clippingGroup.clippingPlanes;
  33886. const l = srcClippingPlanes.length;
  33887. let dstClippingPlanes;
  33888. let offset;
  33889. if ( this.clipIntersection ) {
  33890. dstClippingPlanes = this.intersectionPlanes;
  33891. offset = parentContext.intersectionPlanes.length;
  33892. } else {
  33893. dstClippingPlanes = this.unionPlanes;
  33894. offset = parentContext.unionPlanes.length;
  33895. }
  33896. if ( dstClippingPlanes.length !== offset + l ) {
  33897. dstClippingPlanes.length = offset + l;
  33898. for ( let i = 0; i < l; i ++ ) {
  33899. dstClippingPlanes[ offset + i ] = new Vector4();
  33900. }
  33901. update = true;
  33902. }
  33903. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  33904. if ( update ) {
  33905. this.version ++;
  33906. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  33907. }
  33908. }
  33909. /**
  33910. * Returns a clipping context for the given clipping group.
  33911. *
  33912. * @param {ClippingGroup} clippingGroup - The clipping group.
  33913. * @return {ClippingContext} The clipping context.
  33914. */
  33915. getGroupContext( clippingGroup ) {
  33916. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  33917. let context = this.clippingGroupContexts.get( clippingGroup );
  33918. if ( context === undefined ) {
  33919. context = new ClippingContext( this );
  33920. this.clippingGroupContexts.set( clippingGroup, context );
  33921. }
  33922. context.update( this, clippingGroup );
  33923. return context;
  33924. }
  33925. /**
  33926. * The count of union clipping planes.
  33927. *
  33928. * @type {number}
  33929. * @readonly
  33930. */
  33931. get unionClippingCount() {
  33932. return this.unionPlanes.length;
  33933. }
  33934. }
  33935. /**
  33936. * This module is used to represent render bundles inside the renderer
  33937. * for further processing.
  33938. *
  33939. * @private
  33940. */
  33941. class RenderBundle {
  33942. /**
  33943. * Constructs a new bundle group.
  33944. *
  33945. * @param {BundleGroup} bundleGroup - The bundle group.
  33946. * @param {Camera} camera - The camera the bundle group is rendered with.
  33947. */
  33948. constructor( bundleGroup, camera ) {
  33949. this.bundleGroup = bundleGroup;
  33950. this.camera = camera;
  33951. }
  33952. }
  33953. const _chainKeys$1 = [];
  33954. /**
  33955. * This renderer module manages render bundles.
  33956. *
  33957. * @private
  33958. */
  33959. class RenderBundles {
  33960. /**
  33961. * Constructs a new render bundle management component.
  33962. */
  33963. constructor() {
  33964. /**
  33965. * A chain map for maintaining the render bundles.
  33966. *
  33967. * @type {ChainMap}
  33968. */
  33969. this.bundles = new ChainMap();
  33970. }
  33971. /**
  33972. * Returns a render bundle for the given bundle group and camera.
  33973. *
  33974. * @param {BundleGroup} bundleGroup - The bundle group.
  33975. * @param {Camera} camera - The camera the bundle group is rendered with.
  33976. * @return {RenderBundle} The render bundle.
  33977. */
  33978. get( bundleGroup, camera ) {
  33979. const bundles = this.bundles;
  33980. _chainKeys$1[ 0 ] = bundleGroup;
  33981. _chainKeys$1[ 1 ] = camera;
  33982. let bundle = bundles.get( _chainKeys$1 );
  33983. if ( bundle === undefined ) {
  33984. bundle = new RenderBundle( bundleGroup, camera );
  33985. bundles.set( _chainKeys$1, bundle );
  33986. }
  33987. _chainKeys$1.length = 0;
  33988. return bundle;
  33989. }
  33990. /**
  33991. * Frees all internal resources.
  33992. */
  33993. dispose() {
  33994. this.bundles = new ChainMap();
  33995. }
  33996. }
  33997. /**
  33998. * The purpose of a node library is to assign node implementations
  33999. * to existing library features. In `WebGPURenderer` lights, materials
  34000. * which are not based on `NodeMaterial` as well as tone mapping techniques
  34001. * are implemented with node-based modules.
  34002. *
  34003. * @private
  34004. */
  34005. class NodeLibrary {
  34006. /**
  34007. * Constructs a new node library.
  34008. */
  34009. constructor() {
  34010. /**
  34011. * A weak map that maps lights to light nodes.
  34012. *
  34013. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  34014. */
  34015. this.lightNodes = new WeakMap();
  34016. /**
  34017. * A map that maps materials to node materials.
  34018. *
  34019. * @type {Map<string,NodeMaterial.constructor>}
  34020. */
  34021. this.materialNodes = new Map();
  34022. /**
  34023. * A map that maps tone mapping techniques (constants)
  34024. * to tone mapping node functions.
  34025. *
  34026. * @type {Map<number,Function>}
  34027. */
  34028. this.toneMappingNodes = new Map();
  34029. }
  34030. /**
  34031. * Returns a matching node material instance for the given material object.
  34032. *
  34033. * This method also assigns/copies the properties of the given material object
  34034. * to the node material. This is done to make sure the current material
  34035. * configuration carries over to the node version.
  34036. *
  34037. * @param {Material} material - A material.
  34038. * @return {NodeMaterial} The corresponding node material.
  34039. */
  34040. fromMaterial( material ) {
  34041. if ( material.isNodeMaterial ) return material;
  34042. let nodeMaterial = null;
  34043. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  34044. if ( nodeMaterialClass !== null ) {
  34045. nodeMaterial = new nodeMaterialClass();
  34046. for ( const key in material ) {
  34047. nodeMaterial[ key ] = material[ key ];
  34048. }
  34049. }
  34050. return nodeMaterial;
  34051. }
  34052. /**
  34053. * Adds a tone mapping node function for a tone mapping technique (constant).
  34054. *
  34055. * @param {Function} toneMappingNode - The tone mapping node function.
  34056. * @param {number} toneMapping - The tone mapping.
  34057. */
  34058. addToneMapping( toneMappingNode, toneMapping ) {
  34059. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  34060. }
  34061. /**
  34062. * Returns a tone mapping node function for a tone mapping technique (constant).
  34063. *
  34064. * @param {number} toneMapping - The tone mapping.
  34065. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  34066. */
  34067. getToneMappingFunction( toneMapping ) {
  34068. return this.toneMappingNodes.get( toneMapping ) || null;
  34069. }
  34070. /**
  34071. * Returns a node material class definition for a material type.
  34072. *
  34073. * @param {string} materialType - The material type.
  34074. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  34075. */
  34076. getMaterialNodeClass( materialType ) {
  34077. return this.materialNodes.get( materialType ) || null;
  34078. }
  34079. /**
  34080. * Adds a node material class definition for a given material type.
  34081. *
  34082. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  34083. * @param {string} materialClassType - The material type.
  34084. */
  34085. addMaterial( materialNodeClass, materialClassType ) {
  34086. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  34087. }
  34088. /**
  34089. * Returns a light node class definition for a light class definition.
  34090. *
  34091. * @param {Light.constructor} light - The light class definition.
  34092. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  34093. */
  34094. getLightNodeClass( light ) {
  34095. return this.lightNodes.get( light ) || null;
  34096. }
  34097. /**
  34098. * Adds a light node class definition for a given light class definition.
  34099. *
  34100. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  34101. * @param {Light.constructor} lightClass - The light class definition.
  34102. */
  34103. addLight( lightNodeClass, lightClass ) {
  34104. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  34105. }
  34106. /**
  34107. * Adds a node class definition for the given type to the provided type library.
  34108. *
  34109. * @param {any} nodeClass - The node class definition.
  34110. * @param {number|string} type - The object type.
  34111. * @param {Map} library - The type library.
  34112. */
  34113. addType( nodeClass, type, library ) {
  34114. if ( library.has( type ) ) {
  34115. console.warn( `Redefinition of node ${ type }` );
  34116. return;
  34117. }
  34118. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34119. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  34120. library.set( type, nodeClass );
  34121. }
  34122. /**
  34123. * Adds a node class definition for the given class definition to the provided type library.
  34124. *
  34125. * @param {any} nodeClass - The node class definition.
  34126. * @param {any} baseClass - The class definition.
  34127. * @param {WeakMap} library - The type library.
  34128. */
  34129. addClass( nodeClass, baseClass, library ) {
  34130. if ( library.has( baseClass ) ) {
  34131. console.warn( `Redefinition of node ${ baseClass.name }` );
  34132. return;
  34133. }
  34134. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34135. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  34136. library.set( baseClass, nodeClass );
  34137. }
  34138. }
  34139. const _defaultLights = /*@__PURE__*/ new LightsNode();
  34140. const _chainKeys = [];
  34141. /**
  34142. * This renderer module manages the lights nodes which are unique
  34143. * per scene and camera combination.
  34144. *
  34145. * The lights node itself is later configured in the render list
  34146. * with the actual lights from the scene.
  34147. *
  34148. * @private
  34149. * @augments ChainMap
  34150. */
  34151. class Lighting extends ChainMap {
  34152. /**
  34153. * Constructs a lighting management component.
  34154. */
  34155. constructor() {
  34156. super();
  34157. }
  34158. /**
  34159. * Creates a new lights node for the given array of lights.
  34160. *
  34161. * @param {Array<Light>} lights - The render object.
  34162. * @return {LightsNode} The lights node.
  34163. */
  34164. createNode( lights = [] ) {
  34165. return new LightsNode().setLights( lights );
  34166. }
  34167. /**
  34168. * Returns a lights node for the given scene and camera.
  34169. *
  34170. * @param {Scene} scene - The scene.
  34171. * @param {Camera} camera - The camera.
  34172. * @return {LightsNode} The lights node.
  34173. */
  34174. getNode( scene, camera ) {
  34175. // ignore post-processing
  34176. if ( scene.isQuadMesh ) return _defaultLights;
  34177. _chainKeys[ 0 ] = scene;
  34178. _chainKeys[ 1 ] = camera;
  34179. let node = this.get( _chainKeys );
  34180. if ( node === undefined ) {
  34181. node = this.createNode();
  34182. this.set( _chainKeys, node );
  34183. }
  34184. _chainKeys.length = 0;
  34185. return node;
  34186. }
  34187. }
  34188. /**
  34189. * A special type of render target that is used when rendering
  34190. * with the WebXR Device API.
  34191. *
  34192. * @private
  34193. * @augments RenderTarget
  34194. */
  34195. class XRRenderTarget extends RenderTarget {
  34196. /**
  34197. * Constructs a new XR render target.
  34198. *
  34199. * @param {number} [width=1] - The width of the render target.
  34200. * @param {number} [height=1] - The height of the render target.
  34201. * @param {Object} [options={}] - The configuration options.
  34202. */
  34203. constructor( width = 1, height = 1, options = {} ) {
  34204. super( width, height, options );
  34205. /**
  34206. * This flag can be used for type testing.
  34207. *
  34208. * @type {boolean}
  34209. * @readonly
  34210. * @default true
  34211. */
  34212. this.isXRRenderTarget = true;
  34213. /**
  34214. * Whether the attachments of the render target
  34215. * are defined by external textures. This flag is
  34216. * set to `true` when using the WebXR Layers API.
  34217. *
  34218. * @type {boolean}
  34219. * @default false
  34220. */
  34221. this.hasExternalTextures = false;
  34222. /**
  34223. * Whether a depth buffer should automatically be allocated
  34224. * for this XR render target or not.
  34225. *
  34226. * Allocating a depth buffer is the default behavior of XR render
  34227. * targets. However, when using the WebXR Layers API, this flag
  34228. * must be set to `false` when the `ignoreDepthValues` property of
  34229. * the projection layers evaluates to `false`.
  34230. *
  34231. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  34232. *
  34233. * @type {boolean}
  34234. * @default true
  34235. */
  34236. this.autoAllocateDepthBuffer = true;
  34237. }
  34238. copy( source ) {
  34239. super.copy( source );
  34240. this.hasExternalTextures = source.hasExternalTextures;
  34241. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  34242. return this;
  34243. }
  34244. }
  34245. const _cameraLPos = /*@__PURE__*/ new Vector3();
  34246. const _cameraRPos = /*@__PURE__*/ new Vector3();
  34247. /**
  34248. * The XR manager is built on top of the WebXR Device API to
  34249. * manage XR sessions with `WebGPURenderer`.
  34250. *
  34251. * XR is currently only supported with a WebGL 2 backend.
  34252. *
  34253. * @augments EventDispatcher
  34254. */
  34255. class XRManager extends EventDispatcher {
  34256. /**
  34257. * Constructs a new XR manager.
  34258. *
  34259. * @param {Renderer} renderer - The renderer.
  34260. */
  34261. constructor( renderer ) {
  34262. super();
  34263. /**
  34264. * This flag globally enables XR rendering.
  34265. *
  34266. * @type {boolean}
  34267. * @default false
  34268. */
  34269. this.enabled = false;
  34270. /**
  34271. * Whether the XR device is currently presenting or not.
  34272. *
  34273. * @type {boolean}
  34274. * @default false
  34275. * @readonly
  34276. */
  34277. this.isPresenting = false;
  34278. /**
  34279. * Whether the XR camera should automatically be updated or not.
  34280. *
  34281. * @type {boolean}
  34282. * @default true
  34283. */
  34284. this.cameraAutoUpdate = true;
  34285. /**
  34286. * The renderer.
  34287. *
  34288. * @private
  34289. * @type {Renderer}
  34290. */
  34291. this._renderer = renderer;
  34292. // camera
  34293. /**
  34294. * Represents the camera for the left eye.
  34295. *
  34296. * @private
  34297. * @type {PerspectiveCamera}
  34298. */
  34299. this._cameraL = new PerspectiveCamera();
  34300. this._cameraL.viewport = new Vector4();
  34301. /**
  34302. * Represents the camera for the right eye.
  34303. *
  34304. * @private
  34305. * @type {PerspectiveCamera}
  34306. */
  34307. this._cameraR = new PerspectiveCamera();
  34308. this._cameraR.viewport = new Vector4();
  34309. /**
  34310. * A list of cameras used for rendering the XR views.
  34311. *
  34312. * @private
  34313. * @type {Array<Camera>}
  34314. */
  34315. this._cameras = [ this._cameraL, this._cameraR ];
  34316. /**
  34317. * The main XR camera.
  34318. *
  34319. * @private
  34320. * @type {ArrayCamera}
  34321. */
  34322. this._cameraXR = new ArrayCamera();
  34323. /**
  34324. * The current near value of the XR camera.
  34325. *
  34326. * @private
  34327. * @type {?number}
  34328. * @default null
  34329. */
  34330. this._currentDepthNear = null;
  34331. /**
  34332. * The current far value of the XR camera.
  34333. *
  34334. * @private
  34335. * @type {?number}
  34336. * @default null
  34337. */
  34338. this._currentDepthFar = null;
  34339. /**
  34340. * A list of WebXR controllers requested by the application.
  34341. *
  34342. * @private
  34343. * @type {Array<WebXRController>}
  34344. */
  34345. this._controllers = [];
  34346. /**
  34347. * A list of XR input source. Each input source belongs to
  34348. * an instance of WebXRController.
  34349. *
  34350. * @private
  34351. * @type {Array<XRInputSource?>}
  34352. */
  34353. this._controllerInputSources = [];
  34354. /**
  34355. * The XR render target that represents the rendering destination
  34356. * during an active XR session.
  34357. *
  34358. * @private
  34359. * @type {?RenderTarget}
  34360. * @default null
  34361. */
  34362. this._xrRenderTarget = null;
  34363. /**
  34364. * An array holding all the non-projection layers
  34365. *
  34366. * @private
  34367. * @type {Array<Object>}
  34368. * @default []
  34369. */
  34370. this._layers = [];
  34371. /**
  34372. * Whether the device has support for all layer types.
  34373. *
  34374. * @type {boolean}
  34375. * @default false
  34376. */
  34377. this._supportsLayers = false;
  34378. /**
  34379. * Helper function to create native WebXR Layer.
  34380. *
  34381. * @private
  34382. * @type {Function}
  34383. */
  34384. this._createXRLayer = createXRLayer.bind( this );
  34385. /**
  34386. * The current WebGL context.
  34387. *
  34388. * @private
  34389. * @type {?WebGL2RenderingContext}
  34390. * @default null
  34391. */
  34392. this._gl = null;
  34393. /**
  34394. * The current animation context.
  34395. *
  34396. * @private
  34397. * @type {?Window}
  34398. * @default null
  34399. */
  34400. this._currentAnimationContext = null;
  34401. /**
  34402. * The current animation loop.
  34403. *
  34404. * @private
  34405. * @type {?Function}
  34406. * @default null
  34407. */
  34408. this._currentAnimationLoop = null;
  34409. /**
  34410. * The current pixel ratio.
  34411. *
  34412. * @private
  34413. * @type {?number}
  34414. * @default null
  34415. */
  34416. this._currentPixelRatio = null;
  34417. /**
  34418. * The current size of the renderer's canvas
  34419. * in logical pixel unit.
  34420. *
  34421. * @private
  34422. * @type {Vector2}
  34423. */
  34424. this._currentSize = new Vector2();
  34425. /**
  34426. * The default event listener for handling events inside a XR session.
  34427. *
  34428. * @private
  34429. * @type {Function}
  34430. */
  34431. this._onSessionEvent = onSessionEvent.bind( this );
  34432. /**
  34433. * The event listener for handling the end of a XR session.
  34434. *
  34435. * @private
  34436. * @type {Function}
  34437. */
  34438. this._onSessionEnd = onSessionEnd.bind( this );
  34439. /**
  34440. * The event listener for handling the `inputsourceschange` event.
  34441. *
  34442. * @private
  34443. * @type {Function}
  34444. */
  34445. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  34446. /**
  34447. * The animation loop which is used as a replacement for the default
  34448. * animation loop of the application. It is only used when a XR session
  34449. * is active.
  34450. *
  34451. * @private
  34452. * @type {Function}
  34453. */
  34454. this._onAnimationFrame = onAnimationFrame.bind( this );
  34455. /**
  34456. * The current XR reference space.
  34457. *
  34458. * @private
  34459. * @type {?XRReferenceSpace}
  34460. * @default null
  34461. */
  34462. this._referenceSpace = null;
  34463. /**
  34464. * The current XR reference space type.
  34465. *
  34466. * @private
  34467. * @type {XRReferenceSpaceType}
  34468. * @default 'local-floor'
  34469. */
  34470. this._referenceSpaceType = 'local-floor';
  34471. /**
  34472. * A custom reference space defined by the application.
  34473. *
  34474. * @private
  34475. * @type {?XRReferenceSpace}
  34476. * @default null
  34477. */
  34478. this._customReferenceSpace = null;
  34479. /**
  34480. * The framebuffer scale factor.
  34481. *
  34482. * @private
  34483. * @type {number}
  34484. * @default 1
  34485. */
  34486. this._framebufferScaleFactor = 1;
  34487. /**
  34488. * The foveation factor.
  34489. *
  34490. * @private
  34491. * @type {number}
  34492. * @default 1
  34493. */
  34494. this._foveation = 1.0;
  34495. /**
  34496. * A reference to the current XR session.
  34497. *
  34498. * @private
  34499. * @type {?XRSession}
  34500. * @default null
  34501. */
  34502. this._session = null;
  34503. /**
  34504. * A reference to the current XR base layer.
  34505. *
  34506. * @private
  34507. * @type {?XRWebGLLayer}
  34508. * @default null
  34509. */
  34510. this._glBaseLayer = null;
  34511. /**
  34512. * A reference to the current XR binding.
  34513. *
  34514. * @private
  34515. * @type {?XRWebGLBinding}
  34516. * @default null
  34517. */
  34518. this._glBinding = null;
  34519. /**
  34520. * A reference to the current XR projection layer.
  34521. *
  34522. * @private
  34523. * @type {?XRProjectionLayer}
  34524. * @default null
  34525. */
  34526. this._glProjLayer = null;
  34527. /**
  34528. * A reference to the current XR frame.
  34529. *
  34530. * @private
  34531. * @type {?XRFrame}
  34532. * @default null
  34533. */
  34534. this._xrFrame = null;
  34535. /**
  34536. * Whether to use the WebXR Layers API or not.
  34537. *
  34538. * @private
  34539. * @type {boolean}
  34540. * @readonly
  34541. */
  34542. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  34543. }
  34544. /**
  34545. * Returns an instance of `THREE.Group` that represents the transformation
  34546. * of a XR controller in target ray space. The requested controller is defined
  34547. * by the given index.
  34548. *
  34549. * @param {number} index - The index of the XR controller.
  34550. * @return {Group} A group that represents the controller's transformation.
  34551. */
  34552. getController( index ) {
  34553. const controller = this._getController( index );
  34554. return controller.getTargetRaySpace();
  34555. }
  34556. /**
  34557. * Returns an instance of `THREE.Group` that represents the transformation
  34558. * of a XR controller in grip space. The requested controller is defined
  34559. * by the given index.
  34560. *
  34561. * @param {number} index - The index of the XR controller.
  34562. * @return {Group} A group that represents the controller's transformation.
  34563. */
  34564. getControllerGrip( index ) {
  34565. const controller = this._getController( index );
  34566. return controller.getGripSpace();
  34567. }
  34568. /**
  34569. * Returns an instance of `THREE.Group` that represents the transformation
  34570. * of a XR controller in hand space. The requested controller is defined
  34571. * by the given index.
  34572. *
  34573. * @param {number} index - The index of the XR controller.
  34574. * @return {Group} A group that represents the controller's transformation.
  34575. */
  34576. getHand( index ) {
  34577. const controller = this._getController( index );
  34578. return controller.getHandSpace();
  34579. }
  34580. /**
  34581. * Returns the foveation value.
  34582. *
  34583. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  34584. */
  34585. getFoveation() {
  34586. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  34587. return undefined;
  34588. }
  34589. return this._foveation;
  34590. }
  34591. /**
  34592. * Sets the foveation value.
  34593. *
  34594. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  34595. * and `1` means maximum foveation (the edges render at lower resolution).
  34596. */
  34597. setFoveation( foveation ) {
  34598. this._foveation = foveation;
  34599. if ( this._glProjLayer !== null ) {
  34600. this._glProjLayer.fixedFoveation = foveation;
  34601. }
  34602. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  34603. this._glBaseLayer.fixedFoveation = foveation;
  34604. }
  34605. }
  34606. /**
  34607. * Returns the framebuffer scale factor.
  34608. *
  34609. * @return {number} The framebuffer scale factor.
  34610. */
  34611. getFramebufferScaleFactor() {
  34612. return this._framebufferScaleFactor;
  34613. }
  34614. /**
  34615. * Sets the framebuffer scale factor.
  34616. *
  34617. * This method can not be used during a XR session.
  34618. *
  34619. * @param {number} factor - The framebuffer scale factor.
  34620. */
  34621. setFramebufferScaleFactor( factor ) {
  34622. this._framebufferScaleFactor = factor;
  34623. if ( this.isPresenting === true ) {
  34624. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  34625. }
  34626. }
  34627. /**
  34628. * Returns the reference space type.
  34629. *
  34630. * @return {XRReferenceSpaceType} The reference space type.
  34631. */
  34632. getReferenceSpaceType() {
  34633. return this._referenceSpaceType;
  34634. }
  34635. /**
  34636. * Sets the reference space type.
  34637. *
  34638. * This method can not be used during a XR session.
  34639. *
  34640. * @param {XRReferenceSpaceType} type - The reference space type.
  34641. */
  34642. setReferenceSpaceType( type ) {
  34643. this._referenceSpaceType = type;
  34644. if ( this.isPresenting === true ) {
  34645. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  34646. }
  34647. }
  34648. /**
  34649. * Returns the XR reference space.
  34650. *
  34651. * @return {XRReferenceSpace} The XR reference space.
  34652. */
  34653. getReferenceSpace() {
  34654. return this._customReferenceSpace || this._referenceSpace;
  34655. }
  34656. /**
  34657. * Sets a custom XR reference space.
  34658. *
  34659. * @param {XRReferenceSpace} space - The XR reference space.
  34660. */
  34661. setReferenceSpace( space ) {
  34662. this._customReferenceSpace = space;
  34663. }
  34664. /**
  34665. * Returns the XR camera.
  34666. *
  34667. * @return {ArrayCamera} The XR camera.
  34668. */
  34669. getCamera() {
  34670. return this._cameraXR;
  34671. }
  34672. /**
  34673. * Returns the environment blend mode from the current XR session.
  34674. *
  34675. * @return {?('opaque'|'additive'|'alpha-blend')} The environment blend mode. Returns `null` when used outside of a XR session.
  34676. */
  34677. getEnvironmentBlendMode() {
  34678. if ( this._session !== null ) {
  34679. return this._session.environmentBlendMode;
  34680. }
  34681. }
  34682. /**
  34683. * Returns the current XR frame.
  34684. *
  34685. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  34686. */
  34687. getFrame() {
  34688. return this._xrFrame;
  34689. }
  34690. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  34691. const geometry = new PlaneGeometry( width, height );
  34692. const renderTarget = new XRRenderTarget(
  34693. pixelwidth,
  34694. pixelheight,
  34695. {
  34696. format: RGBAFormat,
  34697. type: UnsignedByteType,
  34698. depthTexture: new DepthTexture(
  34699. pixelwidth,
  34700. pixelheight,
  34701. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  34702. undefined,
  34703. undefined,
  34704. undefined,
  34705. undefined,
  34706. undefined,
  34707. undefined,
  34708. attributes.stencil ? DepthStencilFormat : DepthFormat
  34709. ),
  34710. stencilBuffer: attributes.stencil,
  34711. resolveDepthBuffer: false,
  34712. resolveStencilBuffer: false
  34713. } );
  34714. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  34715. material.map = renderTarget.texture;
  34716. material.map.offset.y = 1;
  34717. material.map.repeat.y = - 1;
  34718. const plane = new Mesh( geometry, material );
  34719. plane.position.copy( translation );
  34720. plane.quaternion.copy( quaternion );
  34721. const layer = {
  34722. type: 'quad',
  34723. width: width,
  34724. height: height,
  34725. translation: translation,
  34726. quaternion: quaternion,
  34727. pixelwidth: pixelwidth,
  34728. pixelheight: pixelheight,
  34729. plane: plane,
  34730. material: material,
  34731. rendercall: rendercall,
  34732. renderTarget: renderTarget };
  34733. this._layers.push( layer );
  34734. if ( this._session !== null ) {
  34735. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  34736. layer.plane.material.blending = CustomBlending;
  34737. layer.plane.material.blendEquation = AddEquation;
  34738. layer.plane.material.blendSrc = ZeroFactor;
  34739. layer.plane.material.blendDst = ZeroFactor;
  34740. layer.xrlayer = this._createXRLayer( layer );
  34741. const xrlayers = this._session.renderState.layers;
  34742. xrlayers.unshift( layer.xrlayer );
  34743. this._session.updateRenderState( { layers: xrlayers } );
  34744. } else {
  34745. renderTarget.isXRRenderTarget = false;
  34746. }
  34747. return plane;
  34748. }
  34749. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  34750. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  34751. const renderTarget = new XRRenderTarget(
  34752. pixelwidth,
  34753. pixelheight,
  34754. {
  34755. format: RGBAFormat,
  34756. type: UnsignedByteType,
  34757. depthTexture: new DepthTexture(
  34758. pixelwidth,
  34759. pixelheight,
  34760. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  34761. undefined,
  34762. undefined,
  34763. undefined,
  34764. undefined,
  34765. undefined,
  34766. undefined,
  34767. attributes.stencil ? DepthStencilFormat : DepthFormat
  34768. ),
  34769. stencilBuffer: attributes.stencil,
  34770. resolveDepthBuffer: false,
  34771. resolveStencilBuffer: false
  34772. } );
  34773. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  34774. material.map = renderTarget.texture;
  34775. material.map.offset.y = 1;
  34776. material.map.repeat.y = - 1;
  34777. const plane = new Mesh( geometry, material );
  34778. plane.position.copy( translation );
  34779. plane.quaternion.copy( quaternion );
  34780. const layer = {
  34781. type: 'cylinder',
  34782. radius: radius,
  34783. centralAngle: centralAngle,
  34784. aspectratio: aspectratio,
  34785. translation: translation,
  34786. quaternion: quaternion,
  34787. pixelwidth: pixelwidth,
  34788. pixelheight: pixelheight,
  34789. plane: plane,
  34790. material: material,
  34791. rendercall: rendercall,
  34792. renderTarget: renderTarget };
  34793. this._layers.push( layer );
  34794. if ( this._session !== null ) {
  34795. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  34796. layer.plane.material.blending = CustomBlending;
  34797. layer.plane.material.blendEquation = AddEquation;
  34798. layer.plane.material.blendSrc = ZeroFactor;
  34799. layer.plane.material.blendDst = ZeroFactor;
  34800. layer.xrlayer = this._createXRLayer( layer );
  34801. const xrlayers = this._session.renderState.layers;
  34802. xrlayers.unshift( layer.xrlayer );
  34803. this._session.updateRenderState( { layers: xrlayers } );
  34804. } else {
  34805. renderTarget.isXRRenderTarget = false;
  34806. }
  34807. return plane;
  34808. }
  34809. renderLayers( ) {
  34810. const translationObject = new Vector3();
  34811. const quaternionObject = new Quaternion();
  34812. const wasPresenting = this.isPresenting;
  34813. this.isPresenting = false;
  34814. for ( const layer of this._layers ) {
  34815. layer.renderTarget.isXRRenderTarget = this._session !== null;
  34816. layer.renderTarget.hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  34817. layer.renderTarget.autoAllocateDepthBuffer = ! layer.renderTarget.isXRRenderTarget;
  34818. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  34819. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  34820. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  34821. this._renderer.backend.setXRRenderTargetTextures(
  34822. layer.renderTarget,
  34823. glSubImage.colorTexture,
  34824. glSubImage.depthStencilTexture );
  34825. }
  34826. this._renderer.setRenderTarget( layer.renderTarget );
  34827. layer.rendercall();
  34828. }
  34829. this.isPresenting = wasPresenting;
  34830. this._renderer.setRenderTarget( null );
  34831. }
  34832. /**
  34833. * Returns the current XR session.
  34834. *
  34835. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  34836. */
  34837. getSession() {
  34838. return this._session;
  34839. }
  34840. /**
  34841. * After a XR session has been requested usually with one of the `*Button` modules, it
  34842. * is injected into the renderer with this method. This method triggers the start of
  34843. * the actual XR rendering.
  34844. *
  34845. * @async
  34846. * @param {XRSession} session - The XR session to set.
  34847. * @return {Promise} A Promise that resolves when the session has been set.
  34848. */
  34849. async setSession( session ) {
  34850. const renderer = this._renderer;
  34851. const backend = renderer.backend;
  34852. this._gl = renderer.getContext();
  34853. const gl = this._gl;
  34854. const attributes = gl.getContextAttributes();
  34855. this._session = session;
  34856. if ( session !== null ) {
  34857. 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.' );
  34858. session.addEventListener( 'select', this._onSessionEvent );
  34859. session.addEventListener( 'selectstart', this._onSessionEvent );
  34860. session.addEventListener( 'selectend', this._onSessionEvent );
  34861. session.addEventListener( 'squeeze', this._onSessionEvent );
  34862. session.addEventListener( 'squeezestart', this._onSessionEvent );
  34863. session.addEventListener( 'squeezeend', this._onSessionEvent );
  34864. session.addEventListener( 'end', this._onSessionEnd );
  34865. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34866. await backend.makeXRCompatible();
  34867. this._currentPixelRatio = renderer.getPixelRatio();
  34868. renderer.getSize( this._currentSize );
  34869. this._currentAnimationContext = renderer._animation.getContext();
  34870. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  34871. renderer._animation.stop();
  34872. //
  34873. if ( this._useLayers === true ) {
  34874. // default path using XRWebGLBinding/XRProjectionLayer
  34875. let depthFormat = null;
  34876. let depthType = null;
  34877. let glDepthFormat = null;
  34878. if ( renderer.depth ) {
  34879. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  34880. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  34881. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  34882. }
  34883. const projectionlayerInit = {
  34884. colorFormat: gl.RGBA8,
  34885. depthFormat: glDepthFormat,
  34886. scaleFactor: this._framebufferScaleFactor
  34887. };
  34888. const glBinding = new XRWebGLBinding( session, gl );
  34889. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  34890. const layersArray = [ glProjLayer ];
  34891. this._glBinding = glBinding;
  34892. this._glProjLayer = glProjLayer;
  34893. renderer.setPixelRatio( 1 );
  34894. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  34895. this._xrRenderTarget = new XRRenderTarget(
  34896. glProjLayer.textureWidth,
  34897. glProjLayer.textureHeight,
  34898. {
  34899. format: RGBAFormat,
  34900. type: UnsignedByteType,
  34901. colorSpace: renderer.outputColorSpace,
  34902. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  34903. stencilBuffer: renderer.stencil,
  34904. samples: attributes.antialias ? 4 : 0,
  34905. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  34906. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  34907. } );
  34908. this._xrRenderTarget.hasExternalTextures = true;
  34909. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  34910. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  34911. if ( this._supportsLayers ) {
  34912. // switch layers to native
  34913. for ( const layer of this._layers ) {
  34914. // change material so it "punches" out a hole to show the XR Layer.
  34915. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  34916. layer.plane.material.blending = CustomBlending;
  34917. layer.plane.material.blendEquation = AddEquation;
  34918. layer.plane.material.blendSrc = ZeroFactor;
  34919. layer.plane.material.blendDst = ZeroFactor;
  34920. layer.xrlayer = this._createXRLayer( layer );
  34921. layersArray.unshift( layer.xrlayer );
  34922. }
  34923. }
  34924. session.updateRenderState( { layers: layersArray } );
  34925. } else {
  34926. // fallback to XRWebGLLayer
  34927. const layerInit = {
  34928. antialias: renderer.samples > 0,
  34929. alpha: true,
  34930. depth: renderer.depth,
  34931. stencil: renderer.stencil,
  34932. framebufferScaleFactor: this.getFramebufferScaleFactor()
  34933. };
  34934. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  34935. this._glBaseLayer = glBaseLayer;
  34936. session.updateRenderState( { baseLayer: glBaseLayer } );
  34937. renderer.setPixelRatio( 1 );
  34938. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  34939. this._xrRenderTarget = new XRRenderTarget(
  34940. glBaseLayer.framebufferWidth,
  34941. glBaseLayer.framebufferHeight,
  34942. {
  34943. format: RGBAFormat,
  34944. type: UnsignedByteType,
  34945. colorSpace: renderer.outputColorSpace,
  34946. stencilBuffer: renderer.stencil,
  34947. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  34948. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  34949. }
  34950. );
  34951. }
  34952. //
  34953. this.setFoveation( this.getFoveation() );
  34954. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  34955. renderer._animation.setContext( session );
  34956. renderer._animation.start();
  34957. this.isPresenting = true;
  34958. this.dispatchEvent( { type: 'sessionstart' } );
  34959. }
  34960. }
  34961. /**
  34962. * This method is called by the renderer per frame and updates the XR camera
  34963. * and it sub cameras based on the given camera. The given camera is the "user"
  34964. * camera created on application level and used for non-XR rendering.
  34965. *
  34966. * @param {PerspectiveCamera} camera - The camera.
  34967. */
  34968. updateCamera( camera ) {
  34969. const session = this._session;
  34970. if ( session === null ) return;
  34971. const depthNear = camera.near;
  34972. const depthFar = camera.far;
  34973. const cameraXR = this._cameraXR;
  34974. const cameraL = this._cameraL;
  34975. const cameraR = this._cameraR;
  34976. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  34977. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  34978. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  34979. // Note that the new renderState won't apply until the next frame. See #18320
  34980. session.updateRenderState( {
  34981. depthNear: cameraXR.near,
  34982. depthFar: cameraXR.far
  34983. } );
  34984. this._currentDepthNear = cameraXR.near;
  34985. this._currentDepthFar = cameraXR.far;
  34986. }
  34987. cameraL.layers.mask = camera.layers.mask | 0b010;
  34988. cameraR.layers.mask = camera.layers.mask | 0b100;
  34989. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  34990. const parent = camera.parent;
  34991. const cameras = cameraXR.cameras;
  34992. updateCamera( cameraXR, parent );
  34993. for ( let i = 0; i < cameras.length; i ++ ) {
  34994. updateCamera( cameras[ i ], parent );
  34995. }
  34996. // update projection matrix for proper view frustum culling
  34997. if ( cameras.length === 2 ) {
  34998. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  34999. } else {
  35000. // assume single camera setup (AR)
  35001. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  35002. }
  35003. // update user camera and its children
  35004. updateUserCamera( camera, cameraXR, parent );
  35005. }
  35006. /**
  35007. * Returns a WebXR controller for the given controller index.
  35008. *
  35009. * @private
  35010. * @param {number} index - The controller index.
  35011. * @return {WebXRController} The XR controller.
  35012. */
  35013. _getController( index ) {
  35014. let controller = this._controllers[ index ];
  35015. if ( controller === undefined ) {
  35016. controller = new WebXRController();
  35017. this._controllers[ index ] = controller;
  35018. }
  35019. return controller;
  35020. }
  35021. }
  35022. /**
  35023. * Assumes 2 cameras that are parallel and share an X-axis, and that
  35024. * the cameras' projection and world matrices have already been set.
  35025. * And that near and far planes are identical for both cameras.
  35026. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  35027. *
  35028. * @param {ArrayCamera} camera - The camera to update.
  35029. * @param {PerspectiveCamera} cameraL - The left camera.
  35030. * @param {PerspectiveCamera} cameraR - The right camera.
  35031. */
  35032. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  35033. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  35034. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  35035. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  35036. const projL = cameraL.projectionMatrix.elements;
  35037. const projR = cameraR.projectionMatrix.elements;
  35038. // VR systems will have identical far and near planes, and
  35039. // most likely identical top and bottom frustum extents.
  35040. // Use the left camera for these values.
  35041. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  35042. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  35043. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  35044. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  35045. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  35046. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  35047. const left = near * leftFov;
  35048. const right = near * rightFov;
  35049. // Calculate the new camera's position offset from the
  35050. // left camera. xOffset should be roughly half `ipd`.
  35051. const zOffset = ipd / ( - leftFov + rightFov );
  35052. const xOffset = zOffset * - leftFov;
  35053. // TODO: Better way to apply this offset?
  35054. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  35055. camera.translateX( xOffset );
  35056. camera.translateZ( zOffset );
  35057. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  35058. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35059. // Check if the projection uses an infinite far plane.
  35060. if ( projL[ 10 ] === - 1.0 ) {
  35061. // Use the projection matrix from the left eye.
  35062. // The camera offset is sufficient to include the view volumes
  35063. // of both eyes (assuming symmetric projections).
  35064. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  35065. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  35066. } else {
  35067. // Find the union of the frustum values of the cameras and scale
  35068. // the values so that the near plane's position does not change in world space,
  35069. // although must now be relative to the new union camera.
  35070. const near2 = near + zOffset;
  35071. const far2 = far + zOffset;
  35072. const left2 = left - xOffset;
  35073. const right2 = right + ( ipd - xOffset );
  35074. const top2 = topFov * far / far2 * near2;
  35075. const bottom2 = bottomFov * far / far2 * near2;
  35076. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  35077. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  35078. }
  35079. }
  35080. /**
  35081. * Updates the world matrices for the given camera based on the parent 3D object.
  35082. *
  35083. * @inner
  35084. * @param {Camera} camera - The camera to update.
  35085. * @param {Object3D} parent - The parent 3D object.
  35086. */
  35087. function updateCamera( camera, parent ) {
  35088. if ( parent === null ) {
  35089. camera.matrixWorld.copy( camera.matrix );
  35090. } else {
  35091. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  35092. }
  35093. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35094. }
  35095. /**
  35096. * Updates the given camera with the transformation of the XR camera and parent object.
  35097. *
  35098. * @inner
  35099. * @param {Camera} camera - The camera to update.
  35100. * @param {ArrayCamera} cameraXR - The XR camera.
  35101. * @param {Object3D} parent - The parent 3D object.
  35102. */
  35103. function updateUserCamera( camera, cameraXR, parent ) {
  35104. if ( parent === null ) {
  35105. camera.matrix.copy( cameraXR.matrixWorld );
  35106. } else {
  35107. camera.matrix.copy( parent.matrixWorld );
  35108. camera.matrix.invert();
  35109. camera.matrix.multiply( cameraXR.matrixWorld );
  35110. }
  35111. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  35112. camera.updateMatrixWorld( true );
  35113. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  35114. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  35115. if ( camera.isPerspectiveCamera ) {
  35116. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  35117. camera.zoom = 1;
  35118. }
  35119. }
  35120. function onSessionEvent( event ) {
  35121. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  35122. if ( controllerIndex === - 1 ) {
  35123. return;
  35124. }
  35125. const controller = this._controllers[ controllerIndex ];
  35126. if ( controller !== undefined ) {
  35127. const referenceSpace = this.getReferenceSpace();
  35128. controller.update( event.inputSource, event.frame, referenceSpace );
  35129. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  35130. }
  35131. }
  35132. function onSessionEnd() {
  35133. const session = this._session;
  35134. const renderer = this._renderer;
  35135. session.removeEventListener( 'select', this._onSessionEvent );
  35136. session.removeEventListener( 'selectstart', this._onSessionEvent );
  35137. session.removeEventListener( 'selectend', this._onSessionEvent );
  35138. session.removeEventListener( 'squeeze', this._onSessionEvent );
  35139. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  35140. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  35141. session.removeEventListener( 'end', this._onSessionEnd );
  35142. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  35143. for ( let i = 0; i < this._controllers.length; i ++ ) {
  35144. const inputSource = this._controllerInputSources[ i ];
  35145. if ( inputSource === null ) continue;
  35146. this._controllerInputSources[ i ] = null;
  35147. this._controllers[ i ].disconnect( inputSource );
  35148. }
  35149. this._currentDepthNear = null;
  35150. this._currentDepthFar = null;
  35151. // restore framebuffer/rendering state
  35152. renderer.backend.setXRTarget( null );
  35153. renderer.setOutputRenderTarget( null );
  35154. renderer.setRenderTarget( null );
  35155. this._session = null;
  35156. this._xrRenderTarget = null;
  35157. // switch layers back to emulated
  35158. if ( this._supportsLayers === true ) {
  35159. for ( const layer of this._layers ) {
  35160. // Recreate layer render target to reset state
  35161. layer.renderTarget = new XRRenderTarget(
  35162. layer.pixelwidth,
  35163. layer.pixelheight,
  35164. {
  35165. format: RGBAFormat,
  35166. type: UnsignedByteType,
  35167. depthTexture: new DepthTexture(
  35168. layer.pixelwidth,
  35169. layer.pixelheight,
  35170. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  35171. undefined,
  35172. undefined,
  35173. undefined,
  35174. undefined,
  35175. undefined,
  35176. undefined,
  35177. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  35178. ),
  35179. stencilBuffer: layer.stencilBuffer,
  35180. resolveDepthBuffer: false,
  35181. resolveStencilBuffer: false
  35182. } );
  35183. layer.renderTarget.isXRRenderTarget = false;
  35184. layer.plane.material = layer.material;
  35185. layer.material.map = layer.renderTarget.texture;
  35186. delete layer.xrlayer;
  35187. }
  35188. }
  35189. //
  35190. this.isPresenting = false;
  35191. renderer._animation.stop();
  35192. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  35193. renderer._animation.setContext( this._currentAnimationContext );
  35194. renderer._animation.start();
  35195. renderer.setPixelRatio( this._currentPixelRatio );
  35196. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  35197. this.dispatchEvent( { type: 'sessionend' } );
  35198. }
  35199. function onInputSourcesChange( event ) {
  35200. const controllers = this._controllers;
  35201. const controllerInputSources = this._controllerInputSources;
  35202. // Notify disconnected
  35203. for ( let i = 0; i < event.removed.length; i ++ ) {
  35204. const inputSource = event.removed[ i ];
  35205. const index = controllerInputSources.indexOf( inputSource );
  35206. if ( index >= 0 ) {
  35207. controllerInputSources[ index ] = null;
  35208. controllers[ index ].disconnect( inputSource );
  35209. }
  35210. }
  35211. // Notify connected
  35212. for ( let i = 0; i < event.added.length; i ++ ) {
  35213. const inputSource = event.added[ i ];
  35214. let controllerIndex = controllerInputSources.indexOf( inputSource );
  35215. if ( controllerIndex === - 1 ) {
  35216. // Assign input source a controller that currently has no input source
  35217. for ( let i = 0; i < controllers.length; i ++ ) {
  35218. if ( i >= controllerInputSources.length ) {
  35219. controllerInputSources.push( inputSource );
  35220. controllerIndex = i;
  35221. break;
  35222. } else if ( controllerInputSources[ i ] === null ) {
  35223. controllerInputSources[ i ] = inputSource;
  35224. controllerIndex = i;
  35225. break;
  35226. }
  35227. }
  35228. // If all controllers do currently receive input we ignore new ones
  35229. if ( controllerIndex === - 1 ) break;
  35230. }
  35231. const controller = controllers[ controllerIndex ];
  35232. if ( controller ) {
  35233. controller.connect( inputSource );
  35234. }
  35235. }
  35236. }
  35237. // Creation method for native WebXR layers
  35238. function createXRLayer( layer ) {
  35239. if ( layer.type === 'quad' ) {
  35240. return this._glBinding.createQuadLayer( {
  35241. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  35242. depthFormat: this._gl.DEPTH_COMPONENT,
  35243. width: layer.width / 2,
  35244. height: layer.height / 2,
  35245. space: this._referenceSpace,
  35246. viewPixelWidth: layer.pixelwidth,
  35247. viewPixelHeight: layer.pixelheight
  35248. } );
  35249. } else {
  35250. return this._glBinding.createCylinderLayer( {
  35251. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  35252. depthFormat: this._gl.DEPTH_COMPONENT,
  35253. radius: layer.radius,
  35254. centralAngle: layer.centralAngle,
  35255. aspectRatio: layer.aspectRatio,
  35256. space: this._referenceSpace,
  35257. viewPixelWidth: layer.pixelwidth,
  35258. viewPixelHeight: layer.pixelheight
  35259. } );
  35260. }
  35261. }
  35262. // Animation Loop
  35263. function onAnimationFrame( time, frame ) {
  35264. if ( frame === undefined ) return;
  35265. const cameraXR = this._cameraXR;
  35266. const renderer = this._renderer;
  35267. const backend = renderer.backend;
  35268. const glBaseLayer = this._glBaseLayer;
  35269. const referenceSpace = this.getReferenceSpace();
  35270. const pose = frame.getViewerPose( referenceSpace );
  35271. this._xrFrame = frame;
  35272. if ( pose !== null ) {
  35273. const views = pose.views;
  35274. if ( this._glBaseLayer !== null ) {
  35275. backend.setXRTarget( glBaseLayer.framebuffer );
  35276. }
  35277. let cameraXRNeedsUpdate = false;
  35278. // check if it's necessary to rebuild cameraXR's camera list
  35279. if ( views.length !== cameraXR.cameras.length ) {
  35280. cameraXR.cameras.length = 0;
  35281. cameraXRNeedsUpdate = true;
  35282. }
  35283. for ( let i = 0; i < views.length; i ++ ) {
  35284. const view = views[ i ];
  35285. let viewport;
  35286. if ( this._useLayers === true ) {
  35287. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  35288. viewport = glSubImage.viewport;
  35289. // For side-by-side projection, we only produce a single texture for both eyes.
  35290. if ( i === 0 ) {
  35291. backend.setXRRenderTargetTextures(
  35292. this._xrRenderTarget,
  35293. glSubImage.colorTexture,
  35294. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  35295. );
  35296. }
  35297. } else {
  35298. viewport = glBaseLayer.getViewport( view );
  35299. }
  35300. let camera = this._cameras[ i ];
  35301. if ( camera === undefined ) {
  35302. camera = new PerspectiveCamera();
  35303. camera.layers.enable( i );
  35304. camera.viewport = new Vector4();
  35305. this._cameras[ i ] = camera;
  35306. }
  35307. camera.matrix.fromArray( view.transform.matrix );
  35308. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  35309. camera.projectionMatrix.fromArray( view.projectionMatrix );
  35310. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  35311. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  35312. if ( i === 0 ) {
  35313. cameraXR.matrix.copy( camera.matrix );
  35314. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  35315. }
  35316. if ( cameraXRNeedsUpdate === true ) {
  35317. cameraXR.cameras.push( camera );
  35318. }
  35319. }
  35320. renderer.setOutputRenderTarget( this._xrRenderTarget );
  35321. }
  35322. //
  35323. for ( let i = 0; i < this._controllers.length; i ++ ) {
  35324. const inputSource = this._controllerInputSources[ i ];
  35325. const controller = this._controllers[ i ];
  35326. if ( inputSource !== null && controller !== undefined ) {
  35327. controller.update( inputSource, frame, referenceSpace );
  35328. }
  35329. }
  35330. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  35331. if ( frame.detectedPlanes ) {
  35332. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  35333. }
  35334. this._xrFrame = null;
  35335. }
  35336. const _scene = /*@__PURE__*/ new Scene();
  35337. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  35338. const _screen = /*@__PURE__*/ new Vector4();
  35339. const _frustum = /*@__PURE__*/ new Frustum();
  35340. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  35341. const _vector4 = /*@__PURE__*/ new Vector4();
  35342. /**
  35343. * Base class for renderers.
  35344. */
  35345. class Renderer {
  35346. /**
  35347. * Renderer options.
  35348. *
  35349. * @typedef {Object} Renderer~Options
  35350. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  35351. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  35352. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  35353. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  35354. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  35355. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  35356. * to overwrite the default.
  35357. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  35358. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  35359. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  35360. */
  35361. /**
  35362. * Constructs a new renderer.
  35363. *
  35364. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  35365. * @param {Renderer~Options} [parameters] - The configuration parameter.
  35366. */
  35367. constructor( backend, parameters = {} ) {
  35368. /**
  35369. * This flag can be used for type testing.
  35370. *
  35371. * @type {boolean}
  35372. * @readonly
  35373. * @default true
  35374. */
  35375. this.isRenderer = true;
  35376. //
  35377. const {
  35378. logarithmicDepthBuffer = false,
  35379. alpha = true,
  35380. depth = true,
  35381. stencil = false,
  35382. antialias = false,
  35383. samples = 0,
  35384. getFallback = null,
  35385. colorBufferType = HalfFloatType
  35386. } = parameters;
  35387. /**
  35388. * A reference to the canvas element the renderer is drawing to.
  35389. * This value of this property will automatically be created by
  35390. * the renderer.
  35391. *
  35392. * @type {HTMLCanvasElement|OffscreenCanvas}
  35393. */
  35394. this.domElement = backend.getDomElement();
  35395. /**
  35396. * A reference to the current backend.
  35397. *
  35398. * @type {Backend}
  35399. */
  35400. this.backend = backend;
  35401. /**
  35402. * The number of MSAA samples.
  35403. *
  35404. * @type {number}
  35405. * @default 0
  35406. */
  35407. this.samples = samples || ( antialias === true ) ? 4 : 0;
  35408. /**
  35409. * Whether the renderer should automatically clear the current rendering target
  35410. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  35411. * or the current bound render target (custom framebuffer).
  35412. *
  35413. * @type {boolean}
  35414. * @default true
  35415. */
  35416. this.autoClear = true;
  35417. /**
  35418. * When `autoClear` is set to `true`, this property defines whether the renderer
  35419. * should clear the color buffer.
  35420. *
  35421. * @type {boolean}
  35422. * @default true
  35423. */
  35424. this.autoClearColor = true;
  35425. /**
  35426. * When `autoClear` is set to `true`, this property defines whether the renderer
  35427. * should clear the depth buffer.
  35428. *
  35429. * @type {boolean}
  35430. * @default true
  35431. */
  35432. this.autoClearDepth = true;
  35433. /**
  35434. * When `autoClear` is set to `true`, this property defines whether the renderer
  35435. * should clear the stencil buffer.
  35436. *
  35437. * @type {boolean}
  35438. * @default true
  35439. */
  35440. this.autoClearStencil = true;
  35441. /**
  35442. * Whether the default framebuffer should be transparent or opaque.
  35443. *
  35444. * @type {boolean}
  35445. * @default true
  35446. */
  35447. this.alpha = alpha;
  35448. /**
  35449. * Whether logarithmic depth buffer is enabled or not.
  35450. *
  35451. * @type {boolean}
  35452. * @default false
  35453. */
  35454. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  35455. /**
  35456. * Defines the output color space of the renderer.
  35457. *
  35458. * @type {string}
  35459. * @default SRGBColorSpace
  35460. */
  35461. this.outputColorSpace = SRGBColorSpace;
  35462. /**
  35463. * Defines the tone mapping of the renderer.
  35464. *
  35465. * @type {number}
  35466. * @default NoToneMapping
  35467. */
  35468. this.toneMapping = NoToneMapping;
  35469. /**
  35470. * Defines the tone mapping exposure.
  35471. *
  35472. * @type {number}
  35473. * @default 1
  35474. */
  35475. this.toneMappingExposure = 1.0;
  35476. /**
  35477. * Whether the renderer should sort its render lists or not.
  35478. *
  35479. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  35480. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  35481. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  35482. * e.g. manually determining each object's rendering order.
  35483. *
  35484. * @type {boolean}
  35485. * @default true
  35486. */
  35487. this.sortObjects = true;
  35488. /**
  35489. * Whether the default framebuffer should have a depth buffer or not.
  35490. *
  35491. * @type {boolean}
  35492. * @default true
  35493. */
  35494. this.depth = depth;
  35495. /**
  35496. * Whether the default framebuffer should have a stencil buffer or not.
  35497. *
  35498. * @type {boolean}
  35499. * @default false
  35500. */
  35501. this.stencil = stencil;
  35502. /**
  35503. * Holds a series of statistical information about the GPU memory
  35504. * and the rendering process. Useful for debugging and monitoring.
  35505. *
  35506. * @type {Info}
  35507. */
  35508. this.info = new Info();
  35509. this.nodes = {
  35510. modelViewMatrix: null,
  35511. modelNormalViewMatrix: null
  35512. };
  35513. /**
  35514. * The node library defines how certain library objects like materials, lights
  35515. * or tone mapping functions are mapped to node types. This is required since
  35516. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  35517. * be part of the scene graph, they are internally represented as nodes for
  35518. * further processing.
  35519. *
  35520. * @type {NodeLibrary}
  35521. */
  35522. this.library = new NodeLibrary();
  35523. /**
  35524. * A map-like data structure for managing lights.
  35525. *
  35526. * @type {Lighting}
  35527. */
  35528. this.lighting = new Lighting();
  35529. // internals
  35530. /**
  35531. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  35532. *
  35533. * @private
  35534. * @type {?Function}
  35535. */
  35536. this._getFallback = getFallback;
  35537. /**
  35538. * The renderer's pixel ratio.
  35539. *
  35540. * @private
  35541. * @type {number}
  35542. * @default 1
  35543. */
  35544. this._pixelRatio = 1;
  35545. /**
  35546. * The width of the renderer's default framebuffer in logical pixel unit.
  35547. *
  35548. * @private
  35549. * @type {number}
  35550. */
  35551. this._width = this.domElement.width;
  35552. /**
  35553. * The height of the renderer's default framebuffer in logical pixel unit.
  35554. *
  35555. * @private
  35556. * @type {number}
  35557. */
  35558. this._height = this.domElement.height;
  35559. /**
  35560. * The viewport of the renderer in logical pixel unit.
  35561. *
  35562. * @private
  35563. * @type {Vector4}
  35564. */
  35565. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35566. /**
  35567. * The scissor rectangle of the renderer in logical pixel unit.
  35568. *
  35569. * @private
  35570. * @type {Vector4}
  35571. */
  35572. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35573. /**
  35574. * Whether the scissor test should be enabled or not.
  35575. *
  35576. * @private
  35577. * @type {boolean}
  35578. */
  35579. this._scissorTest = false;
  35580. /**
  35581. * A reference to a renderer module for managing shader attributes.
  35582. *
  35583. * @private
  35584. * @type {?Attributes}
  35585. * @default null
  35586. */
  35587. this._attributes = null;
  35588. /**
  35589. * A reference to a renderer module for managing geometries.
  35590. *
  35591. * @private
  35592. * @type {?Geometries}
  35593. * @default null
  35594. */
  35595. this._geometries = null;
  35596. /**
  35597. * A reference to a renderer module for managing node related logic.
  35598. *
  35599. * @private
  35600. * @type {?Nodes}
  35601. * @default null
  35602. */
  35603. this._nodes = null;
  35604. /**
  35605. * A reference to a renderer module for managing the internal animation loop.
  35606. *
  35607. * @private
  35608. * @type {?Animation}
  35609. * @default null
  35610. */
  35611. this._animation = null;
  35612. /**
  35613. * A reference to a renderer module for managing shader program bindings.
  35614. *
  35615. * @private
  35616. * @type {?Bindings}
  35617. * @default null
  35618. */
  35619. this._bindings = null;
  35620. /**
  35621. * A reference to a renderer module for managing render objects.
  35622. *
  35623. * @private
  35624. * @type {?RenderObjects}
  35625. * @default null
  35626. */
  35627. this._objects = null;
  35628. /**
  35629. * A reference to a renderer module for managing render and compute pipelines.
  35630. *
  35631. * @private
  35632. * @type {?Pipelines}
  35633. * @default null
  35634. */
  35635. this._pipelines = null;
  35636. /**
  35637. * A reference to a renderer module for managing render bundles.
  35638. *
  35639. * @private
  35640. * @type {?RenderBundles}
  35641. * @default null
  35642. */
  35643. this._bundles = null;
  35644. /**
  35645. * A reference to a renderer module for managing render lists.
  35646. *
  35647. * @private
  35648. * @type {?RenderLists}
  35649. * @default null
  35650. */
  35651. this._renderLists = null;
  35652. /**
  35653. * A reference to a renderer module for managing render contexts.
  35654. *
  35655. * @private
  35656. * @type {?RenderContexts}
  35657. * @default null
  35658. */
  35659. this._renderContexts = null;
  35660. /**
  35661. * A reference to a renderer module for managing textures.
  35662. *
  35663. * @private
  35664. * @type {?Textures}
  35665. * @default null
  35666. */
  35667. this._textures = null;
  35668. /**
  35669. * A reference to a renderer module for backgrounds.
  35670. *
  35671. * @private
  35672. * @type {?Background}
  35673. * @default null
  35674. */
  35675. this._background = null;
  35676. /**
  35677. * This fullscreen quad is used for internal render passes
  35678. * like the tone mapping and color space output pass.
  35679. *
  35680. * @private
  35681. * @type {QuadMesh}
  35682. */
  35683. this._quad = new QuadMesh( new NodeMaterial() );
  35684. this._quad.material.name = 'Renderer_output';
  35685. /**
  35686. * A reference to the current render context.
  35687. *
  35688. * @private
  35689. * @type {?RenderContext}
  35690. * @default null
  35691. */
  35692. this._currentRenderContext = null;
  35693. /**
  35694. * A custom sort function for the opaque render list.
  35695. *
  35696. * @private
  35697. * @type {?Function}
  35698. * @default null
  35699. */
  35700. this._opaqueSort = null;
  35701. /**
  35702. * A custom sort function for the transparent render list.
  35703. *
  35704. * @private
  35705. * @type {?Function}
  35706. * @default null
  35707. */
  35708. this._transparentSort = null;
  35709. /**
  35710. * The framebuffer target.
  35711. *
  35712. * @private
  35713. * @type {?RenderTarget}
  35714. * @default null
  35715. */
  35716. this._frameBufferTarget = null;
  35717. const alphaClear = this.alpha === true ? 0 : 1;
  35718. /**
  35719. * The clear color value.
  35720. *
  35721. * @private
  35722. * @type {Color4}
  35723. */
  35724. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35725. /**
  35726. * The clear depth value.
  35727. *
  35728. * @private
  35729. * @type {number}
  35730. * @default 1
  35731. */
  35732. this._clearDepth = 1;
  35733. /**
  35734. * The clear stencil value.
  35735. *
  35736. * @private
  35737. * @type {number}
  35738. * @default 0
  35739. */
  35740. this._clearStencil = 0;
  35741. /**
  35742. * The current render target.
  35743. *
  35744. * @private
  35745. * @type {?RenderTarget}
  35746. * @default null
  35747. */
  35748. this._renderTarget = null;
  35749. /**
  35750. * The active cube face.
  35751. *
  35752. * @private
  35753. * @type {number}
  35754. * @default 0
  35755. */
  35756. this._activeCubeFace = 0;
  35757. /**
  35758. * The active mipmap level.
  35759. *
  35760. * @private
  35761. * @type {number}
  35762. * @default 0
  35763. */
  35764. this._activeMipmapLevel = 0;
  35765. /**
  35766. * The current output render target.
  35767. *
  35768. * @private
  35769. * @type {?RenderTarget}
  35770. * @default null
  35771. */
  35772. this._outputRenderTarget = null;
  35773. /**
  35774. * The MRT setting.
  35775. *
  35776. * @private
  35777. * @type {?MRTNode}
  35778. * @default null
  35779. */
  35780. this._mrt = null;
  35781. /**
  35782. * This function defines how a render object is going
  35783. * to be rendered.
  35784. *
  35785. * @private
  35786. * @type {?Function}
  35787. * @default null
  35788. */
  35789. this._renderObjectFunction = null;
  35790. /**
  35791. * Used to keep track of the current render object function.
  35792. *
  35793. * @private
  35794. * @type {?Function}
  35795. * @default null
  35796. */
  35797. this._currentRenderObjectFunction = null;
  35798. /**
  35799. * Used to keep track of the current render bundle.
  35800. *
  35801. * @private
  35802. * @type {?RenderBundle}
  35803. * @default null
  35804. */
  35805. this._currentRenderBundle = null;
  35806. /**
  35807. * Next to `_renderObjectFunction()`, this function provides another hook
  35808. * for influencing the render process of a render object. It is meant for internal
  35809. * use and only relevant for `compileAsync()` right now. Instead of using
  35810. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  35811. * a different function might be used which performs no draw but just the node
  35812. * and pipeline updates.
  35813. *
  35814. * @private
  35815. * @type {?Function}
  35816. * @default null
  35817. */
  35818. this._handleObjectFunction = this._renderObjectDirect;
  35819. /**
  35820. * Indicates whether the device has been lost or not. In WebGL terms, the device
  35821. * lost is considered as a context lost. When this is set to `true`, rendering
  35822. * isn't possible anymore.
  35823. *
  35824. * @private
  35825. * @type {boolean}
  35826. * @default false
  35827. */
  35828. this._isDeviceLost = false;
  35829. /**
  35830. * A callback function that defines what should happen when a device/context lost occurs.
  35831. *
  35832. * @type {Function}
  35833. */
  35834. this.onDeviceLost = this._onDeviceLost;
  35835. /**
  35836. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  35837. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  35838. * This will reduce rendering quality though.
  35839. *
  35840. * @private
  35841. * @type {number}
  35842. * @default HalfFloatType
  35843. */
  35844. this._colorBufferType = colorBufferType;
  35845. /**
  35846. * Whether the renderer has been initialized or not.
  35847. *
  35848. * @private
  35849. * @type {boolean}
  35850. * @default false
  35851. */
  35852. this._initialized = false;
  35853. /**
  35854. * A reference to the promise which initializes the renderer.
  35855. *
  35856. * @private
  35857. * @type {?Promise<this>}
  35858. * @default null
  35859. */
  35860. this._initPromise = null;
  35861. /**
  35862. * An array of compilation promises which are used in `compileAsync()`.
  35863. *
  35864. * @private
  35865. * @type {?Array<Promise>}
  35866. * @default null
  35867. */
  35868. this._compilationPromises = null;
  35869. /**
  35870. * Whether the renderer should render transparent render objects or not.
  35871. *
  35872. * @type {boolean}
  35873. * @default true
  35874. */
  35875. this.transparent = true;
  35876. /**
  35877. * Whether the renderer should render opaque render objects or not.
  35878. *
  35879. * @type {boolean}
  35880. * @default true
  35881. */
  35882. this.opaque = true;
  35883. /**
  35884. * Shadow map configuration
  35885. * @typedef {Object} ShadowMapConfig
  35886. * @property {boolean} enabled - Whether to globally enable shadows or not.
  35887. * @property {number} type - The shadow map type.
  35888. */
  35889. /**
  35890. * The renderer's shadow configuration.
  35891. *
  35892. * @type {ShadowMapConfig}
  35893. */
  35894. this.shadowMap = {
  35895. enabled: false,
  35896. type: PCFShadowMap
  35897. };
  35898. /**
  35899. * XR configuration.
  35900. * @typedef {Object} XRConfig
  35901. * @property {boolean} enabled - Whether to globally enable XR or not.
  35902. */
  35903. /**
  35904. * The renderer's XR manager.
  35905. *
  35906. * @type {XRManager}
  35907. */
  35908. this.xr = new XRManager( this );
  35909. /**
  35910. * Debug configuration.
  35911. * @typedef {Object} DebugConfig
  35912. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  35913. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  35914. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  35915. */
  35916. /**
  35917. * The renderer's debug configuration.
  35918. *
  35919. * @type {DebugConfig}
  35920. */
  35921. this.debug = {
  35922. checkShaderErrors: true,
  35923. onShaderError: null,
  35924. getShaderAsync: async ( scene, camera, object ) => {
  35925. await this.compileAsync( scene, camera );
  35926. const renderList = this._renderLists.get( scene, camera );
  35927. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  35928. const material = scene.overrideMaterial || object.material;
  35929. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  35930. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  35931. return { fragmentShader, vertexShader };
  35932. }
  35933. };
  35934. }
  35935. /**
  35936. * Initializes the renderer so it is ready for usage.
  35937. *
  35938. * @async
  35939. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  35940. */
  35941. async init() {
  35942. if ( this._initialized ) {
  35943. throw new Error( 'Renderer: Backend has already been initialized.' );
  35944. }
  35945. if ( this._initPromise !== null ) {
  35946. return this._initPromise;
  35947. }
  35948. this._initPromise = new Promise( async ( resolve, reject ) => {
  35949. let backend = this.backend;
  35950. try {
  35951. await backend.init( this );
  35952. } catch ( error ) {
  35953. if ( this._getFallback !== null ) {
  35954. // try the fallback
  35955. try {
  35956. this.backend = backend = this._getFallback( error );
  35957. await backend.init( this );
  35958. } catch ( error ) {
  35959. reject( error );
  35960. return;
  35961. }
  35962. } else {
  35963. reject( error );
  35964. return;
  35965. }
  35966. }
  35967. this._nodes = new Nodes( this, backend );
  35968. this._animation = new Animation( this._nodes, this.info );
  35969. this._attributes = new Attributes( backend );
  35970. this._background = new Background( this, this._nodes );
  35971. this._geometries = new Geometries( this._attributes, this.info );
  35972. this._textures = new Textures( this, backend, this.info );
  35973. this._pipelines = new Pipelines( backend, this._nodes );
  35974. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35975. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35976. this._renderLists = new RenderLists( this.lighting );
  35977. this._bundles = new RenderBundles();
  35978. this._renderContexts = new RenderContexts();
  35979. //
  35980. this._animation.start();
  35981. this._initialized = true;
  35982. resolve( this );
  35983. } );
  35984. return this._initPromise;
  35985. }
  35986. /**
  35987. * The coordinate system of the renderer. The value of this property
  35988. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  35989. * `THREE.WebGPUCoordinateSystem`.
  35990. *
  35991. * @readonly
  35992. * @type {number}
  35993. */
  35994. get coordinateSystem() {
  35995. return this.backend.coordinateSystem;
  35996. }
  35997. /**
  35998. * Compiles all materials in the given scene. This can be useful to avoid a
  35999. * phenomenon which is called "shader compilation stutter", which occurs when
  36000. * rendering an object with a new shader for the first time.
  36001. *
  36002. * If you want to add a 3D object to an existing scene, use the third optional
  36003. * parameter for applying the target scene. Note that the (target) scene's lighting
  36004. * and environment must be configured before calling this method.
  36005. *
  36006. * @async
  36007. * @param {Object3D} scene - The scene or 3D object to precompile.
  36008. * @param {Camera} camera - The camera that is used to render the scene.
  36009. * @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.
  36010. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  36011. */
  36012. async compileAsync( scene, camera, targetScene = null ) {
  36013. if ( this._isDeviceLost === true ) return;
  36014. if ( this._initialized === false ) await this.init();
  36015. // preserve render tree
  36016. const nodeFrame = this._nodes.nodeFrame;
  36017. const previousRenderId = nodeFrame.renderId;
  36018. const previousRenderContext = this._currentRenderContext;
  36019. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36020. const previousCompilationPromises = this._compilationPromises;
  36021. //
  36022. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36023. if ( targetScene === null ) targetScene = scene;
  36024. const renderTarget = this._renderTarget;
  36025. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  36026. const activeMipmapLevel = this._activeMipmapLevel;
  36027. const compilationPromises = [];
  36028. this._currentRenderContext = renderContext;
  36029. this._currentRenderObjectFunction = this.renderObject;
  36030. this._handleObjectFunction = this._createObjectPipeline;
  36031. this._compilationPromises = compilationPromises;
  36032. nodeFrame.renderId ++;
  36033. //
  36034. nodeFrame.update();
  36035. //
  36036. renderContext.depth = this.depth;
  36037. renderContext.stencil = this.stencil;
  36038. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36039. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  36040. //
  36041. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36042. //
  36043. const renderList = this._renderLists.get( scene, camera );
  36044. renderList.begin();
  36045. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  36046. // include lights from target scene
  36047. if ( targetScene !== scene ) {
  36048. targetScene.traverseVisible( function ( object ) {
  36049. if ( object.isLight && object.layers.test( camera.layers ) ) {
  36050. renderList.pushLight( object );
  36051. }
  36052. } );
  36053. }
  36054. renderList.finish();
  36055. //
  36056. if ( renderTarget !== null ) {
  36057. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36058. const renderTargetData = this._textures.get( renderTarget );
  36059. renderContext.textures = renderTargetData.textures;
  36060. renderContext.depthTexture = renderTargetData.depthTexture;
  36061. } else {
  36062. renderContext.textures = null;
  36063. renderContext.depthTexture = null;
  36064. }
  36065. //
  36066. this._background.update( sceneRef, renderList, renderContext );
  36067. // process render lists
  36068. const opaqueObjects = renderList.opaque;
  36069. const transparentObjects = renderList.transparent;
  36070. const transparentDoublePassObjects = renderList.transparentDoublePass;
  36071. const lightsNode = renderList.lightsNode;
  36072. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36073. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36074. // restore render tree
  36075. nodeFrame.renderId = previousRenderId;
  36076. this._currentRenderContext = previousRenderContext;
  36077. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36078. this._compilationPromises = previousCompilationPromises;
  36079. this._handleObjectFunction = this._renderObjectDirect;
  36080. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  36081. await Promise.all( compilationPromises );
  36082. }
  36083. /**
  36084. * Renders the scene in an async fashion.
  36085. *
  36086. * @async
  36087. * @param {Object3D} scene - The scene or 3D object to render.
  36088. * @param {Camera} camera - The camera.
  36089. * @return {Promise} A Promise that resolves when the render has been finished.
  36090. */
  36091. async renderAsync( scene, camera ) {
  36092. if ( this._initialized === false ) await this.init();
  36093. this._renderScene( scene, camera );
  36094. }
  36095. /**
  36096. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36097. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36098. *
  36099. * @async
  36100. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36101. */
  36102. async waitForGPU() {
  36103. await this.backend.waitForGPU();
  36104. }
  36105. /**
  36106. * Sets the given MRT configuration.
  36107. *
  36108. * @param {MRTNode} mrt - The MRT node to set.
  36109. * @return {Renderer} A reference to this renderer.
  36110. */
  36111. setMRT( mrt ) {
  36112. this._mrt = mrt;
  36113. return this;
  36114. }
  36115. /**
  36116. * Returns the MRT configuration.
  36117. *
  36118. * @return {MRTNode} The MRT configuration.
  36119. */
  36120. getMRT() {
  36121. return this._mrt;
  36122. }
  36123. /**
  36124. * Returns the color buffer type.
  36125. *
  36126. * @return {number} The color buffer type.
  36127. */
  36128. getColorBufferType() {
  36129. return this._colorBufferType;
  36130. }
  36131. /**
  36132. * Default implementation of the device lost callback.
  36133. *
  36134. * @private
  36135. * @param {Object} info - Information about the context lost.
  36136. */
  36137. _onDeviceLost( info ) {
  36138. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  36139. if ( info.reason ) {
  36140. errorMessage += `\nReason: ${info.reason}`;
  36141. }
  36142. console.error( errorMessage );
  36143. this._isDeviceLost = true;
  36144. }
  36145. /**
  36146. * Renders the given render bundle.
  36147. *
  36148. * @private
  36149. * @param {Object} bundle - Render bundle data.
  36150. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  36151. * @param {LightsNode} lightsNode - The lights node.
  36152. */
  36153. _renderBundle( bundle, sceneRef, lightsNode ) {
  36154. const { bundleGroup, camera, renderList } = bundle;
  36155. const renderContext = this._currentRenderContext;
  36156. //
  36157. const renderBundle = this._bundles.get( bundleGroup, camera );
  36158. const renderBundleData = this.backend.get( renderBundle );
  36159. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  36160. //
  36161. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  36162. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  36163. renderBundleData.renderContexts.add( renderContext );
  36164. if ( renderBundleNeedsUpdate ) {
  36165. this.backend.beginBundle( renderContext );
  36166. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  36167. renderBundleData.renderObjects = [];
  36168. }
  36169. this._currentRenderBundle = renderBundle;
  36170. const {
  36171. transparentDoublePass: transparentDoublePassObjects,
  36172. transparent: transparentObjects,
  36173. opaque: opaqueObjects
  36174. } = renderList;
  36175. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36176. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36177. this._currentRenderBundle = null;
  36178. //
  36179. this.backend.finishBundle( renderContext, renderBundle );
  36180. renderBundleData.version = bundleGroup.version;
  36181. } else {
  36182. const { renderObjects } = renderBundleData;
  36183. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  36184. const renderObject = renderObjects[ i ];
  36185. if ( this._nodes.needsRefresh( renderObject ) ) {
  36186. this._nodes.updateBefore( renderObject );
  36187. this._nodes.updateForRender( renderObject );
  36188. this._bindings.updateForRender( renderObject );
  36189. this._nodes.updateAfter( renderObject );
  36190. }
  36191. }
  36192. }
  36193. this.backend.addBundle( renderContext, renderBundle );
  36194. }
  36195. /**
  36196. * Renders the scene or 3D object with the given camera. This method can only be called
  36197. * if the renderer has been initialized.
  36198. *
  36199. * The target of the method is the default framebuffer (meaning the canvas)
  36200. * or alternatively a render target when specified via `setRenderTarget()`.
  36201. *
  36202. * @param {Object3D} scene - The scene or 3D object to render.
  36203. * @param {Camera} camera - The camera to render the scene with.
  36204. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  36205. * Only returned when the renderer has not been initialized.
  36206. */
  36207. render( scene, camera ) {
  36208. if ( this._initialized === false ) {
  36209. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  36210. return this.renderAsync( scene, camera );
  36211. }
  36212. this._renderScene( scene, camera );
  36213. }
  36214. /**
  36215. * Returns an internal render target which is used when computing the output tone mapping
  36216. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  36217. * pass and not inline to achieve more correct results.
  36218. *
  36219. * @private
  36220. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  36221. */
  36222. _getFrameBufferTarget() {
  36223. const { currentToneMapping, currentColorSpace } = this;
  36224. const useToneMapping = currentToneMapping !== NoToneMapping;
  36225. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  36226. if ( useToneMapping === false && useColorSpace === false ) return null;
  36227. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  36228. const { depth, stencil } = this;
  36229. let frameBufferTarget = this._frameBufferTarget;
  36230. if ( frameBufferTarget === null ) {
  36231. frameBufferTarget = new RenderTarget( width, height, {
  36232. depthBuffer: depth,
  36233. stencilBuffer: stencil,
  36234. type: this._colorBufferType,
  36235. format: RGBAFormat,
  36236. colorSpace: LinearSRGBColorSpace,
  36237. generateMipmaps: false,
  36238. minFilter: LinearFilter,
  36239. magFilter: LinearFilter,
  36240. samples: this.samples
  36241. } );
  36242. frameBufferTarget.isPostProcessingRenderTarget = true;
  36243. this._frameBufferTarget = frameBufferTarget;
  36244. }
  36245. frameBufferTarget.depthBuffer = depth;
  36246. frameBufferTarget.stencilBuffer = stencil;
  36247. frameBufferTarget.setSize( width, height );
  36248. frameBufferTarget.viewport.copy( this._viewport );
  36249. frameBufferTarget.scissor.copy( this._scissor );
  36250. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  36251. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  36252. frameBufferTarget.scissorTest = this._scissorTest;
  36253. return frameBufferTarget;
  36254. }
  36255. /**
  36256. * Renders the scene or 3D object with the given camera.
  36257. *
  36258. * @private
  36259. * @param {Object3D} scene - The scene or 3D object to render.
  36260. * @param {Camera} camera - The camera to render the scene with.
  36261. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  36262. * @return {RenderContext} The current render context.
  36263. */
  36264. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  36265. if ( this._isDeviceLost === true ) return;
  36266. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  36267. // preserve render tree
  36268. const nodeFrame = this._nodes.nodeFrame;
  36269. const previousRenderId = nodeFrame.renderId;
  36270. const previousRenderContext = this._currentRenderContext;
  36271. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36272. //
  36273. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36274. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  36275. const activeCubeFace = this._activeCubeFace;
  36276. const activeMipmapLevel = this._activeMipmapLevel;
  36277. //
  36278. let renderTarget;
  36279. if ( frameBufferTarget !== null ) {
  36280. renderTarget = frameBufferTarget;
  36281. this.setRenderTarget( renderTarget );
  36282. } else {
  36283. renderTarget = outputRenderTarget;
  36284. }
  36285. //
  36286. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  36287. this._currentRenderContext = renderContext;
  36288. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  36289. //
  36290. this.info.calls ++;
  36291. this.info.render.calls ++;
  36292. this.info.render.frameCalls ++;
  36293. nodeFrame.renderId = this.info.calls;
  36294. //
  36295. const coordinateSystem = this.coordinateSystem;
  36296. const xr = this.xr;
  36297. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  36298. camera.coordinateSystem = coordinateSystem;
  36299. camera.updateProjectionMatrix();
  36300. if ( camera.isArrayCamera ) {
  36301. for ( const subCamera of camera.cameras ) {
  36302. subCamera.coordinateSystem = coordinateSystem;
  36303. subCamera.updateProjectionMatrix();
  36304. }
  36305. }
  36306. }
  36307. //
  36308. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  36309. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  36310. if ( xr.enabled === true && xr.isPresenting === true ) {
  36311. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  36312. camera = xr.getCamera(); // use XR camera for rendering
  36313. }
  36314. //
  36315. let viewport = this._viewport;
  36316. let scissor = this._scissor;
  36317. let pixelRatio = this._pixelRatio;
  36318. if ( renderTarget !== null ) {
  36319. viewport = renderTarget.viewport;
  36320. scissor = renderTarget.scissor;
  36321. pixelRatio = 1;
  36322. }
  36323. this.getDrawingBufferSize( _drawingBufferSize );
  36324. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  36325. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  36326. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  36327. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  36328. renderContext.viewportValue.width >>= activeMipmapLevel;
  36329. renderContext.viewportValue.height >>= activeMipmapLevel;
  36330. renderContext.viewportValue.minDepth = minDepth;
  36331. renderContext.viewportValue.maxDepth = maxDepth;
  36332. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  36333. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  36334. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  36335. renderContext.scissorValue.width >>= activeMipmapLevel;
  36336. renderContext.scissorValue.height >>= activeMipmapLevel;
  36337. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36338. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  36339. //
  36340. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36341. //
  36342. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  36343. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  36344. const renderList = this._renderLists.get( scene, camera );
  36345. renderList.begin();
  36346. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  36347. renderList.finish();
  36348. if ( this.sortObjects === true ) {
  36349. renderList.sort( this._opaqueSort, this._transparentSort );
  36350. }
  36351. //
  36352. if ( renderTarget !== null ) {
  36353. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36354. const renderTargetData = this._textures.get( renderTarget );
  36355. renderContext.textures = renderTargetData.textures;
  36356. renderContext.depthTexture = renderTargetData.depthTexture;
  36357. renderContext.width = renderTargetData.width;
  36358. renderContext.height = renderTargetData.height;
  36359. renderContext.renderTarget = renderTarget;
  36360. renderContext.depth = renderTarget.depthBuffer;
  36361. renderContext.stencil = renderTarget.stencilBuffer;
  36362. } else {
  36363. renderContext.textures = null;
  36364. renderContext.depthTexture = null;
  36365. renderContext.width = this.domElement.width;
  36366. renderContext.height = this.domElement.height;
  36367. renderContext.depth = this.depth;
  36368. renderContext.stencil = this.stencil;
  36369. }
  36370. renderContext.width >>= activeMipmapLevel;
  36371. renderContext.height >>= activeMipmapLevel;
  36372. renderContext.activeCubeFace = activeCubeFace;
  36373. renderContext.activeMipmapLevel = activeMipmapLevel;
  36374. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  36375. //
  36376. this._background.update( sceneRef, renderList, renderContext );
  36377. //
  36378. this.backend.beginRender( renderContext );
  36379. // process render lists
  36380. const {
  36381. bundles,
  36382. lightsNode,
  36383. transparentDoublePass: transparentDoublePassObjects,
  36384. transparent: transparentObjects,
  36385. opaque: opaqueObjects
  36386. } = renderList;
  36387. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  36388. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36389. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36390. // finish render pass
  36391. this.backend.finishRender( renderContext );
  36392. // restore render tree
  36393. nodeFrame.renderId = previousRenderId;
  36394. this._currentRenderContext = previousRenderContext;
  36395. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36396. //
  36397. if ( frameBufferTarget !== null ) {
  36398. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  36399. this._renderOutput( renderTarget );
  36400. }
  36401. //
  36402. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  36403. //
  36404. return renderContext;
  36405. }
  36406. /**
  36407. * The output pass performs tone mapping and color space conversion.
  36408. *
  36409. * @private
  36410. * @param {RenderTarget} renderTarget - The current render target.
  36411. */
  36412. _renderOutput( renderTarget ) {
  36413. const quad = this._quad;
  36414. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36415. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36416. quad.material.needsUpdate = true;
  36417. }
  36418. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  36419. const currentAutoClear = this.autoClear;
  36420. const currentXR = this.xr.enabled;
  36421. this.autoClear = false;
  36422. this.xr.enabled = false;
  36423. this._renderScene( quad, quad.camera, false );
  36424. this.autoClear = currentAutoClear;
  36425. this.xr.enabled = currentXR;
  36426. }
  36427. /**
  36428. * Returns the maximum available anisotropy for texture filtering.
  36429. *
  36430. * @return {number} The maximum available anisotropy.
  36431. */
  36432. getMaxAnisotropy() {
  36433. return this.backend.getMaxAnisotropy();
  36434. }
  36435. /**
  36436. * Returns the active cube face.
  36437. *
  36438. * @return {number} The active cube face.
  36439. */
  36440. getActiveCubeFace() {
  36441. return this._activeCubeFace;
  36442. }
  36443. /**
  36444. * Returns the active mipmap level.
  36445. *
  36446. * @return {number} The active mipmap level.
  36447. */
  36448. getActiveMipmapLevel() {
  36449. return this._activeMipmapLevel;
  36450. }
  36451. /**
  36452. * Applications are advised to always define the animation loop
  36453. * with this method and not manually with `requestAnimationFrame()`
  36454. * for best compatibility.
  36455. *
  36456. * @async
  36457. * @param {?Function} callback - The application's animation loop.
  36458. * @return {Promise} A Promise that resolves when the set has been executed.
  36459. */
  36460. async setAnimationLoop( callback ) {
  36461. if ( this._initialized === false ) await this.init();
  36462. this._animation.setAnimationLoop( callback );
  36463. }
  36464. /**
  36465. * Can be used to transfer buffer data from a storage buffer attribute
  36466. * from the GPU to the CPU in context of compute shaders.
  36467. *
  36468. * @async
  36469. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  36470. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  36471. */
  36472. async getArrayBufferAsync( attribute ) {
  36473. return await this.backend.getArrayBufferAsync( attribute );
  36474. }
  36475. /**
  36476. * Returns the rendering context.
  36477. *
  36478. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  36479. */
  36480. getContext() {
  36481. return this.backend.getContext();
  36482. }
  36483. /**
  36484. * Returns the pixel ratio.
  36485. *
  36486. * @return {number} The pixel ratio.
  36487. */
  36488. getPixelRatio() {
  36489. return this._pixelRatio;
  36490. }
  36491. /**
  36492. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  36493. *
  36494. * @param {Vector2} target - The method writes the result in this target object.
  36495. * @return {Vector2} The drawing buffer size.
  36496. */
  36497. getDrawingBufferSize( target ) {
  36498. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  36499. }
  36500. /**
  36501. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  36502. *
  36503. * @param {Vector2} target - The method writes the result in this target object.
  36504. * @return {Vector2} The renderer's size in logical pixels.
  36505. */
  36506. getSize( target ) {
  36507. return target.set( this._width, this._height );
  36508. }
  36509. /**
  36510. * Sets the given pixel ratio and resizes the canvas if necessary.
  36511. *
  36512. * @param {number} [value=1] - The pixel ratio.
  36513. */
  36514. setPixelRatio( value = 1 ) {
  36515. if ( this._pixelRatio === value ) return;
  36516. this._pixelRatio = value;
  36517. this.setSize( this._width, this._height, false );
  36518. }
  36519. /**
  36520. * This method allows to define the drawing buffer size by specifying
  36521. * width, height and pixel ratio all at once. The size of the drawing
  36522. * buffer is computed with this formula:
  36523. * ```js
  36524. * size.x = width * pixelRatio;
  36525. * size.y = height * pixelRatio;
  36526. * ```
  36527. *
  36528. * @param {number} width - The width in logical pixels.
  36529. * @param {number} height - The height in logical pixels.
  36530. * @param {number} pixelRatio - The pixel ratio.
  36531. */
  36532. setDrawingBufferSize( width, height, pixelRatio ) {
  36533. // Renderer can't be resized while presenting in XR.
  36534. if ( this.xr && this.xr.isPresenting ) return;
  36535. this._width = width;
  36536. this._height = height;
  36537. this._pixelRatio = pixelRatio;
  36538. this.domElement.width = Math.floor( width * pixelRatio );
  36539. this.domElement.height = Math.floor( height * pixelRatio );
  36540. this.setViewport( 0, 0, width, height );
  36541. if ( this._initialized ) this.backend.updateSize();
  36542. }
  36543. /**
  36544. * Sets the size of the renderer.
  36545. *
  36546. * @param {number} width - The width in logical pixels.
  36547. * @param {number} height - The height in logical pixels.
  36548. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  36549. */
  36550. setSize( width, height, updateStyle = true ) {
  36551. // Renderer can't be resized while presenting in XR.
  36552. if ( this.xr && this.xr.isPresenting ) return;
  36553. this._width = width;
  36554. this._height = height;
  36555. this.domElement.width = Math.floor( width * this._pixelRatio );
  36556. this.domElement.height = Math.floor( height * this._pixelRatio );
  36557. if ( updateStyle === true ) {
  36558. this.domElement.style.width = width + 'px';
  36559. this.domElement.style.height = height + 'px';
  36560. }
  36561. this.setViewport( 0, 0, width, height );
  36562. if ( this._initialized ) this.backend.updateSize();
  36563. }
  36564. /**
  36565. * Defines a manual sort function for the opaque render list.
  36566. * Pass `null` to use the default sort.
  36567. *
  36568. * @param {Function} method - The sort function.
  36569. */
  36570. setOpaqueSort( method ) {
  36571. this._opaqueSort = method;
  36572. }
  36573. /**
  36574. * Defines a manual sort function for the transparent render list.
  36575. * Pass `null` to use the default sort.
  36576. *
  36577. * @param {Function} method - The sort function.
  36578. */
  36579. setTransparentSort( method ) {
  36580. this._transparentSort = method;
  36581. }
  36582. /**
  36583. * Returns the scissor rectangle.
  36584. *
  36585. * @param {Vector4} target - The method writes the result in this target object.
  36586. * @return {Vector4} The scissor rectangle.
  36587. */
  36588. getScissor( target ) {
  36589. const scissor = this._scissor;
  36590. target.x = scissor.x;
  36591. target.y = scissor.y;
  36592. target.width = scissor.width;
  36593. target.height = scissor.height;
  36594. return target;
  36595. }
  36596. /**
  36597. * Defines the scissor rectangle.
  36598. *
  36599. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  36600. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  36601. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  36602. * @param {number} width - The width of the scissor box in logical pixel unit.
  36603. * @param {number} height - The height of the scissor box in logical pixel unit.
  36604. */
  36605. setScissor( x, y, width, height ) {
  36606. const scissor = this._scissor;
  36607. if ( x.isVector4 ) {
  36608. scissor.copy( x );
  36609. } else {
  36610. scissor.set( x, y, width, height );
  36611. }
  36612. }
  36613. /**
  36614. * Returns the scissor test value.
  36615. *
  36616. * @return {boolean} Whether the scissor test should be enabled or not.
  36617. */
  36618. getScissorTest() {
  36619. return this._scissorTest;
  36620. }
  36621. /**
  36622. * Defines the scissor test.
  36623. *
  36624. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  36625. */
  36626. setScissorTest( boolean ) {
  36627. this._scissorTest = boolean;
  36628. this.backend.setScissorTest( boolean );
  36629. }
  36630. /**
  36631. * Returns the viewport definition.
  36632. *
  36633. * @param {Vector4} target - The method writes the result in this target object.
  36634. * @return {Vector4} The viewport definition.
  36635. */
  36636. getViewport( target ) {
  36637. return target.copy( this._viewport );
  36638. }
  36639. /**
  36640. * Defines the viewport.
  36641. *
  36642. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36643. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36644. * @param {number} width - The width of the viewport in logical pixel unit.
  36645. * @param {number} height - The height of the viewport in logical pixel unit.
  36646. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  36647. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  36648. */
  36649. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36650. const viewport = this._viewport;
  36651. if ( x.isVector4 ) {
  36652. viewport.copy( x );
  36653. } else {
  36654. viewport.set( x, y, width, height );
  36655. }
  36656. viewport.minDepth = minDepth;
  36657. viewport.maxDepth = maxDepth;
  36658. }
  36659. /**
  36660. * Returns the clear color.
  36661. *
  36662. * @param {Color} target - The method writes the result in this target object.
  36663. * @return {Color} The clear color.
  36664. */
  36665. getClearColor( target ) {
  36666. return target.copy( this._clearColor );
  36667. }
  36668. /**
  36669. * Defines the clear color and optionally the clear alpha.
  36670. *
  36671. * @param {Color} color - The clear color.
  36672. * @param {number} [alpha=1] - The clear alpha.
  36673. */
  36674. setClearColor( color, alpha = 1 ) {
  36675. this._clearColor.set( color );
  36676. this._clearColor.a = alpha;
  36677. }
  36678. /**
  36679. * Returns the clear alpha.
  36680. *
  36681. * @return {number} The clear alpha.
  36682. */
  36683. getClearAlpha() {
  36684. return this._clearColor.a;
  36685. }
  36686. /**
  36687. * Defines the clear alpha.
  36688. *
  36689. * @param {number} alpha - The clear alpha.
  36690. */
  36691. setClearAlpha( alpha ) {
  36692. this._clearColor.a = alpha;
  36693. }
  36694. /**
  36695. * Returns the clear depth.
  36696. *
  36697. * @return {number} The clear depth.
  36698. */
  36699. getClearDepth() {
  36700. return this._clearDepth;
  36701. }
  36702. /**
  36703. * Defines the clear depth.
  36704. *
  36705. * @param {number} depth - The clear depth.
  36706. */
  36707. setClearDepth( depth ) {
  36708. this._clearDepth = depth;
  36709. }
  36710. /**
  36711. * Returns the clear stencil.
  36712. *
  36713. * @return {number} The clear stencil.
  36714. */
  36715. getClearStencil() {
  36716. return this._clearStencil;
  36717. }
  36718. /**
  36719. * Defines the clear stencil.
  36720. *
  36721. * @param {number} stencil - The clear stencil.
  36722. */
  36723. setClearStencil( stencil ) {
  36724. this._clearStencil = stencil;
  36725. }
  36726. /**
  36727. * This method performs an occlusion query for the given 3D object.
  36728. * It returns `true` if the given 3D object is fully occluded by other
  36729. * 3D objects in the scene.
  36730. *
  36731. * @param {Object3D} object - The 3D object to test.
  36732. * @return {boolean} Whether the 3D object is fully occluded or not.
  36733. */
  36734. isOccluded( object ) {
  36735. const renderContext = this._currentRenderContext;
  36736. return renderContext && this.backend.isOccluded( renderContext, object );
  36737. }
  36738. /**
  36739. * Performs a manual clear operation. This method ignores `autoClear` properties.
  36740. *
  36741. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36742. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36743. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36744. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36745. * Only returned when the renderer has not been initialized.
  36746. */
  36747. clear( color = true, depth = true, stencil = true ) {
  36748. if ( this._initialized === false ) {
  36749. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36750. return this.clearAsync( color, depth, stencil );
  36751. }
  36752. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36753. let renderContext = null;
  36754. if ( renderTarget !== null ) {
  36755. this._textures.updateRenderTarget( renderTarget );
  36756. const renderTargetData = this._textures.get( renderTarget );
  36757. renderContext = this._renderContexts.getForClear( renderTarget );
  36758. renderContext.textures = renderTargetData.textures;
  36759. renderContext.depthTexture = renderTargetData.depthTexture;
  36760. renderContext.width = renderTargetData.width;
  36761. renderContext.height = renderTargetData.height;
  36762. renderContext.renderTarget = renderTarget;
  36763. renderContext.depth = renderTarget.depthBuffer;
  36764. renderContext.stencil = renderTarget.stencilBuffer;
  36765. // #30329
  36766. renderContext.clearColorValue = this.backend.getClearColor();
  36767. renderContext.activeCubeFace = this.getActiveCubeFace();
  36768. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  36769. }
  36770. this.backend.clear( color, depth, stencil, renderContext );
  36771. if ( renderTarget !== null && this._renderTarget === null ) {
  36772. this._renderOutput( renderTarget );
  36773. }
  36774. }
  36775. /**
  36776. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  36777. *
  36778. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36779. * Only returned when the renderer has not been initialized.
  36780. */
  36781. clearColor() {
  36782. return this.clear( true, false, false );
  36783. }
  36784. /**
  36785. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  36786. *
  36787. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36788. * Only returned when the renderer has not been initialized.
  36789. */
  36790. clearDepth() {
  36791. return this.clear( false, true, false );
  36792. }
  36793. /**
  36794. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  36795. *
  36796. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36797. * Only returned when the renderer has not been initialized.
  36798. */
  36799. clearStencil() {
  36800. return this.clear( false, false, true );
  36801. }
  36802. /**
  36803. * Async version of {@link Renderer#clear}.
  36804. *
  36805. * @async
  36806. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36807. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36808. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36809. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36810. */
  36811. async clearAsync( color = true, depth = true, stencil = true ) {
  36812. if ( this._initialized === false ) await this.init();
  36813. this.clear( color, depth, stencil );
  36814. }
  36815. /**
  36816. * Async version of {@link Renderer#clearColor}.
  36817. *
  36818. * @async
  36819. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36820. */
  36821. async clearColorAsync() {
  36822. this.clearAsync( true, false, false );
  36823. }
  36824. /**
  36825. * Async version of {@link Renderer#clearDepth}.
  36826. *
  36827. * @async
  36828. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36829. */
  36830. async clearDepthAsync() {
  36831. this.clearAsync( false, true, false );
  36832. }
  36833. /**
  36834. * Async version of {@link Renderer#clearStencil}.
  36835. *
  36836. * @async
  36837. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36838. */
  36839. async clearStencilAsync() {
  36840. this.clearAsync( false, false, true );
  36841. }
  36842. /**
  36843. * The current output tone mapping of the renderer. When a render target is set,
  36844. * the output tone mapping is always `NoToneMapping`.
  36845. *
  36846. * @type {number}
  36847. */
  36848. get currentToneMapping() {
  36849. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  36850. }
  36851. /**
  36852. * The current output color space of the renderer. When a render target is set,
  36853. * the output color space is always `LinearSRGBColorSpace`.
  36854. *
  36855. * @type {string}
  36856. */
  36857. get currentColorSpace() {
  36858. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  36859. }
  36860. /**
  36861. * Returns `true` if the rendering settings are set to screen output.
  36862. *
  36863. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  36864. */
  36865. get isOutputTarget() {
  36866. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  36867. }
  36868. /**
  36869. * Frees all internal resources of the renderer. Call this method if the renderer
  36870. * is no longer in use by your app.
  36871. */
  36872. dispose() {
  36873. this.info.dispose();
  36874. this.backend.dispose();
  36875. this._animation.dispose();
  36876. this._objects.dispose();
  36877. this._pipelines.dispose();
  36878. this._nodes.dispose();
  36879. this._bindings.dispose();
  36880. this._renderLists.dispose();
  36881. this._renderContexts.dispose();
  36882. this._textures.dispose();
  36883. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  36884. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  36885. if ( queryPool !== null ) queryPool.dispose();
  36886. } );
  36887. this.setRenderTarget( null );
  36888. this.setAnimationLoop( null );
  36889. }
  36890. /**
  36891. * Sets the given render target. Calling this method means the renderer does not
  36892. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  36893. * Use `null` as the first argument to reset the state.
  36894. *
  36895. * @param {?RenderTarget} renderTarget - The render target to set.
  36896. * @param {number} [activeCubeFace=0] - The active cube face.
  36897. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  36898. */
  36899. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36900. this._renderTarget = renderTarget;
  36901. this._activeCubeFace = activeCubeFace;
  36902. this._activeMipmapLevel = activeMipmapLevel;
  36903. }
  36904. /**
  36905. * Returns the current render target.
  36906. *
  36907. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  36908. */
  36909. getRenderTarget() {
  36910. return this._renderTarget;
  36911. }
  36912. /**
  36913. * Sets the output render target for the renderer.
  36914. *
  36915. * @param {Object} renderTarget - The render target to set as the output target.
  36916. */
  36917. setOutputRenderTarget( renderTarget ) {
  36918. this._outputRenderTarget = renderTarget;
  36919. }
  36920. /**
  36921. * Returns the current output target.
  36922. *
  36923. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  36924. */
  36925. getOutputRenderTarget() {
  36926. return this._outputRenderTarget;
  36927. }
  36928. /**
  36929. * Callback for {@link Renderer#setRenderObjectFunction}.
  36930. *
  36931. * @callback renderObjectFunction
  36932. * @param {Object3D} object - The 3D object.
  36933. * @param {Scene} scene - The scene the 3D object belongs to.
  36934. * @param {Camera} camera - The camera the object should be rendered with.
  36935. * @param {BufferGeometry} geometry - The object's geometry.
  36936. * @param {Material} material - The object's material.
  36937. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36938. * @param {LightsNode} lightsNode - The current lights node.
  36939. * @param {ClippingContext} clippingContext - The clipping context.
  36940. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36941. */
  36942. /**
  36943. * Sets the given render object function. Calling this method overwrites the default implementation
  36944. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  36945. * if you want to modify the way objects are rendered. For example you can define things like "every
  36946. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  36947. * The custom function must always call `renderObject()` in its implementation.
  36948. *
  36949. * Use `null` as the first argument to reset the state.
  36950. *
  36951. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  36952. */
  36953. setRenderObjectFunction( renderObjectFunction ) {
  36954. this._renderObjectFunction = renderObjectFunction;
  36955. }
  36956. /**
  36957. * Returns the current render object function.
  36958. *
  36959. * @return {?Function} The current render object function. Returns `null` if no function is set.
  36960. */
  36961. getRenderObjectFunction() {
  36962. return this._renderObjectFunction;
  36963. }
  36964. /**
  36965. * Execute a single or an array of compute nodes. This method can only be called
  36966. * if the renderer has been initialized.
  36967. *
  36968. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36969. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  36970. */
  36971. compute( computeNodes ) {
  36972. if ( this._isDeviceLost === true ) return;
  36973. if ( this._initialized === false ) {
  36974. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  36975. return this.computeAsync( computeNodes );
  36976. }
  36977. //
  36978. const nodeFrame = this._nodes.nodeFrame;
  36979. const previousRenderId = nodeFrame.renderId;
  36980. //
  36981. this.info.calls ++;
  36982. this.info.compute.calls ++;
  36983. this.info.compute.frameCalls ++;
  36984. nodeFrame.renderId = this.info.calls;
  36985. //
  36986. const backend = this.backend;
  36987. const pipelines = this._pipelines;
  36988. const bindings = this._bindings;
  36989. const nodes = this._nodes;
  36990. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36991. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36992. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36993. }
  36994. backend.beginCompute( computeNodes );
  36995. for ( const computeNode of computeList ) {
  36996. // onInit
  36997. if ( pipelines.has( computeNode ) === false ) {
  36998. const dispose = () => {
  36999. computeNode.removeEventListener( 'dispose', dispose );
  37000. pipelines.delete( computeNode );
  37001. bindings.delete( computeNode );
  37002. nodes.delete( computeNode );
  37003. };
  37004. computeNode.addEventListener( 'dispose', dispose );
  37005. //
  37006. const onInitFn = computeNode.onInitFunction;
  37007. if ( onInitFn !== null ) {
  37008. onInitFn.call( computeNode, { renderer: this } );
  37009. }
  37010. }
  37011. nodes.updateForCompute( computeNode );
  37012. bindings.updateForCompute( computeNode );
  37013. const computeBindings = bindings.getForCompute( computeNode );
  37014. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37015. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37016. }
  37017. backend.finishCompute( computeNodes );
  37018. //
  37019. nodeFrame.renderId = previousRenderId;
  37020. }
  37021. /**
  37022. * Execute a single or an array of compute nodes.
  37023. *
  37024. * @async
  37025. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  37026. * @return {Promise} A Promise that resolve when the compute has finished.
  37027. */
  37028. async computeAsync( computeNodes ) {
  37029. if ( this._initialized === false ) await this.init();
  37030. this.compute( computeNodes );
  37031. }
  37032. /**
  37033. * Checks if the given feature is supported by the selected backend.
  37034. *
  37035. * @async
  37036. * @param {string} name - The feature's name.
  37037. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  37038. */
  37039. async hasFeatureAsync( name ) {
  37040. if ( this._initialized === false ) await this.init();
  37041. return this.backend.hasFeature( name );
  37042. }
  37043. async resolveTimestampsAsync( type = 'render' ) {
  37044. if ( this._initialized === false ) await this.init();
  37045. return this.backend.resolveTimestampsAsync( type );
  37046. }
  37047. /**
  37048. * Checks if the given feature is supported by the selected backend. If the
  37049. * renderer has not been initialized, this method always returns `false`.
  37050. *
  37051. * @param {string} name - The feature's name.
  37052. * @return {boolean} Whether the feature is supported or not.
  37053. */
  37054. hasFeature( name ) {
  37055. if ( this._initialized === false ) {
  37056. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37057. return false;
  37058. }
  37059. return this.backend.hasFeature( name );
  37060. }
  37061. /**
  37062. * Returns `true` when the renderer has been initialized.
  37063. *
  37064. * @return {boolean} Whether the renderer has been initialized or not.
  37065. */
  37066. hasInitialized() {
  37067. return this._initialized;
  37068. }
  37069. /**
  37070. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  37071. * (which can cause noticeable lags due to decode and GPU upload overhead).
  37072. *
  37073. * @async
  37074. * @param {Texture} texture - The texture.
  37075. * @return {Promise} A Promise that resolves when the texture has been initialized.
  37076. */
  37077. async initTextureAsync( texture ) {
  37078. if ( this._initialized === false ) await this.init();
  37079. this._textures.updateTexture( texture );
  37080. }
  37081. /**
  37082. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  37083. * (which can cause noticeable lags due to decode and GPU upload overhead).
  37084. *
  37085. * This method can only be used if the renderer has been initialized.
  37086. *
  37087. * @param {Texture} texture - The texture.
  37088. */
  37089. initTexture( texture ) {
  37090. if ( this._initialized === false ) {
  37091. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  37092. }
  37093. this._textures.updateTexture( texture );
  37094. }
  37095. /**
  37096. * Copies the current bound framebuffer into the given texture.
  37097. *
  37098. * @param {FramebufferTexture} framebufferTexture - The texture.
  37099. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  37100. */
  37101. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  37102. if ( rectangle !== null ) {
  37103. if ( rectangle.isVector2 ) {
  37104. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  37105. } else if ( rectangle.isVector4 ) {
  37106. rectangle = _vector4.copy( rectangle ).floor();
  37107. } else {
  37108. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  37109. return;
  37110. }
  37111. } else {
  37112. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  37113. }
  37114. //
  37115. let renderContext = this._currentRenderContext;
  37116. let renderTarget;
  37117. if ( renderContext !== null ) {
  37118. renderTarget = renderContext.renderTarget;
  37119. } else {
  37120. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37121. if ( renderTarget !== null ) {
  37122. this._textures.updateRenderTarget( renderTarget );
  37123. renderContext = this._textures.get( renderTarget );
  37124. }
  37125. }
  37126. //
  37127. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  37128. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  37129. }
  37130. /**
  37131. * Copies data of the given source texture into a destination texture.
  37132. *
  37133. * @param {Texture} srcTexture - The source texture.
  37134. * @param {Texture} dstTexture - The destination texture.
  37135. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  37136. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  37137. * @param {number} [srcLevel=0] - The source mip level to copy from.
  37138. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  37139. */
  37140. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  37141. this._textures.updateTexture( srcTexture );
  37142. this._textures.updateTexture( dstTexture );
  37143. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  37144. }
  37145. /**
  37146. * Reads pixel data from the given render target.
  37147. *
  37148. * @async
  37149. * @param {RenderTarget} renderTarget - The render target to read from.
  37150. * @param {number} x - The `x` coordinate of the copy region's origin.
  37151. * @param {number} y - The `y` coordinate of the copy region's origin.
  37152. * @param {number} width - The width of the copy region.
  37153. * @param {number} height - The height of the copy region.
  37154. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  37155. * @param {number} [faceIndex=0] - The active cube face index.
  37156. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  37157. */
  37158. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  37159. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  37160. }
  37161. /**
  37162. * Analyzes the given 3D object's hierarchy and builds render lists from the
  37163. * processed hierarchy.
  37164. *
  37165. * @param {Object3D} object - The 3D object to process (usually a scene).
  37166. * @param {Camera} camera - The camera the object is rendered with.
  37167. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  37168. * @param {RenderList} renderList - The current render list.
  37169. * @param {ClippingContext} clippingContext - The current clipping context.
  37170. */
  37171. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  37172. if ( object.visible === false ) return;
  37173. const visible = object.layers.test( camera.layers );
  37174. if ( visible ) {
  37175. if ( object.isGroup ) {
  37176. groupOrder = object.renderOrder;
  37177. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  37178. } else if ( object.isLOD ) {
  37179. if ( object.autoUpdate === true ) object.update( camera );
  37180. } else if ( object.isLight ) {
  37181. renderList.pushLight( object );
  37182. } else if ( object.isSprite ) {
  37183. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  37184. if ( this.sortObjects === true ) {
  37185. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  37186. }
  37187. const { geometry, material } = object;
  37188. if ( material.visible ) {
  37189. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  37190. }
  37191. }
  37192. } else if ( object.isLineLoop ) {
  37193. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  37194. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  37195. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  37196. const { geometry, material } = object;
  37197. if ( this.sortObjects === true ) {
  37198. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  37199. _vector4
  37200. .copy( geometry.boundingSphere.center )
  37201. .applyMatrix4( object.matrixWorld )
  37202. .applyMatrix4( _projScreenMatrix );
  37203. }
  37204. if ( Array.isArray( material ) ) {
  37205. const groups = geometry.groups;
  37206. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  37207. const group = groups[ i ];
  37208. const groupMaterial = material[ group.materialIndex ];
  37209. if ( groupMaterial && groupMaterial.visible ) {
  37210. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  37211. }
  37212. }
  37213. } else if ( material.visible ) {
  37214. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  37215. }
  37216. }
  37217. }
  37218. }
  37219. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  37220. const baseRenderList = renderList;
  37221. // replace render list
  37222. renderList = this._renderLists.get( object, camera );
  37223. renderList.begin();
  37224. baseRenderList.pushBundle( {
  37225. bundleGroup: object,
  37226. camera,
  37227. renderList,
  37228. } );
  37229. renderList.finish();
  37230. }
  37231. const children = object.children;
  37232. for ( let i = 0, l = children.length; i < l; i ++ ) {
  37233. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  37234. }
  37235. }
  37236. /**
  37237. * Renders the given render bundles.
  37238. *
  37239. * @private
  37240. * @param {Array<Object>} bundles - Array with render bundle data.
  37241. * @param {Scene} sceneRef - The scene the render bundles belong to.
  37242. * @param {LightsNode} lightsNode - The current lights node.
  37243. */
  37244. _renderBundles( bundles, sceneRef, lightsNode ) {
  37245. for ( const bundle of bundles ) {
  37246. this._renderBundle( bundle, sceneRef, lightsNode );
  37247. }
  37248. }
  37249. /**
  37250. * Renders the transparent objects from the given render lists.
  37251. *
  37252. * @private
  37253. * @param {Array<Object>} renderList - The transparent render list.
  37254. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  37255. * @param {Camera} camera - The camera the render list should be rendered with.
  37256. * @param {Scene} scene - The scene the render list belongs to.
  37257. * @param {LightsNode} lightsNode - The current lights node.
  37258. */
  37259. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  37260. if ( doublePassList.length > 0 ) {
  37261. // render back side
  37262. for ( const { material } of doublePassList ) {
  37263. material.side = BackSide;
  37264. }
  37265. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  37266. // render front side
  37267. for ( const { material } of doublePassList ) {
  37268. material.side = FrontSide;
  37269. }
  37270. this._renderObjects( renderList, camera, scene, lightsNode );
  37271. // restore
  37272. for ( const { material } of doublePassList ) {
  37273. material.side = DoubleSide;
  37274. }
  37275. } else {
  37276. this._renderObjects( renderList, camera, scene, lightsNode );
  37277. }
  37278. }
  37279. /**
  37280. * Renders the objects from the given render list.
  37281. *
  37282. * @private
  37283. * @param {Array<Object>} renderList - The render list.
  37284. * @param {Camera} camera - The camera the render list should be rendered with.
  37285. * @param {Scene} scene - The scene the render list belongs to.
  37286. * @param {LightsNode} lightsNode - The current lights node.
  37287. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37288. */
  37289. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  37290. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  37291. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  37292. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  37293. }
  37294. }
  37295. /**
  37296. * This method represents the default render object function that manages the render lifecycle
  37297. * of the object.
  37298. *
  37299. * @param {Object3D} object - The 3D object.
  37300. * @param {Scene} scene - The scene the 3D object belongs to.
  37301. * @param {Camera} camera - The camera the object should be rendered with.
  37302. * @param {BufferGeometry} geometry - The object's geometry.
  37303. * @param {Material} material - The object's material.
  37304. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37305. * @param {LightsNode} lightsNode - The current lights node.
  37306. * @param {?ClippingContext} clippingContext - The clipping context.
  37307. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37308. */
  37309. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  37310. let overridePositionNode;
  37311. let overrideColorNode;
  37312. let overrideDepthNode;
  37313. //
  37314. object.onBeforeRender( this, scene, camera, geometry, material, group );
  37315. //
  37316. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  37317. const overrideMaterial = scene.overrideMaterial;
  37318. if ( material.positionNode && material.positionNode.isNode ) {
  37319. overridePositionNode = overrideMaterial.positionNode;
  37320. overrideMaterial.positionNode = material.positionNode;
  37321. }
  37322. overrideMaterial.alphaTest = material.alphaTest;
  37323. overrideMaterial.alphaMap = material.alphaMap;
  37324. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  37325. if ( overrideMaterial.isShadowPassMaterial ) {
  37326. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  37327. if ( material.depthNode && material.depthNode.isNode ) {
  37328. overrideDepthNode = overrideMaterial.depthNode;
  37329. overrideMaterial.depthNode = material.depthNode;
  37330. }
  37331. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  37332. overrideColorNode = overrideMaterial.colorNode;
  37333. overrideMaterial.colorNode = material.castShadowNode;
  37334. }
  37335. }
  37336. material = overrideMaterial;
  37337. }
  37338. //
  37339. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  37340. material.side = BackSide;
  37341. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  37342. material.side = FrontSide;
  37343. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  37344. material.side = DoubleSide;
  37345. } else {
  37346. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  37347. }
  37348. //
  37349. if ( overridePositionNode !== undefined ) {
  37350. scene.overrideMaterial.positionNode = overridePositionNode;
  37351. }
  37352. if ( overrideDepthNode !== undefined ) {
  37353. scene.overrideMaterial.depthNode = overrideDepthNode;
  37354. }
  37355. if ( overrideColorNode !== undefined ) {
  37356. scene.overrideMaterial.colorNode = overrideColorNode;
  37357. }
  37358. //
  37359. object.onAfterRender( this, scene, camera, geometry, material, group );
  37360. }
  37361. /**
  37362. * This method represents the default `_handleObjectFunction` implementation which creates
  37363. * a render object from the given data and performs the draw command with the selected backend.
  37364. *
  37365. * @private
  37366. * @param {Object3D} object - The 3D object.
  37367. * @param {Material} material - The object's material.
  37368. * @param {Scene} scene - The scene the 3D object belongs to.
  37369. * @param {Camera} camera - The camera the object should be rendered with.
  37370. * @param {LightsNode} lightsNode - The current lights node.
  37371. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37372. * @param {ClippingContext} clippingContext - The clipping context.
  37373. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37374. */
  37375. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  37376. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  37377. renderObject.drawRange = object.geometry.drawRange;
  37378. renderObject.group = group;
  37379. //
  37380. const needsRefresh = this._nodes.needsRefresh( renderObject );
  37381. if ( needsRefresh ) {
  37382. this._nodes.updateBefore( renderObject );
  37383. this._geometries.updateForRender( renderObject );
  37384. this._nodes.updateForRender( renderObject );
  37385. this._bindings.updateForRender( renderObject );
  37386. }
  37387. this._pipelines.updateForRender( renderObject );
  37388. //
  37389. if ( this._currentRenderBundle !== null ) {
  37390. const renderBundleData = this.backend.get( this._currentRenderBundle );
  37391. renderBundleData.renderObjects.push( renderObject );
  37392. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  37393. }
  37394. this.backend.draw( renderObject, this.info );
  37395. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  37396. }
  37397. /**
  37398. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  37399. * Used in `compileAsync()`.
  37400. *
  37401. * @private
  37402. * @param {Object3D} object - The 3D object.
  37403. * @param {Material} material - The object's material.
  37404. * @param {Scene} scene - The scene the 3D object belongs to.
  37405. * @param {Camera} camera - The camera the object should be rendered with.
  37406. * @param {LightsNode} lightsNode - The current lights node.
  37407. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37408. * @param {ClippingContext} clippingContext - The clipping context.
  37409. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37410. */
  37411. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  37412. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  37413. renderObject.drawRange = object.geometry.drawRange;
  37414. renderObject.group = group;
  37415. //
  37416. this._nodes.updateBefore( renderObject );
  37417. this._geometries.updateForRender( renderObject );
  37418. this._nodes.updateForRender( renderObject );
  37419. this._bindings.updateForRender( renderObject );
  37420. this._pipelines.getForRender( renderObject, this._compilationPromises );
  37421. this._nodes.updateAfter( renderObject );
  37422. }
  37423. /**
  37424. * Alias for `compileAsync()`.
  37425. *
  37426. * @method
  37427. * @param {Object3D} scene - The scene or 3D object to precompile.
  37428. * @param {Camera} camera - The camera that is used to render the scene.
  37429. * @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.
  37430. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  37431. */
  37432. get compile() {
  37433. return this.compileAsync;
  37434. }
  37435. }
  37436. /**
  37437. * A binding represents the connection between a resource (like a texture, sampler
  37438. * or uniform buffer) and the resource definition in a shader stage.
  37439. *
  37440. * This module is an abstract base class for all concrete bindings types.
  37441. *
  37442. * @abstract
  37443. * @private
  37444. */
  37445. class Binding {
  37446. /**
  37447. * Constructs a new binding.
  37448. *
  37449. * @param {string} [name=''] - The binding's name.
  37450. */
  37451. constructor( name = '' ) {
  37452. /**
  37453. * The binding's name.
  37454. *
  37455. * @type {string}
  37456. */
  37457. this.name = name;
  37458. /**
  37459. * A bitmask that defines in what shader stages the
  37460. * binding's resource is accessible.
  37461. *
  37462. * @type {number}
  37463. */
  37464. this.visibility = 0;
  37465. }
  37466. /**
  37467. * Makes sure binding's resource is visible for the given shader stage.
  37468. *
  37469. * @param {number} visibility - The shader stage.
  37470. */
  37471. setVisibility( visibility ) {
  37472. this.visibility |= visibility;
  37473. }
  37474. /**
  37475. * Clones the binding.
  37476. *
  37477. * @return {Binding} The cloned binding.
  37478. */
  37479. clone() {
  37480. return Object.assign( new this.constructor(), this );
  37481. }
  37482. }
  37483. /**
  37484. * This function is usually called with the length in bytes of an array buffer.
  37485. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  37486. *
  37487. * @function
  37488. * @param {number} floatLength - The buffer length.
  37489. * @return {number} The padded length.
  37490. */
  37491. function getFloatLength( floatLength ) {
  37492. // ensure chunk size alignment (STD140 layout)
  37493. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  37494. }
  37495. /**
  37496. * Represents a buffer binding type.
  37497. *
  37498. * @private
  37499. * @abstract
  37500. * @augments Binding
  37501. */
  37502. class Buffer extends Binding {
  37503. /**
  37504. * Constructs a new buffer.
  37505. *
  37506. * @param {string} name - The buffer's name.
  37507. * @param {TypedArray} [buffer=null] - The buffer.
  37508. */
  37509. constructor( name, buffer = null ) {
  37510. super( name );
  37511. /**
  37512. * This flag can be used for type testing.
  37513. *
  37514. * @type {boolean}
  37515. * @readonly
  37516. * @default true
  37517. */
  37518. this.isBuffer = true;
  37519. /**
  37520. * The bytes per element.
  37521. *
  37522. * @type {number}
  37523. */
  37524. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  37525. /**
  37526. * A reference to the internal buffer.
  37527. *
  37528. * @private
  37529. * @type {TypedArray}
  37530. */
  37531. this._buffer = buffer;
  37532. }
  37533. /**
  37534. * The buffer's byte length.
  37535. *
  37536. * @type {number}
  37537. * @readonly
  37538. */
  37539. get byteLength() {
  37540. return getFloatLength( this._buffer.byteLength );
  37541. }
  37542. /**
  37543. * A reference to the internal buffer.
  37544. *
  37545. * @type {Float32Array}
  37546. * @readonly
  37547. */
  37548. get buffer() {
  37549. return this._buffer;
  37550. }
  37551. /**
  37552. * Updates the binding.
  37553. *
  37554. * @return {boolean} Whether the buffer has been updated and must be
  37555. * uploaded to the GPU.
  37556. */
  37557. update() {
  37558. return true;
  37559. }
  37560. }
  37561. /**
  37562. * Represents a uniform buffer binding type.
  37563. *
  37564. * @private
  37565. * @augments Buffer
  37566. */
  37567. class UniformBuffer extends Buffer {
  37568. /**
  37569. * Constructs a new uniform buffer.
  37570. *
  37571. * @param {string} name - The buffer's name.
  37572. * @param {TypedArray} [buffer=null] - The buffer.
  37573. */
  37574. constructor( name, buffer = null ) {
  37575. super( name, buffer );
  37576. /**
  37577. * This flag can be used for type testing.
  37578. *
  37579. * @type {boolean}
  37580. * @readonly
  37581. * @default true
  37582. */
  37583. this.isUniformBuffer = true;
  37584. }
  37585. }
  37586. let _id$4 = 0;
  37587. /**
  37588. * A special form of uniform buffer binding type.
  37589. * It's buffer value is managed by a node object.
  37590. *
  37591. * @private
  37592. * @augments UniformBuffer
  37593. */
  37594. class NodeUniformBuffer extends UniformBuffer {
  37595. /**
  37596. * Constructs a new node-based uniform buffer.
  37597. *
  37598. * @param {BufferNode} nodeUniform - The uniform buffer node.
  37599. * @param {UniformGroupNode} groupNode - The uniform group node.
  37600. */
  37601. constructor( nodeUniform, groupNode ) {
  37602. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  37603. /**
  37604. * The uniform buffer node.
  37605. *
  37606. * @type {BufferNode}
  37607. */
  37608. this.nodeUniform = nodeUniform;
  37609. /**
  37610. * The uniform group node.
  37611. *
  37612. * @type {UniformGroupNode}
  37613. */
  37614. this.groupNode = groupNode;
  37615. }
  37616. /**
  37617. * The uniform buffer.
  37618. *
  37619. * @type {Float32Array}
  37620. */
  37621. get buffer() {
  37622. return this.nodeUniform.value;
  37623. }
  37624. }
  37625. /**
  37626. * This class represents a uniform buffer binding but with
  37627. * an API that allows to maintain individual uniform objects.
  37628. *
  37629. * @private
  37630. * @augments UniformBuffer
  37631. */
  37632. class UniformsGroup extends UniformBuffer {
  37633. /**
  37634. * Constructs a new uniforms group.
  37635. *
  37636. * @param {string} name - The group's name.
  37637. */
  37638. constructor( name ) {
  37639. super( name );
  37640. /**
  37641. * This flag can be used for type testing.
  37642. *
  37643. * @type {boolean}
  37644. * @readonly
  37645. * @default true
  37646. */
  37647. this.isUniformsGroup = true;
  37648. /**
  37649. * An array with the raw uniform values.
  37650. *
  37651. * @private
  37652. * @type {?Array<number>}
  37653. * @default null
  37654. */
  37655. this._values = null;
  37656. /**
  37657. * An array of uniform objects.
  37658. *
  37659. * The order of uniforms in this array must match the order of uniforms in the shader.
  37660. *
  37661. * @type {Array<Uniform>}
  37662. */
  37663. this.uniforms = [];
  37664. }
  37665. /**
  37666. * Adds a uniform to this group.
  37667. *
  37668. * @param {Uniform} uniform - The uniform to add.
  37669. * @return {UniformsGroup} A reference to this group.
  37670. */
  37671. addUniform( uniform ) {
  37672. this.uniforms.push( uniform );
  37673. return this;
  37674. }
  37675. /**
  37676. * Removes a uniform from this group.
  37677. *
  37678. * @param {Uniform} uniform - The uniform to remove.
  37679. * @return {UniformsGroup} A reference to this group.
  37680. */
  37681. removeUniform( uniform ) {
  37682. const index = this.uniforms.indexOf( uniform );
  37683. if ( index !== - 1 ) {
  37684. this.uniforms.splice( index, 1 );
  37685. }
  37686. return this;
  37687. }
  37688. /**
  37689. * An array with the raw uniform values.
  37690. *
  37691. * @type {Array<number>}
  37692. */
  37693. get values() {
  37694. if ( this._values === null ) {
  37695. this._values = Array.from( this.buffer );
  37696. }
  37697. return this._values;
  37698. }
  37699. /**
  37700. * A Float32 array buffer with the uniform values.
  37701. *
  37702. * @type {Float32Array}
  37703. */
  37704. get buffer() {
  37705. let buffer = this._buffer;
  37706. if ( buffer === null ) {
  37707. const byteLength = this.byteLength;
  37708. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  37709. this._buffer = buffer;
  37710. }
  37711. return buffer;
  37712. }
  37713. /**
  37714. * The byte length of the buffer with correct buffer alignment.
  37715. *
  37716. * @type {number}
  37717. */
  37718. get byteLength() {
  37719. let offset = 0; // global buffer offset in bytes
  37720. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  37721. const uniform = this.uniforms[ i ];
  37722. const { boundary, itemSize } = uniform;
  37723. // offset within a single chunk in bytes
  37724. const chunkOffset = offset % GPU_CHUNK_BYTES;
  37725. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  37726. // conformance tests
  37727. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  37728. // check for chunk overflow
  37729. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  37730. } else if ( chunkOffset % boundary !== 0 ) {
  37731. // check for correct alignment
  37732. offset += ( chunkOffset % boundary );
  37733. }
  37734. uniform.offset = ( offset / this.bytesPerElement );
  37735. offset += ( itemSize * this.bytesPerElement );
  37736. }
  37737. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  37738. }
  37739. /**
  37740. * Updates this group by updating each uniform object of
  37741. * the internal uniform list. The uniform objects check if their
  37742. * values has actually changed so this method only returns
  37743. * `true` if there is a real value change.
  37744. *
  37745. * @return {boolean} Whether the uniforms have been updated and
  37746. * must be uploaded to the GPU.
  37747. */
  37748. update() {
  37749. let updated = false;
  37750. for ( const uniform of this.uniforms ) {
  37751. if ( this.updateByType( uniform ) === true ) {
  37752. updated = true;
  37753. }
  37754. }
  37755. return updated;
  37756. }
  37757. /**
  37758. * Updates a given uniform by calling an update method matching
  37759. * the uniforms type.
  37760. *
  37761. * @param {Uniform} uniform - The uniform to update.
  37762. * @return {boolean} Whether the uniform has been updated or not.
  37763. */
  37764. updateByType( uniform ) {
  37765. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  37766. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  37767. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  37768. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  37769. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  37770. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  37771. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  37772. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  37773. }
  37774. /**
  37775. * Updates a given Number uniform.
  37776. *
  37777. * @param {NumberUniform} uniform - The Number uniform.
  37778. * @return {boolean} Whether the uniform has been updated or not.
  37779. */
  37780. updateNumber( uniform ) {
  37781. let updated = false;
  37782. const a = this.values;
  37783. const v = uniform.getValue();
  37784. const offset = uniform.offset;
  37785. const type = uniform.getType();
  37786. if ( a[ offset ] !== v ) {
  37787. const b = this._getBufferForType( type );
  37788. b[ offset ] = a[ offset ] = v;
  37789. updated = true;
  37790. }
  37791. return updated;
  37792. }
  37793. /**
  37794. * Updates a given Vector2 uniform.
  37795. *
  37796. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  37797. * @return {boolean} Whether the uniform has been updated or not.
  37798. */
  37799. updateVector2( uniform ) {
  37800. let updated = false;
  37801. const a = this.values;
  37802. const v = uniform.getValue();
  37803. const offset = uniform.offset;
  37804. const type = uniform.getType();
  37805. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  37806. const b = this._getBufferForType( type );
  37807. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37808. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37809. updated = true;
  37810. }
  37811. return updated;
  37812. }
  37813. /**
  37814. * Updates a given Vector3 uniform.
  37815. *
  37816. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  37817. * @return {boolean} Whether the uniform has been updated or not.
  37818. */
  37819. updateVector3( uniform ) {
  37820. let updated = false;
  37821. const a = this.values;
  37822. const v = uniform.getValue();
  37823. const offset = uniform.offset;
  37824. const type = uniform.getType();
  37825. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  37826. const b = this._getBufferForType( type );
  37827. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37828. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37829. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37830. updated = true;
  37831. }
  37832. return updated;
  37833. }
  37834. /**
  37835. * Updates a given Vector4 uniform.
  37836. *
  37837. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  37838. * @return {boolean} Whether the uniform has been updated or not.
  37839. */
  37840. updateVector4( uniform ) {
  37841. let updated = false;
  37842. const a = this.values;
  37843. const v = uniform.getValue();
  37844. const offset = uniform.offset;
  37845. const type = uniform.getType();
  37846. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  37847. const b = this._getBufferForType( type );
  37848. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37849. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37850. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37851. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  37852. updated = true;
  37853. }
  37854. return updated;
  37855. }
  37856. /**
  37857. * Updates a given Color uniform.
  37858. *
  37859. * @param {ColorUniform} uniform - The Color uniform.
  37860. * @return {boolean} Whether the uniform has been updated or not.
  37861. */
  37862. updateColor( uniform ) {
  37863. let updated = false;
  37864. const a = this.values;
  37865. const c = uniform.getValue();
  37866. const offset = uniform.offset;
  37867. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  37868. const b = this.buffer;
  37869. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  37870. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  37871. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  37872. updated = true;
  37873. }
  37874. return updated;
  37875. }
  37876. /**
  37877. * Updates a given Matrix3 uniform.
  37878. *
  37879. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  37880. * @return {boolean} Whether the uniform has been updated or not.
  37881. */
  37882. updateMatrix3( uniform ) {
  37883. let updated = false;
  37884. const a = this.values;
  37885. const e = uniform.getValue().elements;
  37886. const offset = uniform.offset;
  37887. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  37888. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  37889. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  37890. const b = this.buffer;
  37891. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  37892. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  37893. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  37894. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  37895. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  37896. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  37897. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  37898. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  37899. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  37900. updated = true;
  37901. }
  37902. return updated;
  37903. }
  37904. /**
  37905. * Updates a given Matrix4 uniform.
  37906. *
  37907. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  37908. * @return {boolean} Whether the uniform has been updated or not.
  37909. */
  37910. updateMatrix4( uniform ) {
  37911. let updated = false;
  37912. const a = this.values;
  37913. const e = uniform.getValue().elements;
  37914. const offset = uniform.offset;
  37915. if ( arraysEqual( a, e, offset ) === false ) {
  37916. const b = this.buffer;
  37917. b.set( e, offset );
  37918. setArray( a, e, offset );
  37919. updated = true;
  37920. }
  37921. return updated;
  37922. }
  37923. /**
  37924. * Returns a typed array that matches the given data type.
  37925. *
  37926. * @param {string} type - The data type.
  37927. * @return {TypedArray} The typed array.
  37928. */
  37929. _getBufferForType( type ) {
  37930. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  37931. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  37932. return this.buffer;
  37933. }
  37934. }
  37935. /**
  37936. * Sets the values of the second array to the first array.
  37937. *
  37938. * @private
  37939. * @param {TypedArray} a - The first array.
  37940. * @param {TypedArray} b - The second array.
  37941. * @param {number} offset - An index offset for the first array.
  37942. */
  37943. function setArray( a, b, offset ) {
  37944. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37945. a[ offset + i ] = b[ i ];
  37946. }
  37947. }
  37948. /**
  37949. * Returns `true` if the given arrays are equal.
  37950. *
  37951. * @private
  37952. * @param {TypedArray} a - The first array.
  37953. * @param {TypedArray} b - The second array.
  37954. * @param {number} offset - An index offset for the first array.
  37955. * @return {boolean} Whether the given arrays are equal or not.
  37956. */
  37957. function arraysEqual( a, b, offset ) {
  37958. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37959. if ( a[ offset + i ] !== b[ i ] ) return false;
  37960. }
  37961. return true;
  37962. }
  37963. let _id$3 = 0;
  37964. /**
  37965. * A special form of uniforms group that represents
  37966. * the individual uniforms as node-based uniforms.
  37967. *
  37968. * @private
  37969. * @augments UniformsGroup
  37970. */
  37971. class NodeUniformsGroup extends UniformsGroup {
  37972. /**
  37973. * Constructs a new node-based uniforms group.
  37974. *
  37975. * @param {string} name - The group's name.
  37976. * @param {UniformGroupNode} groupNode - The uniform group node.
  37977. */
  37978. constructor( name, groupNode ) {
  37979. super( name );
  37980. /**
  37981. * The group's ID.
  37982. *
  37983. * @type {number}
  37984. */
  37985. this.id = _id$3 ++;
  37986. /**
  37987. * The uniform group node.
  37988. *
  37989. * @type {UniformGroupNode}
  37990. */
  37991. this.groupNode = groupNode;
  37992. /**
  37993. * This flag can be used for type testing.
  37994. *
  37995. * @type {boolean}
  37996. * @readonly
  37997. * @default true
  37998. */
  37999. this.isNodeUniformsGroup = true;
  38000. }
  38001. }
  38002. let _id$2 = 0;
  38003. /**
  38004. * Represents a sampled texture binding type.
  38005. *
  38006. * @private
  38007. * @augments Binding
  38008. */
  38009. class SampledTexture extends Binding {
  38010. /**
  38011. * Constructs a new sampled texture.
  38012. *
  38013. * @param {string} name - The sampled texture's name.
  38014. * @param {?Texture} texture - The texture this binding is referring to.
  38015. */
  38016. constructor( name, texture ) {
  38017. super( name );
  38018. /**
  38019. * This identifier.
  38020. *
  38021. * @type {number}
  38022. */
  38023. this.id = _id$2 ++;
  38024. /**
  38025. * The texture this binding is referring to.
  38026. *
  38027. * @type {?Texture}
  38028. */
  38029. this.texture = texture;
  38030. /**
  38031. * The binding's version.
  38032. *
  38033. * @type {number}
  38034. */
  38035. this.version = texture ? texture.version : 0;
  38036. /**
  38037. * Whether the texture is a storage texture or not.
  38038. *
  38039. * @type {boolean}
  38040. * @default false
  38041. */
  38042. this.store = false;
  38043. /**
  38044. * The binding's generation which is an additional version
  38045. * qualifier.
  38046. *
  38047. * @type {?number}
  38048. * @default null
  38049. */
  38050. this.generation = null;
  38051. /**
  38052. * This flag can be used for type testing.
  38053. *
  38054. * @type {boolean}
  38055. * @readonly
  38056. * @default true
  38057. */
  38058. this.isSampledTexture = true;
  38059. }
  38060. /**
  38061. * Returns `true` whether this binding requires an update for the
  38062. * given generation.
  38063. *
  38064. * @param {number} generation - The generation.
  38065. * @return {boolean} Whether an update is required or not.
  38066. */
  38067. needsBindingsUpdate( generation ) {
  38068. const { texture } = this;
  38069. if ( generation !== this.generation ) {
  38070. this.generation = generation;
  38071. return true;
  38072. }
  38073. return texture.isVideoTexture;
  38074. }
  38075. /**
  38076. * Updates the binding.
  38077. *
  38078. * @return {boolean} Whether the texture has been updated and must be
  38079. * uploaded to the GPU.
  38080. */
  38081. update() {
  38082. const { texture, version } = this;
  38083. if ( version !== texture.version ) {
  38084. this.version = texture.version;
  38085. return true;
  38086. }
  38087. return false;
  38088. }
  38089. }
  38090. /**
  38091. * A special form of sampled texture binding type.
  38092. * It's texture value is managed by a node object.
  38093. *
  38094. * @private
  38095. * @augments SampledTexture
  38096. */
  38097. class NodeSampledTexture extends SampledTexture {
  38098. /**
  38099. * Constructs a new node-based sampled texture.
  38100. *
  38101. * @param {string} name - The textures's name.
  38102. * @param {TextureNode} textureNode - The texture node.
  38103. * @param {UniformGroupNode} groupNode - The uniform group node.
  38104. * @param {?string} [access=null] - The access type.
  38105. */
  38106. constructor( name, textureNode, groupNode, access = null ) {
  38107. super( name, textureNode ? textureNode.value : null );
  38108. /**
  38109. * The texture node.
  38110. *
  38111. * @type {TextureNode}
  38112. */
  38113. this.textureNode = textureNode;
  38114. /**
  38115. * The uniform group node.
  38116. *
  38117. * @type {UniformGroupNode}
  38118. */
  38119. this.groupNode = groupNode;
  38120. /**
  38121. * The access type.
  38122. *
  38123. * @type {?string}
  38124. * @default null
  38125. */
  38126. this.access = access;
  38127. }
  38128. /**
  38129. * Overwrites the default to additionally check if the node value has changed.
  38130. *
  38131. * @param {number} generation - The generation.
  38132. * @return {boolean} Whether an update is required or not.
  38133. */
  38134. needsBindingsUpdate( generation ) {
  38135. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38136. }
  38137. /**
  38138. * Updates the binding.
  38139. *
  38140. * @return {boolean} Whether the texture has been updated and must be
  38141. * uploaded to the GPU.
  38142. */
  38143. update() {
  38144. const { textureNode } = this;
  38145. if ( this.texture !== textureNode.value ) {
  38146. this.texture = textureNode.value;
  38147. return true;
  38148. }
  38149. return super.update();
  38150. }
  38151. }
  38152. /**
  38153. * A special form of sampled cube texture binding type.
  38154. * It's texture value is managed by a node object.
  38155. *
  38156. * @private
  38157. * @augments NodeSampledTexture
  38158. */
  38159. class NodeSampledCubeTexture extends NodeSampledTexture {
  38160. /**
  38161. * Constructs a new node-based sampled cube texture.
  38162. *
  38163. * @param {string} name - The textures's name.
  38164. * @param {TextureNode} textureNode - The texture node.
  38165. * @param {UniformGroupNode} groupNode - The uniform group node.
  38166. * @param {?string} [access=null] - The access type.
  38167. */
  38168. constructor( name, textureNode, groupNode, access = null ) {
  38169. super( name, textureNode, groupNode, access );
  38170. /**
  38171. * This flag can be used for type testing.
  38172. *
  38173. * @type {boolean}
  38174. * @readonly
  38175. * @default true
  38176. */
  38177. this.isSampledCubeTexture = true;
  38178. }
  38179. }
  38180. /**
  38181. * A special form of sampled 3D texture binding type.
  38182. * It's texture value is managed by a node object.
  38183. *
  38184. * @private
  38185. * @augments NodeSampledTexture
  38186. */
  38187. class NodeSampledTexture3D extends NodeSampledTexture {
  38188. /**
  38189. * Constructs a new node-based sampled 3D texture.
  38190. *
  38191. * @param {string} name - The textures's name.
  38192. * @param {TextureNode} textureNode - The texture node.
  38193. * @param {UniformGroupNode} groupNode - The uniform group node.
  38194. * @param {?string} [access=null] - The access type.
  38195. */
  38196. constructor( name, textureNode, groupNode, access = null ) {
  38197. super( name, textureNode, groupNode, access );
  38198. /**
  38199. * This flag can be used for type testing.
  38200. *
  38201. * @type {boolean}
  38202. * @readonly
  38203. * @default true
  38204. */
  38205. this.isSampledTexture3D = true;
  38206. }
  38207. }
  38208. const glslMethods = {
  38209. textureDimensions: 'textureSize',
  38210. equals: 'equal'
  38211. };
  38212. const precisionLib = {
  38213. low: 'lowp',
  38214. medium: 'mediump',
  38215. high: 'highp'
  38216. };
  38217. const supports$1 = {
  38218. swizzleAssign: true,
  38219. storageBuffer: false
  38220. };
  38221. const defaultPrecisions = `
  38222. precision highp float;
  38223. precision highp int;
  38224. precision highp sampler2D;
  38225. precision highp sampler3D;
  38226. precision highp samplerCube;
  38227. precision highp sampler2DArray;
  38228. precision highp usampler2D;
  38229. precision highp usampler3D;
  38230. precision highp usamplerCube;
  38231. precision highp usampler2DArray;
  38232. precision highp isampler2D;
  38233. precision highp isampler3D;
  38234. precision highp isamplerCube;
  38235. precision highp isampler2DArray;
  38236. precision lowp sampler2DShadow;
  38237. `;
  38238. /**
  38239. * A node builder targeting GLSL.
  38240. *
  38241. * This module generates GLSL shader code from node materials and also
  38242. * generates the respective bindings and vertex buffer definitions. These
  38243. * data are later used by the renderer to create render and compute pipelines
  38244. * for render objects.
  38245. *
  38246. * @augments NodeBuilder
  38247. */
  38248. class GLSLNodeBuilder extends NodeBuilder {
  38249. /**
  38250. * Constructs a new GLSL node builder renderer.
  38251. *
  38252. * @param {Object3D} object - The 3D object.
  38253. * @param {Renderer} renderer - The renderer.
  38254. */
  38255. constructor( object, renderer ) {
  38256. super( object, renderer, new GLSLNodeParser() );
  38257. /**
  38258. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  38259. * another dictionary which manages UBOs per group ('render','frame','object').
  38260. *
  38261. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  38262. */
  38263. this.uniformGroups = {};
  38264. /**
  38265. * An array that holds objects defining the varying and attribute data in
  38266. * context of Transform Feedback.
  38267. *
  38268. * @type {Array<Object<string,AttributeNode|string>>}
  38269. */
  38270. this.transforms = [];
  38271. /**
  38272. * A dictionary that holds for each shader stage a Map of used extensions.
  38273. *
  38274. * @type {Object<string,Map<string,Object>>}
  38275. */
  38276. this.extensions = {};
  38277. /**
  38278. * A dictionary that holds for each shader stage an Array of used builtins.
  38279. *
  38280. * @type {Object<string,Array<string>>}
  38281. */
  38282. this.builtins = { vertex: [], fragment: [], compute: [] };
  38283. /**
  38284. * Whether comparison in shader code are generated with methods or not.
  38285. *
  38286. * @type {boolean}
  38287. * @default true
  38288. */
  38289. this.useComparisonMethod = true;
  38290. }
  38291. /**
  38292. * Checks if the given texture requires a manual conversion to the working color space.
  38293. *
  38294. * @param {Texture} texture - The texture to check.
  38295. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  38296. */
  38297. needsToWorkingColorSpace( texture ) {
  38298. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38299. }
  38300. /**
  38301. * Returns the native shader method name for a given generic name.
  38302. *
  38303. * @param {string} method - The method name to resolve.
  38304. * @return {string} The resolved GLSL method name.
  38305. */
  38306. getMethod( method ) {
  38307. return glslMethods[ method ] || method;
  38308. }
  38309. /**
  38310. * Returns the output struct name. Not relevant for GLSL.
  38311. *
  38312. * @return {string}
  38313. */
  38314. getOutputStructName() {
  38315. return '';
  38316. }
  38317. /**
  38318. * Builds the given shader node.
  38319. *
  38320. * @param {ShaderNodeInternal} shaderNode - The shader node.
  38321. * @return {string} The GLSL function code.
  38322. */
  38323. buildFunctionCode( shaderNode ) {
  38324. const layout = shaderNode.layout;
  38325. const flowData = this.flowShaderNode( shaderNode );
  38326. const parameters = [];
  38327. for ( const input of layout.inputs ) {
  38328. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38329. }
  38330. //
  38331. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38332. ${ flowData.vars }
  38333. ${ flowData.code }
  38334. return ${ flowData.result };
  38335. }`;
  38336. //
  38337. return code;
  38338. }
  38339. /**
  38340. * Setups the Pixel Buffer Object (PBO) for the given storage
  38341. * buffer node.
  38342. *
  38343. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  38344. */
  38345. setupPBO( storageBufferNode ) {
  38346. const attribute = storageBufferNode.value;
  38347. if ( attribute.pbo === undefined ) {
  38348. const originalArray = attribute.array;
  38349. const numElements = attribute.count * attribute.itemSize;
  38350. const { itemSize } = attribute;
  38351. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38352. let format = isInteger ? RedIntegerFormat : RedFormat;
  38353. if ( itemSize === 2 ) {
  38354. format = isInteger ? RGIntegerFormat : RGFormat;
  38355. } else if ( itemSize === 3 ) {
  38356. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38357. } else if ( itemSize === 4 ) {
  38358. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38359. }
  38360. const typeMap = {
  38361. Float32Array: FloatType,
  38362. Uint8Array: UnsignedByteType,
  38363. Uint16Array: UnsignedShortType,
  38364. Uint32Array: UnsignedIntType,
  38365. Int8Array: ByteType,
  38366. Int16Array: ShortType,
  38367. Int32Array: IntType,
  38368. Uint8ClampedArray: UnsignedByteType,
  38369. };
  38370. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38371. let height = Math.ceil( ( numElements / itemSize ) / width );
  38372. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38373. const newSize = width * height * itemSize;
  38374. const newArray = new originalArray.constructor( newSize );
  38375. newArray.set( originalArray, 0 );
  38376. attribute.array = newArray;
  38377. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38378. pboTexture.needsUpdate = true;
  38379. pboTexture.isPBOTexture = true;
  38380. const pbo = new TextureNode( pboTexture, null, null );
  38381. pbo.setPrecision( 'high' );
  38382. attribute.pboNode = pbo;
  38383. attribute.pbo = pbo.value;
  38384. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38385. }
  38386. }
  38387. /**
  38388. * Returns a GLSL snippet that represents the property name of the given node.
  38389. *
  38390. * @param {Node} node - The node.
  38391. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  38392. * @return {string} The property name.
  38393. */
  38394. getPropertyName( node, shaderStage = this.shaderStage ) {
  38395. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38396. return shaderStage.charAt( 0 ) + '_' + node.name;
  38397. }
  38398. return super.getPropertyName( node, shaderStage );
  38399. }
  38400. /**
  38401. * Setups the Pixel Buffer Object (PBO) for the given storage
  38402. * buffer node.
  38403. *
  38404. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  38405. * @return {string} The property name.
  38406. */
  38407. generatePBO( storageArrayElementNode ) {
  38408. const { node, indexNode } = storageArrayElementNode;
  38409. const attribute = node.value;
  38410. if ( this.renderer.backend.has( attribute ) ) {
  38411. const attributeData = this.renderer.backend.get( attribute );
  38412. attributeData.pbo = attribute.pbo;
  38413. }
  38414. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38415. const textureName = this.getPropertyName( nodeUniform );
  38416. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38417. const indexSnippet = indexNode.build( this, 'uint' );
  38418. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38419. let propertyName = elementNodeData.propertyName;
  38420. if ( propertyName === undefined ) {
  38421. // property element
  38422. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38423. propertyName = this.getPropertyName( nodeVar );
  38424. // property size
  38425. const bufferNodeData = this.getDataFromNode( node );
  38426. let propertySizeName = bufferNodeData.propertySizeName;
  38427. if ( propertySizeName === undefined ) {
  38428. propertySizeName = propertyName + 'Size';
  38429. this.getVarFromNode( node, propertySizeName, 'uint' );
  38430. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38431. bufferNodeData.propertySizeName = propertySizeName;
  38432. }
  38433. //
  38434. const { itemSize } = attribute;
  38435. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38436. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38437. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38438. //
  38439. let prefix = 'vec4';
  38440. if ( attribute.pbo.type === UnsignedIntType ) {
  38441. prefix = 'uvec4';
  38442. } else if ( attribute.pbo.type === IntType ) {
  38443. prefix = 'ivec4';
  38444. }
  38445. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38446. elementNodeData.propertyName = propertyName;
  38447. }
  38448. return propertyName;
  38449. }
  38450. /**
  38451. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  38452. *
  38453. * @param {Texture} texture - The texture.
  38454. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38455. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38456. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  38457. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  38458. * @return {string} The GLSL snippet.
  38459. */
  38460. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38461. if ( depthSnippet ) {
  38462. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38463. } else {
  38464. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38465. }
  38466. }
  38467. /**
  38468. * Generates the GLSL snippet for sampling/loading the given texture.
  38469. *
  38470. * @param {Texture} texture - The texture.
  38471. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38472. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38473. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  38474. * @return {string} The GLSL snippet.
  38475. */
  38476. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38477. if ( texture.isDepthTexture ) {
  38478. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38479. } else {
  38480. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38481. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38482. }
  38483. }
  38484. /**
  38485. * Generates the GLSL snippet when sampling textures with explicit mip level.
  38486. *
  38487. * @param {Texture} texture - The texture.
  38488. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38489. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38490. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  38491. * @return {string} The GLSL snippet.
  38492. */
  38493. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38494. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38495. }
  38496. /**
  38497. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  38498. *
  38499. * @param {Texture} texture - The texture.
  38500. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38501. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38502. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  38503. * @return {string} The GLSL snippet.
  38504. */
  38505. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38506. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38507. }
  38508. /**
  38509. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  38510. *
  38511. * @param {Texture} texture - The texture.
  38512. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38513. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38514. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  38515. * @return {string} The GLSL snippet.
  38516. */
  38517. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38518. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38519. }
  38520. /**
  38521. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  38522. * against a reference value.
  38523. *
  38524. * @param {Texture} texture - The texture.
  38525. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38526. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38527. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  38528. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  38529. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  38530. * @return {string} The GLSL snippet.
  38531. */
  38532. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38533. if ( shaderStage === 'fragment' ) {
  38534. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38535. } else {
  38536. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38537. }
  38538. }
  38539. /**
  38540. * Returns the variables of the given shader stage as a GLSL string.
  38541. *
  38542. * @param {string} shaderStage - The shader stage.
  38543. * @return {string} The GLSL snippet that defines the variables.
  38544. */
  38545. getVars( shaderStage ) {
  38546. const snippets = [];
  38547. const vars = this.vars[ shaderStage ];
  38548. if ( vars !== undefined ) {
  38549. for ( const variable of vars ) {
  38550. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  38551. }
  38552. }
  38553. return snippets.join( '\n\t' );
  38554. }
  38555. /**
  38556. * Returns the uniforms of the given shader stage as a GLSL string.
  38557. *
  38558. * @param {string} shaderStage - The shader stage.
  38559. * @return {string} The GLSL snippet that defines the uniforms.
  38560. */
  38561. getUniforms( shaderStage ) {
  38562. const uniforms = this.uniforms[ shaderStage ];
  38563. const bindingSnippets = [];
  38564. const uniformGroups = {};
  38565. for ( const uniform of uniforms ) {
  38566. let snippet = null;
  38567. let group = false;
  38568. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  38569. const texture = uniform.node.value;
  38570. let typePrefix = '';
  38571. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  38572. if ( texture.type === UnsignedIntType ) {
  38573. typePrefix = 'u';
  38574. } else if ( texture.type === IntType ) {
  38575. typePrefix = 'i';
  38576. }
  38577. }
  38578. if ( uniform.type === 'texture3D' ) {
  38579. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  38580. } else if ( texture.compareFunction ) {
  38581. snippet = `sampler2DShadow ${ uniform.name };`;
  38582. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38583. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38584. } else {
  38585. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38586. }
  38587. } else if ( uniform.type === 'cubeTexture' ) {
  38588. snippet = `samplerCube ${ uniform.name };`;
  38589. } else if ( uniform.type === 'buffer' ) {
  38590. const bufferNode = uniform.node;
  38591. const bufferType = this.getType( bufferNode.bufferType );
  38592. const bufferCount = bufferNode.bufferCount;
  38593. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38594. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38595. } else {
  38596. const vectorType = this.getVectorType( uniform.type );
  38597. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38598. group = true;
  38599. }
  38600. const precision = uniform.node.precision;
  38601. if ( precision !== null ) {
  38602. snippet = precisionLib[ precision ] + ' ' + snippet;
  38603. }
  38604. if ( group ) {
  38605. snippet = '\t' + snippet;
  38606. const groupName = uniform.groupNode.name;
  38607. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38608. groupSnippets.push( snippet );
  38609. } else {
  38610. snippet = 'uniform ' + snippet;
  38611. bindingSnippets.push( snippet );
  38612. }
  38613. }
  38614. let output = '';
  38615. for ( const name in uniformGroups ) {
  38616. const groupSnippets = uniformGroups[ name ];
  38617. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38618. }
  38619. output += bindingSnippets.join( '\n' );
  38620. return output;
  38621. }
  38622. /**
  38623. * Returns the type for a given buffer attribute.
  38624. *
  38625. * @param {BufferAttribute} attribute - The buffer attribute.
  38626. * @return {string} The type.
  38627. */
  38628. getTypeFromAttribute( attribute ) {
  38629. let nodeType = super.getTypeFromAttribute( attribute );
  38630. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38631. let dataAttribute = attribute;
  38632. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38633. const array = dataAttribute.array;
  38634. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38635. nodeType = nodeType.slice( 1 );
  38636. }
  38637. }
  38638. return nodeType;
  38639. }
  38640. /**
  38641. * Returns the shader attributes of the given shader stage as a GLSL string.
  38642. *
  38643. * @param {string} shaderStage - The shader stage.
  38644. * @return {string} The GLSL snippet that defines the shader attributes.
  38645. */
  38646. getAttributes( shaderStage ) {
  38647. let snippet = '';
  38648. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38649. const attributes = this.getAttributesArray();
  38650. let location = 0;
  38651. for ( const attribute of attributes ) {
  38652. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38653. }
  38654. }
  38655. return snippet;
  38656. }
  38657. /**
  38658. * Returns the members of the given struct type node as a GLSL string.
  38659. *
  38660. * @param {StructTypeNode} struct - The struct type node.
  38661. * @return {string} The GLSL snippet that defines the struct members.
  38662. */
  38663. getStructMembers( struct ) {
  38664. const snippets = [];
  38665. for ( const member of struct.members ) {
  38666. snippets.push( `\t${ member.type } ${ member.name };` );
  38667. }
  38668. return snippets.join( '\n' );
  38669. }
  38670. /**
  38671. * Returns the structs of the given shader stage as a GLSL string.
  38672. *
  38673. * @param {string} shaderStage - The shader stage.
  38674. * @return {string} The GLSL snippet that defines the structs.
  38675. */
  38676. getStructs( shaderStage ) {
  38677. const snippets = [];
  38678. const structs = this.structs[ shaderStage ];
  38679. const outputSnippet = [];
  38680. for ( const struct of structs ) {
  38681. if ( struct.output ) {
  38682. for ( const member of struct.members ) {
  38683. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  38684. }
  38685. } else {
  38686. let snippet = 'struct ' + struct.name + ' {\n';
  38687. snippet += this.getStructMembers( struct );
  38688. snippet += '\n};\n';
  38689. snippets.push( snippet );
  38690. }
  38691. }
  38692. if ( outputSnippet.length === 0 ) {
  38693. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  38694. }
  38695. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  38696. }
  38697. /**
  38698. * Returns the varyings of the given shader stage as a GLSL string.
  38699. *
  38700. * @param {string} shaderStage - The shader stage.
  38701. * @return {string} The GLSL snippet that defines the varyings.
  38702. */
  38703. getVaryings( shaderStage ) {
  38704. let snippet = '';
  38705. const varyings = this.varyings;
  38706. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38707. for ( const varying of varyings ) {
  38708. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38709. const type = this.getType( varying.type );
  38710. if ( varying.needsInterpolation ) {
  38711. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38712. snippet += `${flat} out ${type} ${varying.name};\n`;
  38713. } else {
  38714. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  38715. }
  38716. }
  38717. } else if ( shaderStage === 'fragment' ) {
  38718. for ( const varying of varyings ) {
  38719. if ( varying.needsInterpolation ) {
  38720. const type = this.getType( varying.type );
  38721. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38722. snippet += `${flat}in ${type} ${varying.name};\n`;
  38723. }
  38724. }
  38725. }
  38726. for ( const builtin of this.builtins[ shaderStage ] ) {
  38727. snippet += `${builtin};\n`;
  38728. }
  38729. return snippet;
  38730. }
  38731. /**
  38732. * Returns the vertex index builtin.
  38733. *
  38734. * @return {string} The vertex index.
  38735. */
  38736. getVertexIndex() {
  38737. return 'uint( gl_VertexID )';
  38738. }
  38739. /**
  38740. * Returns the instance index builtin.
  38741. *
  38742. * @return {string} The instance index.
  38743. */
  38744. getInstanceIndex() {
  38745. return 'uint( gl_InstanceID )';
  38746. }
  38747. /**
  38748. * Returns the invocation local index builtin.
  38749. *
  38750. * @return {string} The invocation local index.
  38751. */
  38752. getInvocationLocalIndex() {
  38753. const workgroupSize = this.object.workgroupSize;
  38754. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  38755. return `uint( gl_InstanceID ) % ${size}u`;
  38756. }
  38757. /**
  38758. * Returns the draw index builtin.
  38759. *
  38760. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  38761. */
  38762. getDrawIndex() {
  38763. const extensions = this.renderer.backend.extensions;
  38764. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38765. return 'uint( gl_DrawID )';
  38766. }
  38767. return null;
  38768. }
  38769. /**
  38770. * Returns the front facing builtin.
  38771. *
  38772. * @return {string} The front facing builtin.
  38773. */
  38774. getFrontFacing() {
  38775. return 'gl_FrontFacing';
  38776. }
  38777. /**
  38778. * Returns the frag coord builtin.
  38779. *
  38780. * @return {string} The frag coord builtin.
  38781. */
  38782. getFragCoord() {
  38783. return 'gl_FragCoord.xy';
  38784. }
  38785. /**
  38786. * Returns the frag depth builtin.
  38787. *
  38788. * @return {string} The frag depth builtin.
  38789. */
  38790. getFragDepth() {
  38791. return 'gl_FragDepth';
  38792. }
  38793. /**
  38794. * Enables the given extension.
  38795. *
  38796. * @param {string} name - The extension name.
  38797. * @param {string} behavior - The extension behavior.
  38798. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  38799. */
  38800. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38801. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38802. if ( map.has( name ) === false ) {
  38803. map.set( name, {
  38804. name,
  38805. behavior
  38806. } );
  38807. }
  38808. }
  38809. /**
  38810. * Returns the enabled extensions of the given shader stage as a GLSL string.
  38811. *
  38812. * @param {string} shaderStage - The shader stage.
  38813. * @return {string} The GLSL snippet that defines the enabled extensions.
  38814. */
  38815. getExtensions( shaderStage ) {
  38816. const snippets = [];
  38817. if ( shaderStage === 'vertex' ) {
  38818. const ext = this.renderer.backend.extensions;
  38819. const isBatchedMesh = this.object.isBatchedMesh;
  38820. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38821. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  38822. }
  38823. }
  38824. const extensions = this.extensions[ shaderStage ];
  38825. if ( extensions !== undefined ) {
  38826. for ( const { name, behavior } of extensions.values() ) {
  38827. snippets.push( `#extension ${name} : ${behavior}` );
  38828. }
  38829. }
  38830. return snippets.join( '\n' );
  38831. }
  38832. /**
  38833. * Returns the clip distances builtin.
  38834. *
  38835. * @return {string} The clip distances builtin.
  38836. */
  38837. getClipDistance() {
  38838. return 'gl_ClipDistance';
  38839. }
  38840. /**
  38841. * Whether the requested feature is available or not.
  38842. *
  38843. * @param {string} name - The requested feature.
  38844. * @return {boolean} Whether the requested feature is supported or not.
  38845. */
  38846. isAvailable( name ) {
  38847. let result = supports$1[ name ];
  38848. if ( result === undefined ) {
  38849. let extensionName;
  38850. result = false;
  38851. switch ( name ) {
  38852. case 'float32Filterable':
  38853. extensionName = 'OES_texture_float_linear';
  38854. break;
  38855. case 'clipDistance':
  38856. extensionName = 'WEBGL_clip_cull_distance';
  38857. break;
  38858. }
  38859. if ( extensionName !== undefined ) {
  38860. const extensions = this.renderer.backend.extensions;
  38861. if ( extensions.has( extensionName ) ) {
  38862. extensions.get( extensionName );
  38863. result = true;
  38864. }
  38865. }
  38866. supports$1[ name ] = result;
  38867. }
  38868. return result;
  38869. }
  38870. /**
  38871. * Whether to flip texture data along its vertical axis or not.
  38872. *
  38873. * @return {boolean} Returns always `true` in context of GLSL.
  38874. */
  38875. isFlipY() {
  38876. return true;
  38877. }
  38878. /**
  38879. * Enables hardware clipping.
  38880. *
  38881. * @param {string} planeCount - The clipping plane count.
  38882. */
  38883. enableHardwareClipping( planeCount ) {
  38884. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  38885. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  38886. }
  38887. /**
  38888. * Registers a transform in context of Transform Feedback.
  38889. *
  38890. * @param {string} varyingName - The varying name.
  38891. * @param {AttributeNode} attributeNode - The attribute node.
  38892. */
  38893. registerTransform( varyingName, attributeNode ) {
  38894. this.transforms.push( { varyingName, attributeNode } );
  38895. }
  38896. /**
  38897. * Returns the transforms of the given shader stage as a GLSL string.
  38898. *
  38899. * @param {string} shaderStage - The shader stage.
  38900. * @return {string} The GLSL snippet that defines the transforms.
  38901. */
  38902. getTransforms( /* shaderStage */ ) {
  38903. const transforms = this.transforms;
  38904. let snippet = '';
  38905. for ( let i = 0; i < transforms.length; i ++ ) {
  38906. const transform = transforms[ i ];
  38907. const attributeName = this.getPropertyName( transform.attributeNode );
  38908. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38909. }
  38910. return snippet;
  38911. }
  38912. /**
  38913. * Returns a GLSL struct based on the given name and variables.
  38914. *
  38915. * @private
  38916. * @param {string} name - The struct name.
  38917. * @param {string} vars - The struct variables.
  38918. * @return {string} The GLSL snippet representing a struct.
  38919. */
  38920. _getGLSLUniformStruct( name, vars ) {
  38921. return `
  38922. layout( std140 ) uniform ${name} {
  38923. ${vars}
  38924. };`;
  38925. }
  38926. /**
  38927. * Returns a GLSL vertex shader based on the given shader data.
  38928. *
  38929. * @private
  38930. * @param {Object} shaderData - The shader data.
  38931. * @return {string} The vertex shader.
  38932. */
  38933. _getGLSLVertexCode( shaderData ) {
  38934. return `#version 300 es
  38935. ${ this.getSignature() }
  38936. // extensions
  38937. ${shaderData.extensions}
  38938. // precision
  38939. ${ defaultPrecisions }
  38940. // uniforms
  38941. ${shaderData.uniforms}
  38942. // varyings
  38943. ${shaderData.varyings}
  38944. // attributes
  38945. ${shaderData.attributes}
  38946. // codes
  38947. ${shaderData.codes}
  38948. void main() {
  38949. // vars
  38950. ${shaderData.vars}
  38951. // transforms
  38952. ${shaderData.transforms}
  38953. // flow
  38954. ${shaderData.flow}
  38955. gl_PointSize = 1.0;
  38956. }
  38957. `;
  38958. }
  38959. /**
  38960. * Returns a GLSL fragment shader based on the given shader data.
  38961. *
  38962. * @private
  38963. * @param {Object} shaderData - The shader data.
  38964. * @return {string} The vertex shader.
  38965. */
  38966. _getGLSLFragmentCode( shaderData ) {
  38967. return `#version 300 es
  38968. ${ this.getSignature() }
  38969. // precision
  38970. ${ defaultPrecisions }
  38971. // uniforms
  38972. ${shaderData.uniforms}
  38973. // varyings
  38974. ${shaderData.varyings}
  38975. // codes
  38976. ${shaderData.codes}
  38977. // structs
  38978. ${shaderData.structs}
  38979. void main() {
  38980. // vars
  38981. ${shaderData.vars}
  38982. // flow
  38983. ${shaderData.flow}
  38984. }
  38985. `;
  38986. }
  38987. /**
  38988. * Controls the code build of the shader stages.
  38989. */
  38990. buildCode() {
  38991. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38992. this.sortBindingGroups();
  38993. for ( const shaderStage in shadersData ) {
  38994. let flow = '// code\n\n';
  38995. flow += this.flowCode[ shaderStage ];
  38996. const flowNodes = this.flowNodes[ shaderStage ];
  38997. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38998. for ( const node of flowNodes ) {
  38999. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39000. const slotName = node.name;
  39001. if ( slotName ) {
  39002. if ( flow.length > 0 ) flow += '\n';
  39003. flow += `\t// flow -> ${ slotName }\n\t`;
  39004. }
  39005. flow += `${ flowSlotData.code }\n\t`;
  39006. if ( node === mainNode && shaderStage !== 'compute' ) {
  39007. flow += '// result\n\t';
  39008. if ( shaderStage === 'vertex' ) {
  39009. flow += 'gl_Position = ';
  39010. flow += `${ flowSlotData.result };`;
  39011. } else if ( shaderStage === 'fragment' ) {
  39012. if ( ! node.outputNode.isOutputStructNode ) {
  39013. flow += 'fragColor = ';
  39014. flow += `${ flowSlotData.result };`;
  39015. }
  39016. }
  39017. }
  39018. }
  39019. const stageData = shadersData[ shaderStage ];
  39020. stageData.extensions = this.getExtensions( shaderStage );
  39021. stageData.uniforms = this.getUniforms( shaderStage );
  39022. stageData.attributes = this.getAttributes( shaderStage );
  39023. stageData.varyings = this.getVaryings( shaderStage );
  39024. stageData.vars = this.getVars( shaderStage );
  39025. stageData.structs = this.getStructs( shaderStage );
  39026. stageData.codes = this.getCodes( shaderStage );
  39027. stageData.transforms = this.getTransforms( shaderStage );
  39028. stageData.flow = flow;
  39029. }
  39030. if ( this.material !== null ) {
  39031. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39032. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39033. } else {
  39034. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39035. }
  39036. }
  39037. /**
  39038. * This method is one of the more important ones since it's responsible
  39039. * for generating a matching binding instance for the given uniform node.
  39040. *
  39041. * These bindings are later used in the renderer to create bind groups
  39042. * and layouts.
  39043. *
  39044. * @param {UniformNode} node - The uniform node.
  39045. * @param {string} type - The node data type.
  39046. * @param {string} shaderStage - The shader stage.
  39047. * @param {?string} [name=null] - An optional uniform name.
  39048. * @return {NodeUniform} The node uniform object.
  39049. */
  39050. getUniformFromNode( node, type, shaderStage, name = null ) {
  39051. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39052. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39053. let uniformGPU = nodeData.uniformGPU;
  39054. if ( uniformGPU === undefined ) {
  39055. const group = node.groupNode;
  39056. const groupName = group.name;
  39057. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39058. if ( type === 'texture' ) {
  39059. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39060. bindings.push( uniformGPU );
  39061. } else if ( type === 'cubeTexture' ) {
  39062. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39063. bindings.push( uniformGPU );
  39064. } else if ( type === 'texture3D' ) {
  39065. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39066. bindings.push( uniformGPU );
  39067. } else if ( type === 'buffer' ) {
  39068. node.name = `NodeBuffer_${ node.id }`;
  39069. uniformNode.name = `buffer${ node.id }`;
  39070. const buffer = new NodeUniformBuffer( node, group );
  39071. buffer.name = node.name;
  39072. bindings.push( buffer );
  39073. uniformGPU = buffer;
  39074. } else {
  39075. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39076. let uniformsGroup = uniformsStage[ groupName ];
  39077. if ( uniformsGroup === undefined ) {
  39078. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39079. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39080. uniformsStage[ groupName ] = uniformsGroup;
  39081. bindings.push( uniformsGroup );
  39082. }
  39083. uniformGPU = this.getNodeUniform( uniformNode, type );
  39084. uniformsGroup.addUniform( uniformGPU );
  39085. }
  39086. nodeData.uniformGPU = uniformGPU;
  39087. }
  39088. return uniformNode;
  39089. }
  39090. }
  39091. let _vector2 = null;
  39092. let _color4 = null;
  39093. /**
  39094. * Most of the rendering related logic is implemented in the
  39095. * {@link Renderer} module and related management components.
  39096. * Sometimes it is required though to execute commands which are
  39097. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  39098. * This abstract base class defines an interface that encapsulates
  39099. * all backend-related logic. Derived classes for each backend must
  39100. * implement the interface.
  39101. *
  39102. * @abstract
  39103. * @private
  39104. */
  39105. class Backend {
  39106. /**
  39107. * Constructs a new backend.
  39108. *
  39109. * @param {Object} parameters - An object holding parameters for the backend.
  39110. */
  39111. constructor( parameters = {} ) {
  39112. /**
  39113. * The parameters of the backend.
  39114. *
  39115. * @type {Object}
  39116. */
  39117. this.parameters = Object.assign( {}, parameters );
  39118. /**
  39119. * This weak map holds backend-specific data of objects
  39120. * like textures, attributes or render targets.
  39121. *
  39122. * @type {WeakMap}
  39123. */
  39124. this.data = new WeakMap();
  39125. /**
  39126. * A reference to the renderer.
  39127. *
  39128. * @type {?Renderer}
  39129. * @default null
  39130. */
  39131. this.renderer = null;
  39132. /**
  39133. * A reference to the canvas element the renderer is drawing to.
  39134. *
  39135. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  39136. * @default null
  39137. */
  39138. this.domElement = null;
  39139. /**
  39140. * A reference to the timestamp query pool.
  39141. *
  39142. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  39143. */
  39144. this.timestampQueryPool = {
  39145. 'render': null,
  39146. 'compute': null
  39147. };
  39148. /**
  39149. * Whether to track timestamps with a Timestamp Query API or not.
  39150. *
  39151. * @type {boolean}
  39152. * @default false
  39153. */
  39154. this.trackTimestamp = ( parameters.trackTimestamp === true );
  39155. }
  39156. /**
  39157. * Initializes the backend so it is ready for usage. Concrete backends
  39158. * are supposed to implement their rendering context creation and related
  39159. * operations in this method.
  39160. *
  39161. * @async
  39162. * @param {Renderer} renderer - The renderer.
  39163. * @return {Promise} A Promise that resolves when the backend has been initialized.
  39164. */
  39165. async init( renderer ) {
  39166. this.renderer = renderer;
  39167. }
  39168. /**
  39169. * The coordinate system of the backend.
  39170. *
  39171. * @abstract
  39172. * @type {number}
  39173. * @readonly
  39174. */
  39175. get coordinateSystem() {}
  39176. // render context
  39177. /**
  39178. * This method is executed at the beginning of a render call and
  39179. * can be used by the backend to prepare the state for upcoming
  39180. * draw calls.
  39181. *
  39182. * @abstract
  39183. * @param {RenderContext} renderContext - The render context.
  39184. */
  39185. beginRender( /*renderContext*/ ) {}
  39186. /**
  39187. * This method is executed at the end of a render call and
  39188. * can be used by the backend to finalize work after draw
  39189. * calls.
  39190. *
  39191. * @abstract
  39192. * @param {RenderContext} renderContext - The render context.
  39193. */
  39194. finishRender( /*renderContext*/ ) {}
  39195. /**
  39196. * This method is executed at the beginning of a compute call and
  39197. * can be used by the backend to prepare the state for upcoming
  39198. * compute tasks.
  39199. *
  39200. * @abstract
  39201. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39202. */
  39203. beginCompute( /*computeGroup*/ ) {}
  39204. /**
  39205. * This method is executed at the end of a compute call and
  39206. * can be used by the backend to finalize work after compute
  39207. * tasks.
  39208. *
  39209. * @abstract
  39210. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39211. */
  39212. finishCompute( /*computeGroup*/ ) {}
  39213. // render object
  39214. /**
  39215. * Executes a draw command for the given render object.
  39216. *
  39217. * @abstract
  39218. * @param {RenderObject} renderObject - The render object to draw.
  39219. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  39220. */
  39221. draw( /*renderObject, info*/ ) { }
  39222. // compute node
  39223. /**
  39224. * Executes a compute command for the given compute node.
  39225. *
  39226. * @abstract
  39227. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  39228. * @param {Node} computeNode - The compute node.
  39229. * @param {Array<BindGroup>} bindings - The bindings.
  39230. * @param {ComputePipeline} computePipeline - The compute pipeline.
  39231. */
  39232. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  39233. // program
  39234. /**
  39235. * Creates a shader program from the given programmable stage.
  39236. *
  39237. * @abstract
  39238. * @param {ProgrammableStage} program - The programmable stage.
  39239. */
  39240. createProgram( /*program*/ ) { }
  39241. /**
  39242. * Destroys the shader program of the given programmable stage.
  39243. *
  39244. * @abstract
  39245. * @param {ProgrammableStage} program - The programmable stage.
  39246. */
  39247. destroyProgram( /*program*/ ) { }
  39248. // bindings
  39249. /**
  39250. * Creates bindings from the given bind group definition.
  39251. *
  39252. * @abstract
  39253. * @param {BindGroup} bindGroup - The bind group.
  39254. * @param {Array<BindGroup>} bindings - Array of bind groups.
  39255. * @param {number} cacheIndex - The cache index.
  39256. * @param {number} version - The version.
  39257. */
  39258. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  39259. /**
  39260. * Updates the given bind group definition.
  39261. *
  39262. * @abstract
  39263. * @param {BindGroup} bindGroup - The bind group.
  39264. * @param {Array<BindGroup>} bindings - Array of bind groups.
  39265. * @param {number} cacheIndex - The cache index.
  39266. * @param {number} version - The version.
  39267. */
  39268. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  39269. /**
  39270. * Updates a buffer binding.
  39271. *
  39272. * @abstract
  39273. * @param {Buffer} binding - The buffer binding to update.
  39274. */
  39275. updateBinding( /*binding*/ ) { }
  39276. // pipeline
  39277. /**
  39278. * Creates a render pipeline for the given render object.
  39279. *
  39280. * @abstract
  39281. * @param {RenderObject} renderObject - The render object.
  39282. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  39283. */
  39284. createRenderPipeline( /*renderObject, promises*/ ) { }
  39285. /**
  39286. * Creates a compute pipeline for the given compute node.
  39287. *
  39288. * @abstract
  39289. * @param {ComputePipeline} computePipeline - The compute pipeline.
  39290. * @param {Array<BindGroup>} bindings - The bindings.
  39291. */
  39292. createComputePipeline( /*computePipeline, bindings*/ ) { }
  39293. // cache key
  39294. /**
  39295. * Returns `true` if the render pipeline requires an update.
  39296. *
  39297. * @abstract
  39298. * @param {RenderObject} renderObject - The render object.
  39299. * @return {boolean} Whether the render pipeline requires an update or not.
  39300. */
  39301. needsRenderUpdate( /*renderObject*/ ) { }
  39302. /**
  39303. * Returns a cache key that is used to identify render pipelines.
  39304. *
  39305. * @abstract
  39306. * @param {RenderObject} renderObject - The render object.
  39307. * @return {string} The cache key.
  39308. */
  39309. getRenderCacheKey( /*renderObject*/ ) { }
  39310. // node builder
  39311. /**
  39312. * Returns a node builder for the given render object.
  39313. *
  39314. * @abstract
  39315. * @param {RenderObject} renderObject - The render object.
  39316. * @param {Renderer} renderer - The renderer.
  39317. * @return {NodeBuilder} The node builder.
  39318. */
  39319. createNodeBuilder( /*renderObject, renderer*/ ) { }
  39320. // textures
  39321. /**
  39322. * Creates a GPU sampler for the given texture.
  39323. *
  39324. * @abstract
  39325. * @param {Texture} texture - The texture to create the sampler for.
  39326. */
  39327. createSampler( /*texture*/ ) { }
  39328. /**
  39329. * Destroys the GPU sampler for the given texture.
  39330. *
  39331. * @abstract
  39332. * @param {Texture} texture - The texture to destroy the sampler for.
  39333. */
  39334. destroySampler( /*texture*/ ) {}
  39335. /**
  39336. * Creates a default texture for the given texture that can be used
  39337. * as a placeholder until the actual texture is ready for usage.
  39338. *
  39339. * @abstract
  39340. * @param {Texture} texture - The texture to create a default texture for.
  39341. */
  39342. createDefaultTexture( /*texture*/ ) { }
  39343. /**
  39344. * Defines a texture on the GPU for the given texture object.
  39345. *
  39346. * @abstract
  39347. * @param {Texture} texture - The texture.
  39348. * @param {Object} [options={}] - Optional configuration parameter.
  39349. */
  39350. createTexture( /*texture, options={}*/ ) { }
  39351. /**
  39352. * Uploads the updated texture data to the GPU.
  39353. *
  39354. * @abstract
  39355. * @param {Texture} texture - The texture.
  39356. * @param {Object} [options={}] - Optional configuration parameter.
  39357. */
  39358. updateTexture( /*texture, options = {}*/ ) { }
  39359. /**
  39360. * Generates mipmaps for the given texture.
  39361. *
  39362. * @abstract
  39363. * @param {Texture} texture - The texture.
  39364. */
  39365. generateMipmaps( /*texture*/ ) { }
  39366. /**
  39367. * Destroys the GPU data for the given texture object.
  39368. *
  39369. * @abstract
  39370. * @param {Texture} texture - The texture.
  39371. */
  39372. destroyTexture( /*texture*/ ) { }
  39373. /**
  39374. * Returns texture data as a typed array.
  39375. *
  39376. * @abstract
  39377. * @async
  39378. * @param {Texture} texture - The texture to copy.
  39379. * @param {number} x - The x coordinate of the copy origin.
  39380. * @param {number} y - The y coordinate of the copy origin.
  39381. * @param {number} width - The width of the copy.
  39382. * @param {number} height - The height of the copy.
  39383. * @param {number} faceIndex - The face index.
  39384. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  39385. */
  39386. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  39387. /**
  39388. * Copies data of the given source texture to the given destination texture.
  39389. *
  39390. * @abstract
  39391. * @param {Texture} srcTexture - The source texture.
  39392. * @param {Texture} dstTexture - The destination texture.
  39393. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  39394. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  39395. * @param {number} [srcLevel=0] - The source mip level to copy from.
  39396. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  39397. */
  39398. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  39399. /**
  39400. * Copies the current bound framebuffer to the given texture.
  39401. *
  39402. * @abstract
  39403. * @param {Texture} texture - The destination texture.
  39404. * @param {RenderContext} renderContext - The render context.
  39405. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39406. */
  39407. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  39408. // attributes
  39409. /**
  39410. * Creates the GPU buffer of a shader attribute.
  39411. *
  39412. * @abstract
  39413. * @param {BufferAttribute} attribute - The buffer attribute.
  39414. */
  39415. createAttribute( /*attribute*/ ) { }
  39416. /**
  39417. * Creates the GPU buffer of an indexed shader attribute.
  39418. *
  39419. * @abstract
  39420. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  39421. */
  39422. createIndexAttribute( /*attribute*/ ) { }
  39423. /**
  39424. * Creates the GPU buffer of a storage attribute.
  39425. *
  39426. * @abstract
  39427. * @param {BufferAttribute} attribute - The buffer attribute.
  39428. */
  39429. createStorageAttribute( /*attribute*/ ) { }
  39430. /**
  39431. * Updates the GPU buffer of a shader attribute.
  39432. *
  39433. * @abstract
  39434. * @param {BufferAttribute} attribute - The buffer attribute to update.
  39435. */
  39436. updateAttribute( /*attribute*/ ) { }
  39437. /**
  39438. * Destroys the GPU buffer of a shader attribute.
  39439. *
  39440. * @abstract
  39441. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  39442. */
  39443. destroyAttribute( /*attribute*/ ) { }
  39444. // canvas
  39445. /**
  39446. * Returns the backend's rendering context.
  39447. *
  39448. * @abstract
  39449. * @return {Object} The rendering context.
  39450. */
  39451. getContext() { }
  39452. /**
  39453. * Backends can use this method if they have to run
  39454. * logic when the renderer gets resized.
  39455. *
  39456. * @abstract
  39457. */
  39458. updateSize() { }
  39459. /**
  39460. * Updates the viewport with the values from the given render context.
  39461. *
  39462. * @abstract
  39463. * @param {RenderContext} renderContext - The render context.
  39464. */
  39465. updateViewport( /*renderContext*/ ) {}
  39466. // utils
  39467. /**
  39468. * Returns `true` if the given 3D object is fully occluded by other
  39469. * 3D objects in the scene. Backends must implement this method by using
  39470. * a Occlusion Query API.
  39471. *
  39472. * @abstract
  39473. * @param {RenderContext} renderContext - The render context.
  39474. * @param {Object3D} object - The 3D object to test.
  39475. * @return {boolean} Whether the 3D object is fully occluded or not.
  39476. */
  39477. isOccluded( /*renderContext, object*/ ) {}
  39478. /**
  39479. * Resolves the time stamp for the given render context and type.
  39480. *
  39481. * @async
  39482. * @abstract
  39483. * @param {string} [type='render'] - The type of the time stamp.
  39484. * @return {Promise<number>} A Promise that resolves with the time stamp.
  39485. */
  39486. async resolveTimestampsAsync( type = 'render' ) {
  39487. if ( ! this.trackTimestamp ) {
  39488. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  39489. return;
  39490. }
  39491. const queryPool = this.timestampQueryPool[ type ];
  39492. if ( ! queryPool ) {
  39493. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  39494. return;
  39495. }
  39496. const duration = await queryPool.resolveQueriesAsync();
  39497. this.renderer.info[ type ].timestamp = duration;
  39498. return duration;
  39499. }
  39500. /**
  39501. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  39502. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  39503. *
  39504. * @async
  39505. * @abstract
  39506. * @return {Promise} A Promise that resolves when synchronization has been finished.
  39507. */
  39508. async waitForGPU() {}
  39509. /**
  39510. * This method performs a readback operation by moving buffer data from
  39511. * a storage buffer attribute from the GPU to the CPU.
  39512. *
  39513. * @async
  39514. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39515. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39516. */
  39517. async getArrayBufferAsync( /* attribute */ ) {}
  39518. /**
  39519. * Checks if the given feature is supported by the backend.
  39520. *
  39521. * @async
  39522. * @abstract
  39523. * @param {string} name - The feature's name.
  39524. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  39525. */
  39526. async hasFeatureAsync( /*name*/ ) { }
  39527. /**
  39528. * Checks if the given feature is supported by the backend.
  39529. *
  39530. * @abstract
  39531. * @param {string} name - The feature's name.
  39532. * @return {boolean} Whether the feature is supported or not.
  39533. */
  39534. hasFeature( /*name*/ ) {}
  39535. /**
  39536. * Returns the maximum anisotropy texture filtering value.
  39537. *
  39538. * @abstract
  39539. * @return {number} The maximum anisotropy texture filtering value.
  39540. */
  39541. getMaxAnisotropy() {}
  39542. /**
  39543. * Returns the drawing buffer size.
  39544. *
  39545. * @return {Vector2} The drawing buffer size.
  39546. */
  39547. getDrawingBufferSize() {
  39548. _vector2 = _vector2 || new Vector2();
  39549. return this.renderer.getDrawingBufferSize( _vector2 );
  39550. }
  39551. /**
  39552. * Defines the scissor test.
  39553. *
  39554. * @abstract
  39555. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39556. */
  39557. setScissorTest( /*boolean*/ ) { }
  39558. /**
  39559. * Returns the clear color and alpha into a single
  39560. * color object.
  39561. *
  39562. * @return {Color4} The clear color.
  39563. */
  39564. getClearColor() {
  39565. const renderer = this.renderer;
  39566. _color4 = _color4 || new Color4();
  39567. renderer.getClearColor( _color4 );
  39568. _color4.getRGB( _color4 );
  39569. return _color4;
  39570. }
  39571. /**
  39572. * Returns the DOM element. If no DOM element exists, the backend
  39573. * creates a new one.
  39574. *
  39575. * @return {HTMLCanvasElement} The DOM element.
  39576. */
  39577. getDomElement() {
  39578. let domElement = this.domElement;
  39579. if ( domElement === null ) {
  39580. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39581. // OffscreenCanvas does not have setAttribute, see #22811
  39582. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39583. this.domElement = domElement;
  39584. }
  39585. return domElement;
  39586. }
  39587. /**
  39588. * Sets a dictionary for the given object into the
  39589. * internal data structure.
  39590. *
  39591. * @param {Object} object - The object.
  39592. * @param {Object} value - The dictionary to set.
  39593. */
  39594. set( object, value ) {
  39595. this.data.set( object, value );
  39596. }
  39597. /**
  39598. * Returns the dictionary for the given object.
  39599. *
  39600. * @param {Object} object - The object.
  39601. * @return {Object} The object's dictionary.
  39602. */
  39603. get( object ) {
  39604. let map = this.data.get( object );
  39605. if ( map === undefined ) {
  39606. map = {};
  39607. this.data.set( object, map );
  39608. }
  39609. return map;
  39610. }
  39611. /**
  39612. * Checks if the given object has a dictionary
  39613. * with data defined.
  39614. *
  39615. * @param {Object} object - The object.
  39616. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  39617. */
  39618. has( object ) {
  39619. return this.data.has( object );
  39620. }
  39621. /**
  39622. * Deletes an object from the internal data structure.
  39623. *
  39624. * @param {Object} object - The object to delete.
  39625. */
  39626. delete( object ) {
  39627. this.data.delete( object );
  39628. }
  39629. /**
  39630. * Frees internal resources.
  39631. *
  39632. * @abstract
  39633. */
  39634. dispose() { }
  39635. }
  39636. let _id$1 = 0;
  39637. /**
  39638. * This module is internally used in context of compute shaders.
  39639. * This type of shader is not natively supported in WebGL 2 and
  39640. * thus implemented via Transform Feedback. `DualAttributeData`
  39641. * manages the related data.
  39642. *
  39643. * @private
  39644. */
  39645. class DualAttributeData {
  39646. constructor( attributeData, dualBuffer ) {
  39647. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39648. this.type = attributeData.type;
  39649. this.bufferType = attributeData.bufferType;
  39650. this.pbo = attributeData.pbo;
  39651. this.byteLength = attributeData.byteLength;
  39652. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39653. this.version = attributeData.version;
  39654. this.isInteger = attributeData.isInteger;
  39655. this.activeBufferIndex = 0;
  39656. this.baseId = attributeData.id;
  39657. }
  39658. get id() {
  39659. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39660. }
  39661. get bufferGPU() {
  39662. return this.buffers[ this.activeBufferIndex ];
  39663. }
  39664. get transformBuffer() {
  39665. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39666. }
  39667. switchBuffers() {
  39668. this.activeBufferIndex ^= 1;
  39669. }
  39670. }
  39671. /**
  39672. * A WebGL 2 backend utility module for managing shader attributes.
  39673. *
  39674. * @private
  39675. */
  39676. class WebGLAttributeUtils {
  39677. /**
  39678. * Constructs a new utility object.
  39679. *
  39680. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39681. */
  39682. constructor( backend ) {
  39683. /**
  39684. * A reference to the WebGL 2 backend.
  39685. *
  39686. * @type {WebGLBackend}
  39687. */
  39688. this.backend = backend;
  39689. }
  39690. /**
  39691. * Creates the GPU buffer for the given buffer attribute.
  39692. *
  39693. * @param {BufferAttribute} attribute - The buffer attribute.
  39694. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39695. */
  39696. createAttribute( attribute, bufferType ) {
  39697. const backend = this.backend;
  39698. const { gl } = backend;
  39699. const array = attribute.array;
  39700. const usage = attribute.usage || gl.STATIC_DRAW;
  39701. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39702. const bufferData = backend.get( bufferAttribute );
  39703. let bufferGPU = bufferData.bufferGPU;
  39704. if ( bufferGPU === undefined ) {
  39705. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39706. bufferData.bufferGPU = bufferGPU;
  39707. bufferData.bufferType = bufferType;
  39708. bufferData.version = bufferAttribute.version;
  39709. }
  39710. //attribute.onUploadCallback();
  39711. let type;
  39712. if ( array instanceof Float32Array ) {
  39713. type = gl.FLOAT;
  39714. } else if ( array instanceof Uint16Array ) {
  39715. if ( attribute.isFloat16BufferAttribute ) {
  39716. type = gl.HALF_FLOAT;
  39717. } else {
  39718. type = gl.UNSIGNED_SHORT;
  39719. }
  39720. } else if ( array instanceof Int16Array ) {
  39721. type = gl.SHORT;
  39722. } else if ( array instanceof Uint32Array ) {
  39723. type = gl.UNSIGNED_INT;
  39724. } else if ( array instanceof Int32Array ) {
  39725. type = gl.INT;
  39726. } else if ( array instanceof Int8Array ) {
  39727. type = gl.BYTE;
  39728. } else if ( array instanceof Uint8Array ) {
  39729. type = gl.UNSIGNED_BYTE;
  39730. } else if ( array instanceof Uint8ClampedArray ) {
  39731. type = gl.UNSIGNED_BYTE;
  39732. } else {
  39733. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39734. }
  39735. let attributeData = {
  39736. bufferGPU,
  39737. bufferType,
  39738. type,
  39739. byteLength: array.byteLength,
  39740. bytesPerElement: array.BYTES_PER_ELEMENT,
  39741. version: attribute.version,
  39742. pbo: attribute.pbo,
  39743. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39744. id: _id$1 ++
  39745. };
  39746. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39747. // create buffer for transform feedback use
  39748. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39749. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39750. }
  39751. backend.set( attribute, attributeData );
  39752. }
  39753. /**
  39754. * Updates the GPU buffer of the given buffer attribute.
  39755. *
  39756. * @param {BufferAttribute} attribute - The buffer attribute.
  39757. */
  39758. updateAttribute( attribute ) {
  39759. const backend = this.backend;
  39760. const { gl } = backend;
  39761. const array = attribute.array;
  39762. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39763. const bufferData = backend.get( bufferAttribute );
  39764. const bufferType = bufferData.bufferType;
  39765. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39766. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39767. if ( updateRanges.length === 0 ) {
  39768. // Not using update ranges
  39769. gl.bufferSubData( bufferType, 0, array );
  39770. } else {
  39771. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39772. const range = updateRanges[ i ];
  39773. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39774. array, range.start, range.count );
  39775. }
  39776. bufferAttribute.clearUpdateRanges();
  39777. }
  39778. gl.bindBuffer( bufferType, null );
  39779. bufferData.version = bufferAttribute.version;
  39780. }
  39781. /**
  39782. * Destroys the GPU buffer of the given buffer attribute.
  39783. *
  39784. * @param {BufferAttribute} attribute - The buffer attribute.
  39785. */
  39786. destroyAttribute( attribute ) {
  39787. const backend = this.backend;
  39788. const { gl } = backend;
  39789. if ( attribute.isInterleavedBufferAttribute ) {
  39790. backend.delete( attribute.data );
  39791. }
  39792. const attributeData = backend.get( attribute );
  39793. gl.deleteBuffer( attributeData.bufferGPU );
  39794. backend.delete( attribute );
  39795. }
  39796. /**
  39797. * This method performs a readback operation by moving buffer data from
  39798. * a storage buffer attribute from the GPU to the CPU.
  39799. *
  39800. * @async
  39801. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39802. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39803. */
  39804. async getArrayBufferAsync( attribute ) {
  39805. const backend = this.backend;
  39806. const { gl } = backend;
  39807. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39808. const { bufferGPU } = backend.get( bufferAttribute );
  39809. const array = attribute.array;
  39810. const byteLength = array.byteLength;
  39811. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39812. const writeBuffer = gl.createBuffer();
  39813. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39814. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39815. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39816. await backend.utils._clientWaitAsync();
  39817. const dstBuffer = new attribute.array.constructor( array.length );
  39818. // Ensure the buffer is bound before reading
  39819. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39820. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39821. gl.deleteBuffer( writeBuffer );
  39822. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39823. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39824. return dstBuffer.buffer;
  39825. }
  39826. /**
  39827. * Creates a WebGL buffer with the given data.
  39828. *
  39829. * @private
  39830. * @param {WebGL2RenderingContext} gl - The rendering context.
  39831. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39832. * @param {TypedArray} array - The array of the buffer attribute.
  39833. * @param {GLenum} usage - The usage.
  39834. * @return {WebGLBuffer} The WebGL buffer.
  39835. */
  39836. _createBuffer( gl, bufferType, array, usage ) {
  39837. const bufferGPU = gl.createBuffer();
  39838. gl.bindBuffer( bufferType, bufferGPU );
  39839. gl.bufferData( bufferType, array, usage );
  39840. gl.bindBuffer( bufferType, null );
  39841. return bufferGPU;
  39842. }
  39843. }
  39844. let equationToGL, factorToGL;
  39845. /**
  39846. * A WebGL 2 backend utility module for managing the WebGL state.
  39847. *
  39848. * The major goal of this module is to reduce the number of state changes
  39849. * by caching the WEbGL state with a series of variables. In this way, the
  39850. * renderer only executes state change commands when necessary which
  39851. * improves the overall performance.
  39852. *
  39853. * @private
  39854. */
  39855. class WebGLState {
  39856. /**
  39857. * Constructs a new utility object.
  39858. *
  39859. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39860. */
  39861. constructor( backend ) {
  39862. /**
  39863. * A reference to the WebGL 2 backend.
  39864. *
  39865. * @type {WebGLBackend}
  39866. */
  39867. this.backend = backend;
  39868. /**
  39869. * A reference to the rendering context.
  39870. *
  39871. * @type {WebGL2RenderingContext}
  39872. */
  39873. this.gl = this.backend.gl;
  39874. // Below properties are intended to cache
  39875. // the WebGL state and are not explicitly
  39876. // documented for convenience reasons.
  39877. this.enabled = {};
  39878. this.currentFlipSided = null;
  39879. this.currentCullFace = null;
  39880. this.currentProgram = null;
  39881. this.currentBlendingEnabled = false;
  39882. this.currentBlending = null;
  39883. this.currentBlendSrc = null;
  39884. this.currentBlendDst = null;
  39885. this.currentBlendSrcAlpha = null;
  39886. this.currentBlendDstAlpha = null;
  39887. this.currentPremultipledAlpha = null;
  39888. this.currentPolygonOffsetFactor = null;
  39889. this.currentPolygonOffsetUnits = null;
  39890. this.currentColorMask = null;
  39891. this.currentDepthFunc = null;
  39892. this.currentDepthMask = null;
  39893. this.currentStencilFunc = null;
  39894. this.currentStencilRef = null;
  39895. this.currentStencilFuncMask = null;
  39896. this.currentStencilFail = null;
  39897. this.currentStencilZFail = null;
  39898. this.currentStencilZPass = null;
  39899. this.currentStencilMask = null;
  39900. this.currentLineWidth = null;
  39901. this.currentClippingPlanes = 0;
  39902. this.currentVAO = null;
  39903. this.currentIndex = null;
  39904. this.currentBoundFramebuffers = {};
  39905. this.currentDrawbuffers = new WeakMap();
  39906. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39907. this.currentTextureSlot = null;
  39908. this.currentBoundTextures = {};
  39909. this.currentBoundBufferBases = {};
  39910. this._init();
  39911. }
  39912. /**
  39913. * Inits the state of the utility.
  39914. *
  39915. * @private
  39916. */
  39917. _init() {
  39918. const gl = this.gl;
  39919. // Store only WebGL constants here.
  39920. equationToGL = {
  39921. [ AddEquation ]: gl.FUNC_ADD,
  39922. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39923. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39924. };
  39925. factorToGL = {
  39926. [ ZeroFactor ]: gl.ZERO,
  39927. [ OneFactor ]: gl.ONE,
  39928. [ SrcColorFactor ]: gl.SRC_COLOR,
  39929. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39930. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39931. [ DstColorFactor ]: gl.DST_COLOR,
  39932. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39933. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39934. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39935. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39936. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39937. };
  39938. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  39939. const viewportParam = gl.getParameter( gl.VIEWPORT );
  39940. this.currentScissor = new Vector4().fromArray( scissorParam );
  39941. this.currentViewport = new Vector4().fromArray( viewportParam );
  39942. this._tempVec4 = new Vector4();
  39943. }
  39944. /**
  39945. * Enables the given WebGL capability.
  39946. *
  39947. * This method caches the capability state so
  39948. * `gl.enable()` is only called when necessary.
  39949. *
  39950. * @param {GLenum} id - The capability to enable.
  39951. */
  39952. enable( id ) {
  39953. const { enabled } = this;
  39954. if ( enabled[ id ] !== true ) {
  39955. this.gl.enable( id );
  39956. enabled[ id ] = true;
  39957. }
  39958. }
  39959. /**
  39960. * Disables the given WebGL capability.
  39961. *
  39962. * This method caches the capability state so
  39963. * `gl.disable()` is only called when necessary.
  39964. *
  39965. * @param {GLenum} id - The capability to enable.
  39966. */
  39967. disable( id ) {
  39968. const { enabled } = this;
  39969. if ( enabled[ id ] !== false ) {
  39970. this.gl.disable( id );
  39971. enabled[ id ] = false;
  39972. }
  39973. }
  39974. /**
  39975. * Specifies whether polygons are front- or back-facing
  39976. * by setting the winding orientation.
  39977. *
  39978. * This method caches the state so `gl.frontFace()` is only
  39979. * called when necessary.
  39980. *
  39981. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  39982. */
  39983. setFlipSided( flipSided ) {
  39984. if ( this.currentFlipSided !== flipSided ) {
  39985. const { gl } = this;
  39986. if ( flipSided ) {
  39987. gl.frontFace( gl.CW );
  39988. } else {
  39989. gl.frontFace( gl.CCW );
  39990. }
  39991. this.currentFlipSided = flipSided;
  39992. }
  39993. }
  39994. /**
  39995. * Specifies whether or not front- and/or back-facing
  39996. * polygons can be culled.
  39997. *
  39998. * This method caches the state so `gl.cullFace()` is only
  39999. * called when necessary.
  40000. *
  40001. * @param {number} cullFace - Defines which polygons are candidates for culling.
  40002. */
  40003. setCullFace( cullFace ) {
  40004. const { gl } = this;
  40005. if ( cullFace !== CullFaceNone ) {
  40006. this.enable( gl.CULL_FACE );
  40007. if ( cullFace !== this.currentCullFace ) {
  40008. if ( cullFace === CullFaceBack ) {
  40009. gl.cullFace( gl.BACK );
  40010. } else if ( cullFace === CullFaceFront ) {
  40011. gl.cullFace( gl.FRONT );
  40012. } else {
  40013. gl.cullFace( gl.FRONT_AND_BACK );
  40014. }
  40015. }
  40016. } else {
  40017. this.disable( gl.CULL_FACE );
  40018. }
  40019. this.currentCullFace = cullFace;
  40020. }
  40021. /**
  40022. * Specifies the width of line primitives.
  40023. *
  40024. * This method caches the state so `gl.lineWidth()` is only
  40025. * called when necessary.
  40026. *
  40027. * @param {number} width - The line width.
  40028. */
  40029. setLineWidth( width ) {
  40030. const { currentLineWidth, gl } = this;
  40031. if ( width !== currentLineWidth ) {
  40032. gl.lineWidth( width );
  40033. this.currentLineWidth = width;
  40034. }
  40035. }
  40036. /**
  40037. * Defines the blending.
  40038. *
  40039. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  40040. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  40041. *
  40042. * @param {number} blending - The blending type.
  40043. * @param {number} blendEquation - The blending equation.
  40044. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  40045. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  40046. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  40047. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  40048. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  40049. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  40050. */
  40051. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  40052. const { gl } = this;
  40053. if ( blending === NoBlending ) {
  40054. if ( this.currentBlendingEnabled === true ) {
  40055. this.disable( gl.BLEND );
  40056. this.currentBlendingEnabled = false;
  40057. }
  40058. return;
  40059. }
  40060. if ( this.currentBlendingEnabled === false ) {
  40061. this.enable( gl.BLEND );
  40062. this.currentBlendingEnabled = true;
  40063. }
  40064. if ( blending !== CustomBlending ) {
  40065. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  40066. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  40067. gl.blendEquation( gl.FUNC_ADD );
  40068. this.currentBlendEquation = AddEquation;
  40069. this.currentBlendEquationAlpha = AddEquation;
  40070. }
  40071. if ( premultipliedAlpha ) {
  40072. switch ( blending ) {
  40073. case NormalBlending:
  40074. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40075. break;
  40076. case AdditiveBlending:
  40077. gl.blendFunc( gl.ONE, gl.ONE );
  40078. break;
  40079. case SubtractiveBlending:
  40080. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40081. break;
  40082. case MultiplyBlending:
  40083. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  40084. break;
  40085. default:
  40086. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40087. break;
  40088. }
  40089. } else {
  40090. switch ( blending ) {
  40091. case NormalBlending:
  40092. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40093. break;
  40094. case AdditiveBlending:
  40095. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  40096. break;
  40097. case SubtractiveBlending:
  40098. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40099. break;
  40100. case MultiplyBlending:
  40101. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  40102. break;
  40103. default:
  40104. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40105. break;
  40106. }
  40107. }
  40108. this.currentBlendSrc = null;
  40109. this.currentBlendDst = null;
  40110. this.currentBlendSrcAlpha = null;
  40111. this.currentBlendDstAlpha = null;
  40112. this.currentBlending = blending;
  40113. this.currentPremultipledAlpha = premultipliedAlpha;
  40114. }
  40115. return;
  40116. }
  40117. // custom blending
  40118. blendEquationAlpha = blendEquationAlpha || blendEquation;
  40119. blendSrcAlpha = blendSrcAlpha || blendSrc;
  40120. blendDstAlpha = blendDstAlpha || blendDst;
  40121. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  40122. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  40123. this.currentBlendEquation = blendEquation;
  40124. this.currentBlendEquationAlpha = blendEquationAlpha;
  40125. }
  40126. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  40127. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  40128. this.currentBlendSrc = blendSrc;
  40129. this.currentBlendDst = blendDst;
  40130. this.currentBlendSrcAlpha = blendSrcAlpha;
  40131. this.currentBlendDstAlpha = blendDstAlpha;
  40132. }
  40133. this.currentBlending = blending;
  40134. this.currentPremultipledAlpha = false;
  40135. }
  40136. /**
  40137. * Specifies whether colors can be written when rendering
  40138. * into a framebuffer or not.
  40139. *
  40140. * This method caches the state so `gl.colorMask()` is only
  40141. * called when necessary.
  40142. *
  40143. * @param {boolean} colorMask - The color mask.
  40144. */
  40145. setColorMask( colorMask ) {
  40146. if ( this.currentColorMask !== colorMask ) {
  40147. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  40148. this.currentColorMask = colorMask;
  40149. }
  40150. }
  40151. /**
  40152. * Specifies whether the depth test is enabled or not.
  40153. *
  40154. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  40155. */
  40156. setDepthTest( depthTest ) {
  40157. const { gl } = this;
  40158. if ( depthTest ) {
  40159. this.enable( gl.DEPTH_TEST );
  40160. } else {
  40161. this.disable( gl.DEPTH_TEST );
  40162. }
  40163. }
  40164. /**
  40165. * Specifies whether depth values can be written when rendering
  40166. * into a framebuffer or not.
  40167. *
  40168. * This method caches the state so `gl.depthMask()` is only
  40169. * called when necessary.
  40170. *
  40171. * @param {boolean} depthMask - The depth mask.
  40172. */
  40173. setDepthMask( depthMask ) {
  40174. if ( this.currentDepthMask !== depthMask ) {
  40175. this.gl.depthMask( depthMask );
  40176. this.currentDepthMask = depthMask;
  40177. }
  40178. }
  40179. /**
  40180. * Specifies the depth compare function.
  40181. *
  40182. * This method caches the state so `gl.depthFunc()` is only
  40183. * called when necessary.
  40184. *
  40185. * @param {number} depthFunc - The depth compare function.
  40186. */
  40187. setDepthFunc( depthFunc ) {
  40188. if ( this.currentDepthFunc !== depthFunc ) {
  40189. const { gl } = this;
  40190. switch ( depthFunc ) {
  40191. case NeverDepth:
  40192. gl.depthFunc( gl.NEVER );
  40193. break;
  40194. case AlwaysDepth:
  40195. gl.depthFunc( gl.ALWAYS );
  40196. break;
  40197. case LessDepth:
  40198. gl.depthFunc( gl.LESS );
  40199. break;
  40200. case LessEqualDepth:
  40201. gl.depthFunc( gl.LEQUAL );
  40202. break;
  40203. case EqualDepth:
  40204. gl.depthFunc( gl.EQUAL );
  40205. break;
  40206. case GreaterEqualDepth:
  40207. gl.depthFunc( gl.GEQUAL );
  40208. break;
  40209. case GreaterDepth:
  40210. gl.depthFunc( gl.GREATER );
  40211. break;
  40212. case NotEqualDepth:
  40213. gl.depthFunc( gl.NOTEQUAL );
  40214. break;
  40215. default:
  40216. gl.depthFunc( gl.LEQUAL );
  40217. }
  40218. this.currentDepthFunc = depthFunc;
  40219. }
  40220. }
  40221. /**
  40222. * Specifies the scissor box.
  40223. *
  40224. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  40225. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  40226. * @param {number} width - The width of the viewport.
  40227. * @param {number} height - The height of the viewport.
  40228. *
  40229. */
  40230. scissor( x, y, width, height ) {
  40231. const scissor = this._tempVec4.set( x, y, width, height );
  40232. if ( this.currentScissor.equals( scissor ) === false ) {
  40233. const { gl } = this;
  40234. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  40235. this.currentScissor.copy( scissor );
  40236. }
  40237. }
  40238. /**
  40239. * Specifies the viewport.
  40240. *
  40241. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  40242. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  40243. * @param {number} width - The width of the viewport.
  40244. * @param {number} height - The height of the viewport.
  40245. *
  40246. */
  40247. viewport( x, y, width, height ) {
  40248. const viewport = this._tempVec4.set( x, y, width, height );
  40249. if ( this.currentViewport.equals( viewport ) === false ) {
  40250. const { gl } = this;
  40251. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  40252. this.currentViewport.copy( viewport );
  40253. }
  40254. }
  40255. /**
  40256. * Defines the scissor test.
  40257. *
  40258. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40259. */
  40260. setScissorTest( boolean ) {
  40261. const gl = this.gl;
  40262. if ( boolean ) {
  40263. gl.enable( gl.SCISSOR_TEST );
  40264. } else {
  40265. gl.disable( gl.SCISSOR_TEST );
  40266. }
  40267. }
  40268. /**
  40269. * Specifies whether the stencil test is enabled or not.
  40270. *
  40271. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  40272. */
  40273. setStencilTest( stencilTest ) {
  40274. const { gl } = this;
  40275. if ( stencilTest ) {
  40276. this.enable( gl.STENCIL_TEST );
  40277. } else {
  40278. this.disable( gl.STENCIL_TEST );
  40279. }
  40280. }
  40281. /**
  40282. * Specifies whether stencil values can be written when rendering
  40283. * into a framebuffer or not.
  40284. *
  40285. * This method caches the state so `gl.stencilMask()` is only
  40286. * called when necessary.
  40287. *
  40288. * @param {boolean} stencilMask - The stencil mask.
  40289. */
  40290. setStencilMask( stencilMask ) {
  40291. if ( this.currentStencilMask !== stencilMask ) {
  40292. this.gl.stencilMask( stencilMask );
  40293. this.currentStencilMask = stencilMask;
  40294. }
  40295. }
  40296. /**
  40297. * Specifies whether the stencil test functions.
  40298. *
  40299. * This method caches the state so `gl.stencilFunc()` is only
  40300. * called when necessary.
  40301. *
  40302. * @param {number} stencilFunc - The stencil compare function.
  40303. * @param {number} stencilRef - The reference value for the stencil test.
  40304. * @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.
  40305. */
  40306. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  40307. if ( this.currentStencilFunc !== stencilFunc ||
  40308. this.currentStencilRef !== stencilRef ||
  40309. this.currentStencilFuncMask !== stencilMask ) {
  40310. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  40311. this.currentStencilFunc = stencilFunc;
  40312. this.currentStencilRef = stencilRef;
  40313. this.currentStencilFuncMask = stencilMask;
  40314. }
  40315. }
  40316. /**
  40317. * Specifies whether the stencil test operation.
  40318. *
  40319. * This method caches the state so `gl.stencilOp()` is only
  40320. * called when necessary.
  40321. *
  40322. * @param {number} stencilFail - The function to use when the stencil test fails.
  40323. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  40324. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  40325. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  40326. */
  40327. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  40328. if ( this.currentStencilFail !== stencilFail ||
  40329. this.currentStencilZFail !== stencilZFail ||
  40330. this.currentStencilZPass !== stencilZPass ) {
  40331. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  40332. this.currentStencilFail = stencilFail;
  40333. this.currentStencilZFail = stencilZFail;
  40334. this.currentStencilZPass = stencilZPass;
  40335. }
  40336. }
  40337. /**
  40338. * Configures the WebGL state for the given material.
  40339. *
  40340. * @param {Material} material - The material to configure the state for.
  40341. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  40342. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  40343. */
  40344. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  40345. const { gl } = this;
  40346. material.side === DoubleSide
  40347. ? this.disable( gl.CULL_FACE )
  40348. : this.enable( gl.CULL_FACE );
  40349. let flipSided = ( material.side === BackSide );
  40350. if ( frontFaceCW ) flipSided = ! flipSided;
  40351. this.setFlipSided( flipSided );
  40352. ( material.blending === NormalBlending && material.transparent === false )
  40353. ? this.setBlending( NoBlending )
  40354. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  40355. this.setDepthFunc( material.depthFunc );
  40356. this.setDepthTest( material.depthTest );
  40357. this.setDepthMask( material.depthWrite );
  40358. this.setColorMask( material.colorWrite );
  40359. const stencilWrite = material.stencilWrite;
  40360. this.setStencilTest( stencilWrite );
  40361. if ( stencilWrite ) {
  40362. this.setStencilMask( material.stencilWriteMask );
  40363. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  40364. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  40365. }
  40366. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  40367. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  40368. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  40369. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  40370. if ( hardwareClippingPlanes > 0 ) {
  40371. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  40372. const CLIP_DISTANCE0_WEBGL = 0x3000;
  40373. for ( let i = 0; i < 8; i ++ ) {
  40374. if ( i < hardwareClippingPlanes ) {
  40375. this.enable( CLIP_DISTANCE0_WEBGL + i );
  40376. } else {
  40377. this.disable( CLIP_DISTANCE0_WEBGL + i );
  40378. }
  40379. }
  40380. }
  40381. }
  40382. }
  40383. /**
  40384. * Specifies the polygon offset.
  40385. *
  40386. * This method caches the state so `gl.polygonOffset()` is only
  40387. * called when necessary.
  40388. *
  40389. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  40390. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  40391. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  40392. */
  40393. setPolygonOffset( polygonOffset, factor, units ) {
  40394. const { gl } = this;
  40395. if ( polygonOffset ) {
  40396. this.enable( gl.POLYGON_OFFSET_FILL );
  40397. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  40398. gl.polygonOffset( factor, units );
  40399. this.currentPolygonOffsetFactor = factor;
  40400. this.currentPolygonOffsetUnits = units;
  40401. }
  40402. } else {
  40403. this.disable( gl.POLYGON_OFFSET_FILL );
  40404. }
  40405. }
  40406. /**
  40407. * Defines the usage of the given WebGL program.
  40408. *
  40409. * This method caches the state so `gl.useProgram()` is only
  40410. * called when necessary.
  40411. *
  40412. * @param {WebGLProgram} program - The WebGL program to use.
  40413. * @return {boolean} Whether a program change has been executed or not.
  40414. */
  40415. useProgram( program ) {
  40416. if ( this.currentProgram !== program ) {
  40417. this.gl.useProgram( program );
  40418. this.currentProgram = program;
  40419. return true;
  40420. }
  40421. return false;
  40422. }
  40423. /**
  40424. * Sets the vertex state by binding the given VAO and element buffer.
  40425. *
  40426. * @param {WebGLVertexArrayObject} vao - The VAO.
  40427. * @param {WebGLBuffer} indexBuffer - The index buffer.
  40428. * @return {boolean} Whether a vertex state has been changed or not.
  40429. */
  40430. setVertexState( vao, indexBuffer = null ) {
  40431. const gl = this.gl;
  40432. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  40433. gl.bindVertexArray( vao );
  40434. if ( indexBuffer !== null ) {
  40435. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  40436. }
  40437. this.currentVAO = vao;
  40438. this.currentIndex = indexBuffer;
  40439. return true;
  40440. }
  40441. return false;
  40442. }
  40443. /**
  40444. * Resets the vertex array state by resetting the VAO and element buffer.
  40445. */
  40446. resetVertexState() {
  40447. const gl = this.gl;
  40448. gl.bindVertexArray( null );
  40449. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  40450. this.currentVAO = null;
  40451. this.currentIndex = null;
  40452. }
  40453. // framebuffer
  40454. /**
  40455. * Binds the given framebuffer.
  40456. *
  40457. * This method caches the state so `gl.bindFramebuffer()` is only
  40458. * called when necessary.
  40459. *
  40460. * @param {number} target - The binding point (target).
  40461. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  40462. * @return {boolean} Whether a bind has been executed or not.
  40463. */
  40464. bindFramebuffer( target, framebuffer ) {
  40465. const { gl, currentBoundFramebuffers } = this;
  40466. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  40467. gl.bindFramebuffer( target, framebuffer );
  40468. currentBoundFramebuffers[ target ] = framebuffer;
  40469. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  40470. if ( target === gl.DRAW_FRAMEBUFFER ) {
  40471. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  40472. }
  40473. if ( target === gl.FRAMEBUFFER ) {
  40474. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  40475. }
  40476. return true;
  40477. }
  40478. return false;
  40479. }
  40480. /**
  40481. * Defines draw buffers to which fragment colors are written into.
  40482. * Configures the MRT setup of custom framebuffers.
  40483. *
  40484. * This method caches the state so `gl.drawBuffers()` is only
  40485. * called when necessary.
  40486. *
  40487. * @param {RenderContext} renderContext - The render context.
  40488. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  40489. */
  40490. drawBuffers( renderContext, framebuffer ) {
  40491. const { gl } = this;
  40492. let drawBuffers = [];
  40493. let needsUpdate = false;
  40494. if ( renderContext.textures !== null ) {
  40495. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  40496. if ( drawBuffers === undefined ) {
  40497. drawBuffers = [];
  40498. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  40499. }
  40500. const textures = renderContext.textures;
  40501. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  40502. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  40503. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  40504. }
  40505. drawBuffers.length = textures.length;
  40506. needsUpdate = true;
  40507. }
  40508. } else {
  40509. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  40510. drawBuffers[ 0 ] = gl.BACK;
  40511. needsUpdate = true;
  40512. }
  40513. }
  40514. if ( needsUpdate ) {
  40515. gl.drawBuffers( drawBuffers );
  40516. }
  40517. }
  40518. // texture
  40519. /**
  40520. * Makes the given texture unit active.
  40521. *
  40522. * This method caches the state so `gl.activeTexture()` is only
  40523. * called when necessary.
  40524. *
  40525. * @param {number} webglSlot - The texture unit to make active.
  40526. */
  40527. activeTexture( webglSlot ) {
  40528. const { gl, currentTextureSlot, maxTextures } = this;
  40529. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40530. if ( currentTextureSlot !== webglSlot ) {
  40531. gl.activeTexture( webglSlot );
  40532. this.currentTextureSlot = webglSlot;
  40533. }
  40534. }
  40535. /**
  40536. * Binds the given WebGL texture to a target.
  40537. *
  40538. * This method caches the state so `gl.bindTexture()` is only
  40539. * called when necessary.
  40540. *
  40541. * @param {number} webglType - The binding point (target).
  40542. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  40543. * @param {number} webglSlot - The texture.
  40544. */
  40545. bindTexture( webglType, webglTexture, webglSlot ) {
  40546. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  40547. if ( webglSlot === undefined ) {
  40548. if ( currentTextureSlot === null ) {
  40549. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40550. } else {
  40551. webglSlot = currentTextureSlot;
  40552. }
  40553. }
  40554. let boundTexture = currentBoundTextures[ webglSlot ];
  40555. if ( boundTexture === undefined ) {
  40556. boundTexture = { type: undefined, texture: undefined };
  40557. currentBoundTextures[ webglSlot ] = boundTexture;
  40558. }
  40559. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  40560. if ( currentTextureSlot !== webglSlot ) {
  40561. gl.activeTexture( webglSlot );
  40562. this.currentTextureSlot = webglSlot;
  40563. }
  40564. gl.bindTexture( webglType, webglTexture );
  40565. boundTexture.type = webglType;
  40566. boundTexture.texture = webglTexture;
  40567. }
  40568. }
  40569. /**
  40570. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  40571. *
  40572. * This method caches the state so `gl.bindBufferBase()` is only
  40573. * called when necessary.
  40574. *
  40575. * @param {number} target - The target for the bind operation.
  40576. * @param {number} index - The index of the target.
  40577. * @param {WebGLBuffer} buffer - The WebGL buffer.
  40578. * @return {boolean} Whether a bind has been executed or not.
  40579. */
  40580. bindBufferBase( target, index, buffer ) {
  40581. const { gl } = this;
  40582. const key = `${target}-${index}`;
  40583. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  40584. gl.bindBufferBase( target, index, buffer );
  40585. this.currentBoundBufferBases[ key ] = buffer;
  40586. return true;
  40587. }
  40588. return false;
  40589. }
  40590. /**
  40591. * Unbinds the current bound texture.
  40592. *
  40593. * This method caches the state so `gl.bindTexture()` is only
  40594. * called when necessary.
  40595. */
  40596. unbindTexture() {
  40597. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40598. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40599. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40600. gl.bindTexture( boundTexture.type, null );
  40601. boundTexture.type = undefined;
  40602. boundTexture.texture = undefined;
  40603. }
  40604. }
  40605. }
  40606. /**
  40607. * A WebGL 2 backend utility module with common helpers.
  40608. *
  40609. * @private
  40610. */
  40611. class WebGLUtils {
  40612. /**
  40613. * Constructs a new utility object.
  40614. *
  40615. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40616. */
  40617. constructor( backend ) {
  40618. /**
  40619. * A reference to the WebGL 2 backend.
  40620. *
  40621. * @type {WebGLBackend}
  40622. */
  40623. this.backend = backend;
  40624. /**
  40625. * A reference to the rendering context.
  40626. *
  40627. * @type {WebGL2RenderingContext}
  40628. */
  40629. this.gl = this.backend.gl;
  40630. /**
  40631. * A reference to a backend module holding extension-related
  40632. * utility functions.
  40633. *
  40634. * @type {WebGLExtensions}
  40635. */
  40636. this.extensions = backend.extensions;
  40637. }
  40638. /**
  40639. * Converts the given three.js constant into a WebGL constant.
  40640. * The method currently supports the conversion of texture formats
  40641. * and types.
  40642. *
  40643. * @param {number} p - The three.js constant.
  40644. * @param {string} [colorSpace=NoColorSpace] - The color space.
  40645. * @return {?number} The corresponding WebGL constant.
  40646. */
  40647. convert( p, colorSpace = NoColorSpace ) {
  40648. const { gl, extensions } = this;
  40649. let extension;
  40650. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40651. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40652. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40653. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40654. if ( p === ByteType ) return gl.BYTE;
  40655. if ( p === ShortType ) return gl.SHORT;
  40656. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40657. if ( p === IntType ) return gl.INT;
  40658. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40659. if ( p === FloatType ) return gl.FLOAT;
  40660. if ( p === HalfFloatType ) {
  40661. return gl.HALF_FLOAT;
  40662. }
  40663. if ( p === AlphaFormat ) return gl.ALPHA;
  40664. if ( p === RGBFormat ) return gl.RGB;
  40665. if ( p === RGBAFormat ) return gl.RGBA;
  40666. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40667. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40668. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40669. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40670. // WebGL2 formats.
  40671. if ( p === RedFormat ) return gl.RED;
  40672. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40673. if ( p === RGFormat ) return gl.RG;
  40674. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40675. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40676. // S3TC
  40677. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40678. if ( colorSpace === SRGBColorSpace ) {
  40679. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40680. if ( extension !== null ) {
  40681. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40682. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40683. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40684. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40685. } else {
  40686. return null;
  40687. }
  40688. } else {
  40689. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40690. if ( extension !== null ) {
  40691. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40692. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40693. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40694. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40695. } else {
  40696. return null;
  40697. }
  40698. }
  40699. }
  40700. // PVRTC
  40701. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40702. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40703. if ( extension !== null ) {
  40704. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40705. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40706. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40707. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40708. } else {
  40709. return null;
  40710. }
  40711. }
  40712. // ETC
  40713. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40714. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40715. if ( extension !== null ) {
  40716. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40717. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40718. } else {
  40719. return null;
  40720. }
  40721. }
  40722. // ASTC
  40723. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40724. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40725. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40726. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40727. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40728. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40729. if ( extension !== null ) {
  40730. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40731. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40732. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40733. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40734. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40735. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40736. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40737. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40738. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40739. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40740. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40741. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40742. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40743. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40744. } else {
  40745. return null;
  40746. }
  40747. }
  40748. // BPTC
  40749. if ( p === RGBA_BPTC_Format ) {
  40750. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40751. if ( extension !== null ) {
  40752. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40753. } else {
  40754. return null;
  40755. }
  40756. }
  40757. // RGTC
  40758. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40759. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40760. if ( extension !== null ) {
  40761. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40762. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40763. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40764. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40765. } else {
  40766. return null;
  40767. }
  40768. }
  40769. //
  40770. if ( p === UnsignedInt248Type ) {
  40771. return gl.UNSIGNED_INT_24_8;
  40772. }
  40773. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40774. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40775. }
  40776. /**
  40777. * This method can be used to synchronize the CPU with the GPU by waiting until
  40778. * ongoing GPU commands have been completed.
  40779. *
  40780. * @private
  40781. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  40782. */
  40783. _clientWaitAsync() {
  40784. const { gl } = this;
  40785. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40786. gl.flush();
  40787. return new Promise( ( resolve, reject ) => {
  40788. function test() {
  40789. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40790. if ( res === gl.WAIT_FAILED ) {
  40791. gl.deleteSync( sync );
  40792. reject();
  40793. return;
  40794. }
  40795. if ( res === gl.TIMEOUT_EXPIRED ) {
  40796. requestAnimationFrame( test );
  40797. return;
  40798. }
  40799. gl.deleteSync( sync );
  40800. resolve();
  40801. }
  40802. test();
  40803. } );
  40804. }
  40805. }
  40806. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40807. /**
  40808. * A WebGL 2 backend utility module for managing textures.
  40809. *
  40810. * @private
  40811. */
  40812. class WebGLTextureUtils {
  40813. /**
  40814. * Constructs a new utility object.
  40815. *
  40816. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40817. */
  40818. constructor( backend ) {
  40819. /**
  40820. * A reference to the WebGL 2 backend.
  40821. *
  40822. * @type {WebGLBackend}
  40823. */
  40824. this.backend = backend;
  40825. /**
  40826. * A reference to the rendering context.
  40827. *
  40828. * @type {WebGL2RenderingContext}
  40829. */
  40830. this.gl = backend.gl;
  40831. /**
  40832. * A reference to a backend module holding extension-related
  40833. * utility functions.
  40834. *
  40835. * @type {WebGLExtensions}
  40836. */
  40837. this.extensions = backend.extensions;
  40838. /**
  40839. * A dictionary for managing default textures. The key
  40840. * is the binding point (target), the value the WEbGL texture object.
  40841. *
  40842. * @type {Object<GLenum,WebGLTexture>}
  40843. */
  40844. this.defaultTextures = {};
  40845. if ( initialized === false ) {
  40846. this._init();
  40847. initialized = true;
  40848. }
  40849. }
  40850. /**
  40851. * Inits the state of the utility.
  40852. *
  40853. * @private
  40854. */
  40855. _init() {
  40856. const gl = this.gl;
  40857. // Store only WebGL constants here.
  40858. wrappingToGL = {
  40859. [ RepeatWrapping ]: gl.REPEAT,
  40860. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40861. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40862. };
  40863. filterToGL = {
  40864. [ NearestFilter ]: gl.NEAREST,
  40865. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40866. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40867. [ LinearFilter ]: gl.LINEAR,
  40868. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40869. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40870. };
  40871. compareToGL = {
  40872. [ NeverCompare ]: gl.NEVER,
  40873. [ AlwaysCompare ]: gl.ALWAYS,
  40874. [ LessCompare ]: gl.LESS,
  40875. [ LessEqualCompare ]: gl.LEQUAL,
  40876. [ EqualCompare ]: gl.EQUAL,
  40877. [ GreaterEqualCompare ]: gl.GEQUAL,
  40878. [ GreaterCompare ]: gl.GREATER,
  40879. [ NotEqualCompare ]: gl.NOTEQUAL
  40880. };
  40881. }
  40882. /**
  40883. * Returns the native texture type for the given texture.
  40884. *
  40885. * @param {Texture} texture - The texture.
  40886. * @return {GLenum} The native texture type.
  40887. */
  40888. getGLTextureType( texture ) {
  40889. const { gl } = this;
  40890. let glTextureType;
  40891. if ( texture.isCubeTexture === true ) {
  40892. glTextureType = gl.TEXTURE_CUBE_MAP;
  40893. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40894. glTextureType = gl.TEXTURE_2D_ARRAY;
  40895. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40896. glTextureType = gl.TEXTURE_3D;
  40897. } else {
  40898. glTextureType = gl.TEXTURE_2D;
  40899. }
  40900. return glTextureType;
  40901. }
  40902. /**
  40903. * Returns the native texture type for the given texture.
  40904. *
  40905. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  40906. * @param {GLenum} glFormat - The WebGL format.
  40907. * @param {GLenum} glType - The WebGL type.
  40908. * @param {string} colorSpace - The texture's color space.
  40909. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  40910. * @return {GLenum} The internal format.
  40911. */
  40912. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40913. const { gl, extensions } = this;
  40914. if ( internalFormatName !== null ) {
  40915. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40916. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40917. }
  40918. let internalFormat = glFormat;
  40919. if ( glFormat === gl.RED ) {
  40920. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40921. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40922. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40923. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40924. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40925. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40926. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40927. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40928. }
  40929. if ( glFormat === gl.RED_INTEGER ) {
  40930. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40931. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40932. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40933. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40934. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40935. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40936. }
  40937. if ( glFormat === gl.RG ) {
  40938. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40939. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40940. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40941. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40942. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40943. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40944. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40945. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40946. }
  40947. if ( glFormat === gl.RG_INTEGER ) {
  40948. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40949. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40950. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40951. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40952. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40953. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40954. }
  40955. if ( glFormat === gl.RGB ) {
  40956. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40957. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40958. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40959. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40960. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40961. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40962. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40963. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40964. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40965. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40966. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40967. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40968. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40969. }
  40970. if ( glFormat === gl.RGB_INTEGER ) {
  40971. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40972. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40973. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40974. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40975. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40976. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40977. }
  40978. if ( glFormat === gl.RGBA ) {
  40979. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40980. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40981. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40982. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40983. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40984. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40985. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40986. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40987. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40988. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40989. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40990. }
  40991. if ( glFormat === gl.RGBA_INTEGER ) {
  40992. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40993. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40994. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40995. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40996. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40997. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40998. }
  40999. if ( glFormat === gl.DEPTH_COMPONENT ) {
  41000. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  41001. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  41002. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  41003. }
  41004. if ( glFormat === gl.DEPTH_STENCIL ) {
  41005. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  41006. }
  41007. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  41008. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  41009. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  41010. extensions.get( 'EXT_color_buffer_float' );
  41011. }
  41012. return internalFormat;
  41013. }
  41014. /**
  41015. * Sets the texture parameters for the given texture.
  41016. *
  41017. * @param {GLenum} textureType - The texture type.
  41018. * @param {Texture} texture - The texture.
  41019. */
  41020. setTextureParameters( textureType, texture ) {
  41021. const { gl, extensions, backend } = this;
  41022. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  41023. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  41024. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  41025. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  41026. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  41027. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  41028. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  41029. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  41030. }
  41031. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  41032. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  41033. // follow WebGPU backend mapping for texture filtering
  41034. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  41035. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  41036. if ( texture.compareFunction ) {
  41037. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  41038. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  41039. }
  41040. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41041. if ( texture.magFilter === NearestFilter ) return;
  41042. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  41043. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  41044. if ( texture.anisotropy > 1 ) {
  41045. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41046. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  41047. }
  41048. }
  41049. }
  41050. /**
  41051. * Creates a default texture for the given texture that can be used
  41052. * as a placeholder until the actual texture is ready for usage.
  41053. *
  41054. * @param {Texture} texture - The texture to create a default texture for.
  41055. */
  41056. createDefaultTexture( texture ) {
  41057. const { gl, backend, defaultTextures } = this;
  41058. const glTextureType = this.getGLTextureType( texture );
  41059. let textureGPU = defaultTextures[ glTextureType ];
  41060. if ( textureGPU === undefined ) {
  41061. textureGPU = gl.createTexture();
  41062. backend.state.bindTexture( glTextureType, textureGPU );
  41063. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  41064. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  41065. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  41066. defaultTextures[ glTextureType ] = textureGPU;
  41067. }
  41068. backend.set( texture, {
  41069. textureGPU,
  41070. glTextureType,
  41071. isDefault: true
  41072. } );
  41073. }
  41074. /**
  41075. * Defines a texture on the GPU for the given texture object.
  41076. *
  41077. * @param {Texture} texture - The texture.
  41078. * @param {Object} [options={}] - Optional configuration parameter.
  41079. * @return {undefined}
  41080. */
  41081. createTexture( texture, options ) {
  41082. const { gl, backend } = this;
  41083. const { levels, width, height, depth } = options;
  41084. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  41085. const glType = backend.utils.convert( texture.type );
  41086. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  41087. const textureGPU = gl.createTexture();
  41088. const glTextureType = this.getGLTextureType( texture );
  41089. backend.state.bindTexture( glTextureType, textureGPU );
  41090. this.setTextureParameters( glTextureType, texture );
  41091. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  41092. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  41093. } else if ( texture.isData3DTexture ) {
  41094. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  41095. } else if ( ! texture.isVideoTexture ) {
  41096. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  41097. }
  41098. backend.set( texture, {
  41099. textureGPU,
  41100. glTextureType,
  41101. glFormat,
  41102. glType,
  41103. glInternalFormat
  41104. } );
  41105. }
  41106. /**
  41107. * Uploads texture buffer data to the GPU memory.
  41108. *
  41109. * @param {WebGLBuffer} buffer - The buffer data.
  41110. * @param {Texture} texture - The texture,
  41111. */
  41112. copyBufferToTexture( buffer, texture ) {
  41113. const { gl, backend } = this;
  41114. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  41115. const { width, height } = texture.source.data;
  41116. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  41117. backend.state.bindTexture( glTextureType, textureGPU );
  41118. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  41119. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  41120. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  41121. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  41122. backend.state.unbindTexture();
  41123. // debug
  41124. // const framebuffer = gl.createFramebuffer();
  41125. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  41126. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  41127. // const readout = new Float32Array( width * height * 4 );
  41128. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  41129. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  41130. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  41131. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  41132. // console.log( readout );
  41133. }
  41134. /**
  41135. * Uploads the updated texture data to the GPU.
  41136. *
  41137. * @param {Texture} texture - The texture.
  41138. * @param {Object} [options={}] - Optional configuration parameter.
  41139. */
  41140. updateTexture( texture, options ) {
  41141. const { gl } = this;
  41142. const { width, height } = options;
  41143. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  41144. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  41145. return;
  41146. const getImage = ( source ) => {
  41147. if ( source.isDataTexture ) {
  41148. return source.image.data;
  41149. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  41150. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  41151. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  41152. source instanceof OffscreenCanvas ) {
  41153. return source;
  41154. }
  41155. return source.data;
  41156. };
  41157. this.backend.state.bindTexture( glTextureType, textureGPU );
  41158. this.setTextureParameters( glTextureType, texture );
  41159. if ( texture.isCompressedTexture ) {
  41160. const mipmaps = texture.mipmaps;
  41161. const image = options.image;
  41162. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41163. const mipmap = mipmaps[ i ];
  41164. if ( texture.isCompressedArrayTexture ) {
  41165. if ( texture.format !== gl.RGBA ) {
  41166. if ( glFormat !== null ) {
  41167. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  41168. } else {
  41169. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  41170. }
  41171. } else {
  41172. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  41173. }
  41174. } else {
  41175. if ( glFormat !== null ) {
  41176. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  41177. } else {
  41178. console.warn( 'Unsupported compressed texture format' );
  41179. }
  41180. }
  41181. }
  41182. } else if ( texture.isCubeTexture ) {
  41183. const images = options.images;
  41184. for ( let i = 0; i < 6; i ++ ) {
  41185. const image = getImage( images[ i ] );
  41186. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  41187. }
  41188. } else if ( texture.isDataArrayTexture ) {
  41189. const image = options.image;
  41190. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41191. } else if ( texture.isData3DTexture ) {
  41192. const image = options.image;
  41193. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41194. } else if ( texture.isVideoTexture ) {
  41195. texture.update();
  41196. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  41197. } else {
  41198. const image = getImage( options.image );
  41199. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  41200. }
  41201. }
  41202. /**
  41203. * Generates mipmaps for the given texture.
  41204. *
  41205. * @param {Texture} texture - The texture.
  41206. */
  41207. generateMipmaps( texture ) {
  41208. const { gl, backend } = this;
  41209. const { textureGPU, glTextureType } = backend.get( texture );
  41210. backend.state.bindTexture( glTextureType, textureGPU );
  41211. gl.generateMipmap( glTextureType );
  41212. }
  41213. /**
  41214. * Deallocates the render buffers of the given render target.
  41215. *
  41216. * @param {RenderTarget} renderTarget - The render target.
  41217. */
  41218. deallocateRenderBuffers( renderTarget ) {
  41219. const { gl, backend } = this;
  41220. // remove framebuffer reference
  41221. if ( renderTarget ) {
  41222. const renderContextData = backend.get( renderTarget );
  41223. renderContextData.renderBufferStorageSetup = undefined;
  41224. if ( renderContextData.framebuffers ) {
  41225. for ( const cacheKey in renderContextData.framebuffers ) {
  41226. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  41227. }
  41228. delete renderContextData.framebuffers;
  41229. }
  41230. if ( renderContextData.depthRenderbuffer ) {
  41231. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  41232. delete renderContextData.depthRenderbuffer;
  41233. }
  41234. if ( renderContextData.stencilRenderbuffer ) {
  41235. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  41236. delete renderContextData.stencilRenderbuffer;
  41237. }
  41238. if ( renderContextData.msaaFrameBuffer ) {
  41239. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  41240. delete renderContextData.msaaFrameBuffer;
  41241. }
  41242. if ( renderContextData.msaaRenderbuffers ) {
  41243. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  41244. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  41245. }
  41246. delete renderContextData.msaaRenderbuffers;
  41247. }
  41248. }
  41249. }
  41250. /**
  41251. * Destroys the GPU data for the given texture object.
  41252. *
  41253. * @param {Texture} texture - The texture.
  41254. */
  41255. destroyTexture( texture ) {
  41256. const { gl, backend } = this;
  41257. const { textureGPU, renderTarget } = backend.get( texture );
  41258. this.deallocateRenderBuffers( renderTarget );
  41259. gl.deleteTexture( textureGPU );
  41260. backend.delete( texture );
  41261. }
  41262. /**
  41263. * Copies data of the given source texture to the given destination texture.
  41264. *
  41265. * @param {Texture} srcTexture - The source texture.
  41266. * @param {Texture} dstTexture - The destination texture.
  41267. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  41268. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  41269. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41270. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41271. */
  41272. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41273. const { gl, backend } = this;
  41274. const { state } = this.backend;
  41275. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  41276. state.bindTexture( glTextureType, dstTextureGPU );
  41277. // gather the necessary dimensions to copy
  41278. let width, height, depth, minX, minY, minZ;
  41279. let dstX, dstY, dstZ;
  41280. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  41281. if ( srcRegion !== null ) {
  41282. width = srcRegion.max.x - srcRegion.min.x;
  41283. height = srcRegion.max.y - srcRegion.min.y;
  41284. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  41285. minX = srcRegion.min.x;
  41286. minY = srcRegion.min.y;
  41287. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  41288. } else {
  41289. const levelScale = Math.pow( 2, - srcLevel );
  41290. width = Math.floor( image.width * levelScale );
  41291. height = Math.floor( image.height * levelScale );
  41292. if ( srcTexture.isDataArrayTexture ) {
  41293. depth = image.depth;
  41294. } else if ( srcTexture.isData3DTexture ) {
  41295. depth = Math.floor( image.depth * levelScale );
  41296. } else {
  41297. depth = 1;
  41298. }
  41299. minX = 0;
  41300. minY = 0;
  41301. minZ = 0;
  41302. }
  41303. if ( dstPosition !== null ) {
  41304. dstX = dstPosition.x;
  41305. dstY = dstPosition.y;
  41306. dstZ = dstPosition.z;
  41307. } else {
  41308. dstX = 0;
  41309. dstY = 0;
  41310. dstZ = 0;
  41311. }
  41312. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  41313. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  41314. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  41315. // used for copying data from cpu
  41316. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  41317. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  41318. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  41319. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  41320. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  41321. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  41322. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  41323. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  41324. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  41325. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  41326. // set up the src texture
  41327. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  41328. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  41329. const srcTextureData = backend.get( srcTexture );
  41330. const dstTextureData = backend.get( dstTexture );
  41331. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  41332. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  41333. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  41334. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  41335. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  41336. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  41337. let mask = gl.COLOR_BUFFER_BIT;
  41338. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  41339. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  41340. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  41341. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  41342. } else {
  41343. if ( isDst3D ) {
  41344. // copy data into the 3d texture
  41345. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  41346. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  41347. } else if ( dstTexture.isCompressedArrayTexture ) {
  41348. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  41349. } else {
  41350. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  41351. }
  41352. } else {
  41353. // copy data into the 2d texture
  41354. if ( srcTexture.isDataTexture ) {
  41355. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  41356. } else if ( srcTexture.isCompressedTexture ) {
  41357. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  41358. } else {
  41359. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  41360. }
  41361. }
  41362. }
  41363. // reset values
  41364. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  41365. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  41366. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  41367. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  41368. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  41369. // Generate mipmaps only when copying level 0
  41370. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  41371. gl.generateMipmap( glTextureType );
  41372. }
  41373. state.unbindTexture();
  41374. }
  41375. /**
  41376. * Copies the current bound framebuffer to the given texture.
  41377. *
  41378. * @param {Texture} texture - The destination texture.
  41379. * @param {RenderContext} renderContext - The render context.
  41380. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41381. */
  41382. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41383. const { gl } = this;
  41384. const { state } = this.backend;
  41385. const { textureGPU } = this.backend.get( texture );
  41386. const { x, y, z: width, w: height } = rectangle;
  41387. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  41388. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  41389. if ( requireDrawFrameBuffer ) {
  41390. const partial = ( x !== 0 || y !== 0 );
  41391. let mask;
  41392. let attachment;
  41393. if ( texture.isDepthTexture === true ) {
  41394. mask = gl.DEPTH_BUFFER_BIT;
  41395. attachment = gl.DEPTH_ATTACHMENT;
  41396. if ( renderContext.stencil ) {
  41397. mask |= gl.STENCIL_BUFFER_BIT;
  41398. }
  41399. } else {
  41400. mask = gl.COLOR_BUFFER_BIT;
  41401. attachment = gl.COLOR_ATTACHMENT0;
  41402. }
  41403. if ( partial ) {
  41404. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  41405. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41406. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41407. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41408. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41409. const flippedY = srcHeight - y - height;
  41410. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  41411. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41412. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41413. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  41414. state.unbindTexture();
  41415. } else {
  41416. const fb = gl.createFramebuffer();
  41417. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41418. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  41419. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  41420. gl.deleteFramebuffer( fb );
  41421. }
  41422. } else {
  41423. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41424. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  41425. state.unbindTexture();
  41426. }
  41427. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  41428. this.backend._setFramebuffer( renderContext );
  41429. }
  41430. /**
  41431. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  41432. *
  41433. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  41434. * @param {RenderContext} renderContext - The render context.
  41435. * @param {number} samples - The MSAA sample count.
  41436. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  41437. */
  41438. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  41439. const { gl } = this;
  41440. const renderTarget = renderContext.renderTarget;
  41441. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  41442. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  41443. if ( depthBuffer && ! stencilBuffer ) {
  41444. let glInternalFormat = gl.DEPTH_COMPONENT24;
  41445. if ( useMultisampledRTT === true ) {
  41446. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41447. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  41448. } else if ( samples > 0 ) {
  41449. if ( depthTexture && depthTexture.isDepthTexture ) {
  41450. if ( depthTexture.type === gl.FLOAT ) {
  41451. glInternalFormat = gl.DEPTH_COMPONENT32F;
  41452. }
  41453. }
  41454. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  41455. } else {
  41456. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  41457. }
  41458. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41459. } else if ( depthBuffer && stencilBuffer ) {
  41460. if ( samples > 0 ) {
  41461. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  41462. } else {
  41463. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  41464. }
  41465. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41466. }
  41467. }
  41468. /**
  41469. * Returns texture data as a typed array.
  41470. *
  41471. * @async
  41472. * @param {Texture} texture - The texture to copy.
  41473. * @param {number} x - The x coordinate of the copy origin.
  41474. * @param {number} y - The y coordinate of the copy origin.
  41475. * @param {number} width - The width of the copy.
  41476. * @param {number} height - The height of the copy.
  41477. * @param {number} faceIndex - The face index.
  41478. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41479. */
  41480. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41481. const { backend, gl } = this;
  41482. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  41483. const fb = gl.createFramebuffer();
  41484. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41485. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  41486. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  41487. const typedArrayType = this._getTypedArrayType( glType );
  41488. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  41489. const elementCount = width * height;
  41490. const byteLength = elementCount * bytesPerTexel;
  41491. const buffer = gl.createBuffer();
  41492. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41493. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  41494. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  41495. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41496. await backend.utils._clientWaitAsync();
  41497. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  41498. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41499. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  41500. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41501. gl.deleteFramebuffer( fb );
  41502. return dstBuffer;
  41503. }
  41504. /**
  41505. * Returns the corresponding typed array type for the given WebGL data type.
  41506. *
  41507. * @private
  41508. * @param {GLenum} glType - The WebGL data type.
  41509. * @return {TypedArray.constructor} The typed array type.
  41510. */
  41511. _getTypedArrayType( glType ) {
  41512. const { gl } = this;
  41513. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  41514. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  41515. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  41516. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  41517. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  41518. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  41519. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  41520. if ( glType === gl.FLOAT ) return Float32Array;
  41521. throw new Error( `Unsupported WebGL type: ${glType}` );
  41522. }
  41523. /**
  41524. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  41525. *
  41526. * @private
  41527. * @param {GLenum} glType - The WebGL data type.
  41528. * @param {GLenum} glFormat - The WebGL texture format.
  41529. * @return {number} The bytes-per-texel.
  41530. */
  41531. _getBytesPerTexel( glType, glFormat ) {
  41532. const { gl } = this;
  41533. let bytesPerComponent = 0;
  41534. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  41535. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  41536. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  41537. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  41538. glType === gl.UNSIGNED_SHORT ||
  41539. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  41540. if ( glType === gl.UNSIGNED_INT ||
  41541. glType === gl.FLOAT ) bytesPerComponent = 4;
  41542. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  41543. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  41544. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  41545. }
  41546. }
  41547. /**
  41548. * A WebGL 2 backend utility module for managing extensions.
  41549. *
  41550. * @private
  41551. */
  41552. class WebGLExtensions {
  41553. /**
  41554. * Constructs a new utility object.
  41555. *
  41556. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41557. */
  41558. constructor( backend ) {
  41559. /**
  41560. * A reference to the WebGL 2 backend.
  41561. *
  41562. * @type {WebGLBackend}
  41563. */
  41564. this.backend = backend;
  41565. /**
  41566. * A reference to the rendering context.
  41567. *
  41568. * @type {WebGL2RenderingContext}
  41569. */
  41570. this.gl = this.backend.gl;
  41571. /**
  41572. * A list with all the supported WebGL extensions.
  41573. *
  41574. * @type {Array<string>}
  41575. */
  41576. this.availableExtensions = this.gl.getSupportedExtensions();
  41577. /**
  41578. * A dictionary with requested WebGL extensions.
  41579. * The key is the name of the extension, the value
  41580. * the requested extension object.
  41581. *
  41582. * @type {Object<string,Object>}
  41583. */
  41584. this.extensions = {};
  41585. }
  41586. /**
  41587. * Returns the extension object for the given extension name.
  41588. *
  41589. * @param {string} name - The extension name.
  41590. * @return {Object} The extension object.
  41591. */
  41592. get( name ) {
  41593. let extension = this.extensions[ name ];
  41594. if ( extension === undefined ) {
  41595. extension = this.gl.getExtension( name );
  41596. this.extensions[ name ] = extension;
  41597. }
  41598. return extension;
  41599. }
  41600. /**
  41601. * Returns `true` if the requested extension is available.
  41602. *
  41603. * @param {string} name - The extension name.
  41604. * @return {boolean} Whether the given extension is available or not.
  41605. */
  41606. has( name ) {
  41607. return this.availableExtensions.includes( name );
  41608. }
  41609. }
  41610. /**
  41611. * A WebGL 2 backend utility module for managing the device's capabilities.
  41612. *
  41613. * @private
  41614. */
  41615. class WebGLCapabilities {
  41616. /**
  41617. * Constructs a new utility object.
  41618. *
  41619. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41620. */
  41621. constructor( backend ) {
  41622. /**
  41623. * A reference to the WebGL 2 backend.
  41624. *
  41625. * @type {WebGLBackend}
  41626. */
  41627. this.backend = backend;
  41628. /**
  41629. * This value holds the cached max anisotropy value.
  41630. *
  41631. * @type {?number}
  41632. * @default null
  41633. */
  41634. this.maxAnisotropy = null;
  41635. }
  41636. /**
  41637. * Returns the maximum anisotropy texture filtering value. This value
  41638. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  41639. * WebGL extension.
  41640. *
  41641. * @return {number} The maximum anisotropy texture filtering value.
  41642. */
  41643. getMaxAnisotropy() {
  41644. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  41645. const gl = this.backend.gl;
  41646. const extensions = this.backend.extensions;
  41647. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41648. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41649. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  41650. } else {
  41651. this.maxAnisotropy = 0;
  41652. }
  41653. return this.maxAnisotropy;
  41654. }
  41655. }
  41656. const GLFeatureName = {
  41657. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  41658. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  41659. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  41660. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  41661. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41662. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41663. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  41664. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  41665. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  41666. };
  41667. class WebGLBufferRenderer {
  41668. constructor( backend ) {
  41669. this.gl = backend.gl;
  41670. this.extensions = backend.extensions;
  41671. this.info = backend.renderer.info;
  41672. this.mode = null;
  41673. this.index = 0;
  41674. this.type = null;
  41675. this.object = null;
  41676. }
  41677. render( start, count ) {
  41678. const { gl, mode, object, type, info, index } = this;
  41679. if ( index !== 0 ) {
  41680. gl.drawElements( mode, count, type, start );
  41681. } else {
  41682. gl.drawArrays( mode, start, count );
  41683. }
  41684. info.update( object, count, 1 );
  41685. }
  41686. renderInstances( start, count, primcount ) {
  41687. const { gl, mode, type, index, object, info } = this;
  41688. if ( primcount === 0 ) return;
  41689. if ( index !== 0 ) {
  41690. gl.drawElementsInstanced( mode, count, type, start, primcount );
  41691. } else {
  41692. gl.drawArraysInstanced( mode, start, count, primcount );
  41693. }
  41694. info.update( object, count, primcount );
  41695. }
  41696. renderMultiDraw( starts, counts, drawCount ) {
  41697. const { extensions, mode, object, info } = this;
  41698. if ( drawCount === 0 ) return;
  41699. const extension = extensions.get( 'WEBGL_multi_draw' );
  41700. if ( extension === null ) {
  41701. for ( let i = 0; i < drawCount; i ++ ) {
  41702. this.render( starts[ i ], counts[ i ] );
  41703. }
  41704. } else {
  41705. if ( this.index !== 0 ) {
  41706. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  41707. } else {
  41708. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  41709. }
  41710. let elementCount = 0;
  41711. for ( let i = 0; i < drawCount; i ++ ) {
  41712. elementCount += counts[ i ];
  41713. }
  41714. info.update( object, elementCount, 1 );
  41715. }
  41716. }
  41717. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  41718. const { extensions, mode, object, info } = this;
  41719. if ( drawCount === 0 ) return;
  41720. const extension = extensions.get( 'WEBGL_multi_draw' );
  41721. if ( extension === null ) {
  41722. for ( let i = 0; i < drawCount; i ++ ) {
  41723. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  41724. }
  41725. } else {
  41726. if ( this.index !== 0 ) {
  41727. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  41728. } else {
  41729. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  41730. }
  41731. let elementCount = 0;
  41732. for ( let i = 0; i < drawCount; i ++ ) {
  41733. elementCount += counts[ i ] * primcount[ i ];
  41734. }
  41735. info.update( object, elementCount, 1 );
  41736. }
  41737. }
  41738. //
  41739. }
  41740. /**
  41741. * Abstract base class of a timestamp query pool.
  41742. *
  41743. * @abstract
  41744. */
  41745. class TimestampQueryPool {
  41746. /**
  41747. * Creates a new timestamp query pool.
  41748. *
  41749. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  41750. */
  41751. constructor( maxQueries = 256 ) {
  41752. /**
  41753. * Whether to track timestamps or not.
  41754. *
  41755. * @type {boolean}
  41756. * @default true
  41757. */
  41758. this.trackTimestamp = true;
  41759. /**
  41760. * Maximum number of queries this pool can hold.
  41761. *
  41762. * @type {number}
  41763. * @default 256
  41764. */
  41765. this.maxQueries = maxQueries;
  41766. /**
  41767. * How many queries allocated so far.
  41768. *
  41769. * @type {number}
  41770. * @default 0
  41771. */
  41772. this.currentQueryIndex = 0;
  41773. /**
  41774. * Tracks offsets for different contexts.
  41775. *
  41776. * @type {Map<string, number>}
  41777. */
  41778. this.queryOffsets = new Map();
  41779. /**
  41780. * Whether the pool has been disposed or not.
  41781. *
  41782. * @type {boolean}
  41783. * @default false
  41784. */
  41785. this.isDisposed = false;
  41786. /**
  41787. * TODO
  41788. *
  41789. * @type {number}
  41790. * @default 0
  41791. */
  41792. this.lastValue = 0;
  41793. /**
  41794. * TODO
  41795. *
  41796. * @type {boolean}
  41797. * @default false
  41798. */
  41799. this.pendingResolve = false;
  41800. }
  41801. /**
  41802. * Allocate queries for a specific renderContext.
  41803. *
  41804. * @abstract
  41805. * @param {Object} renderContext - The render context to allocate queries for.
  41806. */
  41807. allocateQueriesForContext( /* renderContext */ ) {}
  41808. /**
  41809. * Resolve all timestamps and return data (or process them).
  41810. *
  41811. * @abstract
  41812. * @async
  41813. * @returns {Promise<number>|number} The resolved timestamp value.
  41814. */
  41815. async resolveQueriesAsync() {}
  41816. /**
  41817. * Dispose of the query pool.
  41818. *
  41819. * @abstract
  41820. */
  41821. dispose() {}
  41822. }
  41823. /**
  41824. * Manages a pool of WebGL timestamp queries for performance measurement.
  41825. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  41826. *
  41827. * @augments TimestampQueryPool
  41828. */
  41829. class WebGLTimestampQueryPool extends TimestampQueryPool {
  41830. /**
  41831. * Creates a new WebGL timestamp query pool.
  41832. *
  41833. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  41834. * @param {string} type - The type identifier for this query pool.
  41835. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  41836. */
  41837. constructor( gl, type, maxQueries = 2048 ) {
  41838. super( maxQueries );
  41839. this.gl = gl;
  41840. this.type = type;
  41841. // Check for timer query extensions
  41842. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  41843. gl.getExtension( 'EXT_disjoint_timer_query' );
  41844. if ( ! this.ext ) {
  41845. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  41846. this.trackTimestamp = false;
  41847. return;
  41848. }
  41849. // Create query objects
  41850. this.queries = [];
  41851. for ( let i = 0; i < this.maxQueries; i ++ ) {
  41852. this.queries.push( gl.createQuery() );
  41853. }
  41854. this.activeQuery = null;
  41855. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  41856. }
  41857. /**
  41858. * Allocates a pair of queries for a given render context.
  41859. *
  41860. * @param {Object} renderContext - The render context to allocate queries for.
  41861. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  41862. */
  41863. allocateQueriesForContext( renderContext ) {
  41864. if ( ! this.trackTimestamp ) return null;
  41865. // Check if we have enough space for a new query pair
  41866. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  41867. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  41868. return null;
  41869. }
  41870. const baseOffset = this.currentQueryIndex;
  41871. this.currentQueryIndex += 2;
  41872. // Initialize query states
  41873. this.queryStates.set( baseOffset, 'inactive' );
  41874. this.queryOffsets.set( renderContext.id, baseOffset );
  41875. return baseOffset;
  41876. }
  41877. /**
  41878. * Begins a timestamp query for the specified render context.
  41879. *
  41880. * @param {Object} renderContext - The render context to begin timing for.
  41881. */
  41882. beginQuery( renderContext ) {
  41883. if ( ! this.trackTimestamp || this.isDisposed ) {
  41884. return;
  41885. }
  41886. const baseOffset = this.queryOffsets.get( renderContext.id );
  41887. if ( baseOffset == null ) {
  41888. return;
  41889. }
  41890. // Don't start a new query if there's an active one
  41891. if ( this.activeQuery !== null ) {
  41892. return;
  41893. }
  41894. const query = this.queries[ baseOffset ];
  41895. if ( ! query ) {
  41896. return;
  41897. }
  41898. try {
  41899. // Only begin if query is inactive
  41900. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  41901. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  41902. this.activeQuery = baseOffset;
  41903. this.queryStates.set( baseOffset, 'started' );
  41904. }
  41905. } catch ( error ) {
  41906. console.error( 'Error in beginQuery:', error );
  41907. this.activeQuery = null;
  41908. this.queryStates.set( baseOffset, 'inactive' );
  41909. }
  41910. }
  41911. /**
  41912. * Ends the active timestamp query for the specified render context.
  41913. *
  41914. * @param {Object} renderContext - The render context to end timing for.
  41915. * @param {string} renderContext.id - Unique identifier for the render context.
  41916. */
  41917. endQuery( renderContext ) {
  41918. if ( ! this.trackTimestamp || this.isDisposed ) {
  41919. return;
  41920. }
  41921. const baseOffset = this.queryOffsets.get( renderContext.id );
  41922. if ( baseOffset == null ) {
  41923. return;
  41924. }
  41925. // Only end if this is the active query
  41926. if ( this.activeQuery !== baseOffset ) {
  41927. return;
  41928. }
  41929. try {
  41930. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  41931. this.queryStates.set( baseOffset, 'ended' );
  41932. this.activeQuery = null;
  41933. } catch ( error ) {
  41934. console.error( 'Error in endQuery:', error );
  41935. // Reset state on error
  41936. this.queryStates.set( baseOffset, 'inactive' );
  41937. this.activeQuery = null;
  41938. }
  41939. }
  41940. /**
  41941. * Asynchronously resolves all completed queries and returns the total duration.
  41942. *
  41943. * @async
  41944. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  41945. */
  41946. async resolveQueriesAsync() {
  41947. if ( ! this.trackTimestamp || this.pendingResolve ) {
  41948. return this.lastValue;
  41949. }
  41950. this.pendingResolve = true;
  41951. try {
  41952. // Wait for all ended queries to complete
  41953. const resolvePromises = [];
  41954. for ( const [ baseOffset, state ] of this.queryStates ) {
  41955. if ( state === 'ended' ) {
  41956. const query = this.queries[ baseOffset ];
  41957. resolvePromises.push( this.resolveQuery( query ) );
  41958. }
  41959. }
  41960. if ( resolvePromises.length === 0 ) {
  41961. return this.lastValue;
  41962. }
  41963. const results = await Promise.all( resolvePromises );
  41964. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  41965. // Store the last valid result
  41966. this.lastValue = totalDuration;
  41967. // Reset states
  41968. this.currentQueryIndex = 0;
  41969. this.queryOffsets.clear();
  41970. this.queryStates.clear();
  41971. this.activeQuery = null;
  41972. return totalDuration;
  41973. } catch ( error ) {
  41974. console.error( 'Error resolving queries:', error );
  41975. return this.lastValue;
  41976. } finally {
  41977. this.pendingResolve = false;
  41978. }
  41979. }
  41980. /**
  41981. * Resolves a single query, checking for completion and disjoint operation.
  41982. *
  41983. * @async
  41984. * @param {WebGLQuery} query - The query object to resolve.
  41985. * @returns {Promise<number>} The elapsed time in milliseconds.
  41986. */
  41987. async resolveQuery( query ) {
  41988. return new Promise( ( resolve ) => {
  41989. if ( this.isDisposed ) {
  41990. resolve( this.lastValue );
  41991. return;
  41992. }
  41993. let timeoutId;
  41994. let isResolved = false;
  41995. const cleanup = () => {
  41996. if ( timeoutId ) {
  41997. clearTimeout( timeoutId );
  41998. timeoutId = null;
  41999. }
  42000. };
  42001. const finalizeResolution = ( value ) => {
  42002. if ( ! isResolved ) {
  42003. isResolved = true;
  42004. cleanup();
  42005. resolve( value );
  42006. }
  42007. };
  42008. const checkQuery = () => {
  42009. if ( this.isDisposed ) {
  42010. finalizeResolution( this.lastValue );
  42011. return;
  42012. }
  42013. try {
  42014. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  42015. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  42016. if ( disjoint ) {
  42017. finalizeResolution( this.lastValue );
  42018. return;
  42019. }
  42020. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  42021. if ( ! available ) {
  42022. timeoutId = setTimeout( checkQuery, 1 );
  42023. return;
  42024. }
  42025. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  42026. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  42027. } catch ( error ) {
  42028. console.error( 'Error checking query:', error );
  42029. resolve( this.lastValue );
  42030. }
  42031. };
  42032. checkQuery();
  42033. } );
  42034. }
  42035. /**
  42036. * Releases all resources held by this query pool.
  42037. * This includes deleting all query objects and clearing internal state.
  42038. */
  42039. dispose() {
  42040. if ( this.isDisposed ) {
  42041. return;
  42042. }
  42043. this.isDisposed = true;
  42044. if ( ! this.trackTimestamp ) return;
  42045. for ( const query of this.queries ) {
  42046. this.gl.deleteQuery( query );
  42047. }
  42048. this.queries = [];
  42049. this.queryStates.clear();
  42050. this.queryOffsets.clear();
  42051. this.lastValue = 0;
  42052. this.activeQuery = null;
  42053. }
  42054. }
  42055. /**
  42056. * A backend implementation targeting WebGL 2.
  42057. *
  42058. * @private
  42059. * @augments Backend
  42060. */
  42061. class WebGLBackend extends Backend {
  42062. /**
  42063. * WebGLBackend options.
  42064. *
  42065. * @typedef {Object} WebGLBackend~Options
  42066. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  42067. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  42068. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  42069. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  42070. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  42071. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  42072. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  42073. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  42074. */
  42075. /**
  42076. * Constructs a new WebGPU backend.
  42077. *
  42078. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  42079. */
  42080. constructor( parameters = {} ) {
  42081. super( parameters );
  42082. /**
  42083. * This flag can be used for type testing.
  42084. *
  42085. * @type {boolean}
  42086. * @readonly
  42087. * @default true
  42088. */
  42089. this.isWebGLBackend = true;
  42090. /**
  42091. * A reference to a backend module holding shader attribute-related
  42092. * utility functions.
  42093. *
  42094. * @type {?WebGLAttributeUtils}
  42095. * @default null
  42096. */
  42097. this.attributeUtils = null;
  42098. /**
  42099. * A reference to a backend module holding extension-related
  42100. * utility functions.
  42101. *
  42102. * @type {?WebGLExtensions}
  42103. * @default null
  42104. */
  42105. this.extensions = null;
  42106. /**
  42107. * A reference to a backend module holding capability-related
  42108. * utility functions.
  42109. *
  42110. * @type {?WebGLCapabilities}
  42111. * @default null
  42112. */
  42113. this.capabilities = null;
  42114. /**
  42115. * A reference to a backend module holding texture-related
  42116. * utility functions.
  42117. *
  42118. * @type {?WebGLTextureUtils}
  42119. * @default null
  42120. */
  42121. this.textureUtils = null;
  42122. /**
  42123. * A reference to a backend module holding renderer-related
  42124. * utility functions.
  42125. *
  42126. * @type {?WebGLBufferRenderer}
  42127. * @default null
  42128. */
  42129. this.bufferRenderer = null;
  42130. /**
  42131. * A reference to the rendering context.
  42132. *
  42133. * @type {?WebGL2RenderingContext}
  42134. * @default null
  42135. */
  42136. this.gl = null;
  42137. /**
  42138. * A reference to a backend module holding state-related
  42139. * utility functions.
  42140. *
  42141. * @type {?WebGLState}
  42142. * @default null
  42143. */
  42144. this.state = null;
  42145. /**
  42146. * A reference to a backend module holding common
  42147. * utility functions.
  42148. *
  42149. * @type {?WebGLUtils}
  42150. * @default null
  42151. */
  42152. this.utils = null;
  42153. /**
  42154. * Dictionary for caching VAOs.
  42155. *
  42156. * @type {Object<string,WebGLVertexArrayObject>}
  42157. */
  42158. this.vaoCache = {};
  42159. /**
  42160. * Dictionary for caching transform feedback objects.
  42161. *
  42162. * @type {Object<string,WebGLTransformFeedback>}
  42163. */
  42164. this.transformFeedbackCache = {};
  42165. /**
  42166. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  42167. * Only relevant when using compute shaders.
  42168. *
  42169. * @type {boolean}
  42170. * @default false
  42171. */
  42172. this.discard = false;
  42173. /**
  42174. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  42175. * device does not support the extension.
  42176. *
  42177. * @type {?EXTDisjointTimerQueryWebGL2}
  42178. * @default null
  42179. */
  42180. this.disjoint = null;
  42181. /**
  42182. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  42183. * device does not support the extension.
  42184. *
  42185. * @type {?KHRParallelShaderCompile}
  42186. * @default null
  42187. */
  42188. this.parallel = null;
  42189. /**
  42190. * A reference to the current render context.
  42191. *
  42192. * @private
  42193. * @type {RenderContext}
  42194. * @default null
  42195. */
  42196. this._currentContext = null;
  42197. /**
  42198. * A unique collection of bindings.
  42199. *
  42200. * @private
  42201. * @type {WeakSet}
  42202. */
  42203. this._knownBindings = new WeakSet();
  42204. /**
  42205. * Whether the device supports framebuffers invalidation or not.
  42206. *
  42207. * @private
  42208. * @type {boolean}
  42209. */
  42210. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  42211. /**
  42212. * The target framebuffer when rendering with
  42213. * the WebXR device API.
  42214. *
  42215. * @private
  42216. * @type {WebGLFramebuffer}
  42217. * @default null
  42218. */
  42219. this._xrFramebuffer = null;
  42220. }
  42221. /**
  42222. * Initializes the backend so it is ready for usage.
  42223. *
  42224. * @param {Renderer} renderer - The renderer.
  42225. */
  42226. init( renderer ) {
  42227. super.init( renderer );
  42228. //
  42229. const parameters = this.parameters;
  42230. const contextAttributes = {
  42231. antialias: renderer.samples > 0,
  42232. alpha: true, // always true for performance reasons
  42233. depth: renderer.depth,
  42234. stencil: renderer.stencil
  42235. };
  42236. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  42237. function onContextLost( event ) {
  42238. event.preventDefault();
  42239. const contextLossInfo = {
  42240. api: 'WebGL',
  42241. message: event.statusMessage || 'Unknown reason',
  42242. reason: null,
  42243. originalEvent: event
  42244. };
  42245. renderer.onDeviceLost( contextLossInfo );
  42246. }
  42247. this._onContextLost = onContextLost;
  42248. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  42249. this.gl = glContext;
  42250. this.extensions = new WebGLExtensions( this );
  42251. this.capabilities = new WebGLCapabilities( this );
  42252. this.attributeUtils = new WebGLAttributeUtils( this );
  42253. this.textureUtils = new WebGLTextureUtils( this );
  42254. this.bufferRenderer = new WebGLBufferRenderer( this );
  42255. this.state = new WebGLState( this );
  42256. this.utils = new WebGLUtils( this );
  42257. this.extensions.get( 'EXT_color_buffer_float' );
  42258. this.extensions.get( 'WEBGL_clip_cull_distance' );
  42259. this.extensions.get( 'OES_texture_float_linear' );
  42260. this.extensions.get( 'EXT_color_buffer_half_float' );
  42261. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42262. this.extensions.get( 'WEBGL_render_shared_exponent' );
  42263. this.extensions.get( 'WEBGL_multi_draw' );
  42264. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  42265. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  42266. }
  42267. /**
  42268. * The coordinate system of the backend.
  42269. *
  42270. * @type {number}
  42271. * @readonly
  42272. */
  42273. get coordinateSystem() {
  42274. return WebGLCoordinateSystem;
  42275. }
  42276. /**
  42277. * This method performs a readback operation by moving buffer data from
  42278. * a storage buffer attribute from the GPU to the CPU.
  42279. *
  42280. * @async
  42281. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42282. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42283. */
  42284. async getArrayBufferAsync( attribute ) {
  42285. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42286. }
  42287. /**
  42288. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  42289. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  42290. *
  42291. * @async
  42292. * @return {Promise} A Promise that resolves when synchronization has been finished.
  42293. */
  42294. async waitForGPU() {
  42295. await this.utils._clientWaitAsync();
  42296. }
  42297. /**
  42298. * Ensures the backend is XR compatible.
  42299. *
  42300. * @async
  42301. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  42302. */
  42303. async makeXRCompatible() {
  42304. const attributes = this.gl.getContextAttributes();
  42305. if ( attributes.xrCompatible !== true ) {
  42306. await this.gl.makeXRCompatible();
  42307. }
  42308. }
  42309. /**
  42310. * Sets the XR rendering destination.
  42311. *
  42312. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  42313. */
  42314. setXRTarget( xrFramebuffer ) {
  42315. this._xrFramebuffer = xrFramebuffer;
  42316. }
  42317. /**
  42318. * Configures the given XR render target with external textures.
  42319. *
  42320. * This method is only relevant when using the WebXR Layers API.
  42321. *
  42322. * @param {XRRenderTarget} renderTarget - The XR render target.
  42323. * @param {WebGLTexture} colorTexture - A native color texture.
  42324. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  42325. */
  42326. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  42327. const gl = this.gl;
  42328. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  42329. if ( depthTexture !== null ) {
  42330. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  42331. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  42332. // The multisample_render_to_texture extension doesn't work properly if there
  42333. // are midframe flushes and an external depth texture.
  42334. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget.autoAllocateDepthBuffer ) {
  42335. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  42336. }
  42337. renderTarget.autoAllocateDepthBuffer = false;
  42338. }
  42339. }
  42340. /**
  42341. * Inits a time stamp query for the given render context.
  42342. *
  42343. * @param {RenderContext} renderContext - The render context.
  42344. */
  42345. initTimestampQuery( renderContext ) {
  42346. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  42347. const type = renderContext.isComputeNode ? 'compute' : 'render';
  42348. if ( ! this.timestampQueryPool[ type ] ) {
  42349. // TODO: Variable maxQueries?
  42350. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  42351. }
  42352. const timestampQueryPool = this.timestampQueryPool[ type ];
  42353. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  42354. if ( baseOffset !== null ) {
  42355. timestampQueryPool.beginQuery( renderContext );
  42356. }
  42357. }
  42358. // timestamp utils
  42359. /**
  42360. * Prepares the timestamp buffer.
  42361. *
  42362. * @param {RenderContext} renderContext - The render context.
  42363. */
  42364. prepareTimestampBuffer( renderContext ) {
  42365. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  42366. const type = renderContext.isComputeNode ? 'compute' : 'render';
  42367. const timestampQueryPool = this.timestampQueryPool[ type ];
  42368. timestampQueryPool.endQuery( renderContext );
  42369. }
  42370. /**
  42371. * Returns the backend's rendering context.
  42372. *
  42373. * @return {WebGL2RenderingContext} The rendering context.
  42374. */
  42375. getContext() {
  42376. return this.gl;
  42377. }
  42378. /**
  42379. * This method is executed at the beginning of a render call and prepares
  42380. * the WebGL state for upcoming render calls
  42381. *
  42382. * @param {RenderContext} renderContext - The render context.
  42383. */
  42384. beginRender( renderContext ) {
  42385. const { state, gl } = this;
  42386. const renderContextData = this.get( renderContext );
  42387. //
  42388. if ( renderContext.viewport ) {
  42389. this.updateViewport( renderContext );
  42390. } else {
  42391. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  42392. }
  42393. if ( renderContext.scissor ) {
  42394. const { x, y, width, height } = renderContext.scissorValue;
  42395. state.scissor( x, renderContext.height - height - y, width, height );
  42396. }
  42397. //
  42398. this.initTimestampQuery( renderContext );
  42399. renderContextData.previousContext = this._currentContext;
  42400. this._currentContext = renderContext;
  42401. this._setFramebuffer( renderContext );
  42402. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  42403. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42404. if ( occlusionQueryCount > 0 ) {
  42405. // Get a reference to the array of objects with queries. The renderContextData property
  42406. // can be changed by another render pass before the async reading of all previous queries complete
  42407. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  42408. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42409. renderContextData.lastOcclusionObject = null;
  42410. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  42411. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42412. renderContextData.occlusionQueryIndex = 0;
  42413. }
  42414. }
  42415. /**
  42416. * This method is executed at the end of a render call and finalizes work
  42417. * after draw calls.
  42418. *
  42419. * @param {RenderContext} renderContext - The render context.
  42420. */
  42421. finishRender( renderContext ) {
  42422. const { gl, state } = this;
  42423. const renderContextData = this.get( renderContext );
  42424. const previousContext = renderContextData.previousContext;
  42425. state.resetVertexState();
  42426. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42427. if ( occlusionQueryCount > 0 ) {
  42428. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42429. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42430. }
  42431. this.resolveOccludedAsync( renderContext );
  42432. }
  42433. const textures = renderContext.textures;
  42434. if ( textures !== null ) {
  42435. for ( let i = 0; i < textures.length; i ++ ) {
  42436. const texture = textures[ i ];
  42437. if ( texture.generateMipmaps ) {
  42438. this.generateMipmaps( texture );
  42439. }
  42440. }
  42441. }
  42442. this._currentContext = previousContext;
  42443. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  42444. const renderTargetContextData = this.get( renderContext.renderTarget );
  42445. const { samples } = renderContext.renderTarget;
  42446. if ( samples > 0 && this._useMultisampledRTT( renderContext.renderTarget ) === false ) {
  42447. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42448. const mask = gl.COLOR_BUFFER_BIT;
  42449. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42450. const textures = renderContext.textures;
  42451. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42452. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42453. for ( let i = 0; i < textures.length; i ++ ) {
  42454. // TODO Add support for MRT
  42455. if ( renderContext.scissor ) {
  42456. const { x, y, width, height } = renderContext.scissorValue;
  42457. const viewY = renderContext.height - height - y;
  42458. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  42459. if ( this._supportsInvalidateFramebuffer === true ) {
  42460. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  42461. }
  42462. } else {
  42463. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  42464. if ( this._supportsInvalidateFramebuffer === true ) {
  42465. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  42466. }
  42467. }
  42468. }
  42469. }
  42470. }
  42471. if ( previousContext !== null ) {
  42472. this._setFramebuffer( previousContext );
  42473. if ( previousContext.viewport ) {
  42474. this.updateViewport( previousContext );
  42475. } else {
  42476. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  42477. }
  42478. }
  42479. this.prepareTimestampBuffer( renderContext );
  42480. }
  42481. /**
  42482. * This method processes the result of occlusion queries and writes it
  42483. * into render context data.
  42484. *
  42485. * @async
  42486. * @param {RenderContext} renderContext - The render context.
  42487. */
  42488. resolveOccludedAsync( renderContext ) {
  42489. const renderContextData = this.get( renderContext );
  42490. // handle occlusion query results
  42491. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  42492. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  42493. const occluded = new WeakSet();
  42494. const { gl } = this;
  42495. renderContextData.currentOcclusionQueryObjects = null;
  42496. renderContextData.currentOcclusionQueries = null;
  42497. const check = () => {
  42498. let completed = 0;
  42499. // check all queries and requeue as appropriate
  42500. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  42501. const query = currentOcclusionQueries[ i ];
  42502. if ( query === null ) continue;
  42503. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  42504. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  42505. currentOcclusionQueries[ i ] = null;
  42506. gl.deleteQuery( query );
  42507. completed ++;
  42508. }
  42509. }
  42510. if ( completed < currentOcclusionQueries.length ) {
  42511. requestAnimationFrame( check );
  42512. } else {
  42513. renderContextData.occluded = occluded;
  42514. }
  42515. };
  42516. check();
  42517. }
  42518. }
  42519. /**
  42520. * Returns `true` if the given 3D object is fully occluded by other
  42521. * 3D objects in the scene.
  42522. *
  42523. * @param {RenderContext} renderContext - The render context.
  42524. * @param {Object3D} object - The 3D object to test.
  42525. * @return {boolean} Whether the 3D object is fully occluded or not.
  42526. */
  42527. isOccluded( renderContext, object ) {
  42528. const renderContextData = this.get( renderContext );
  42529. return renderContextData.occluded && renderContextData.occluded.has( object );
  42530. }
  42531. /**
  42532. * Updates the viewport with the values from the given render context.
  42533. *
  42534. * @param {RenderContext} renderContext - The render context.
  42535. */
  42536. updateViewport( renderContext ) {
  42537. const { state } = this;
  42538. const { x, y, width, height } = renderContext.viewportValue;
  42539. state.viewport( x, renderContext.height - height - y, width, height );
  42540. }
  42541. /**
  42542. * Defines the scissor test.
  42543. *
  42544. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42545. */
  42546. setScissorTest( boolean ) {
  42547. const state = this.state;
  42548. state.setScissorTest( boolean );
  42549. }
  42550. /**
  42551. * Returns the clear color and alpha into a single
  42552. * color object.
  42553. *
  42554. * @return {Color4} The clear color.
  42555. */
  42556. getClearColor() {
  42557. const clearColor = super.getClearColor();
  42558. // Since the canvas is always created with alpha: true,
  42559. // WebGL must always premultiply the clear color.
  42560. clearColor.r *= clearColor.a;
  42561. clearColor.g *= clearColor.a;
  42562. clearColor.b *= clearColor.a;
  42563. return clearColor;
  42564. }
  42565. /**
  42566. * Performs a clear operation.
  42567. *
  42568. * @param {boolean} color - Whether the color buffer should be cleared or not.
  42569. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  42570. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  42571. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  42572. * @param {boolean} [setFrameBuffer=true] - TODO.
  42573. */
  42574. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  42575. const { gl, renderer } = this;
  42576. if ( descriptor === null ) {
  42577. const clearColor = this.getClearColor();
  42578. descriptor = {
  42579. textures: null,
  42580. clearColorValue: clearColor
  42581. };
  42582. }
  42583. //
  42584. let clear = 0;
  42585. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  42586. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  42587. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  42588. if ( clear !== 0 ) {
  42589. let clearColor;
  42590. if ( descriptor.clearColorValue ) {
  42591. clearColor = descriptor.clearColorValue;
  42592. } else {
  42593. clearColor = this.getClearColor();
  42594. }
  42595. const clearDepth = renderer.getClearDepth();
  42596. const clearStencil = renderer.getClearStencil();
  42597. if ( depth ) this.state.setDepthMask( true );
  42598. if ( descriptor.textures === null ) {
  42599. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  42600. gl.clear( clear );
  42601. } else {
  42602. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  42603. if ( color ) {
  42604. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  42605. if ( i === 0 ) {
  42606. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  42607. } else {
  42608. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  42609. }
  42610. }
  42611. }
  42612. if ( depth && stencil ) {
  42613. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  42614. } else if ( depth ) {
  42615. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  42616. } else if ( stencil ) {
  42617. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  42618. }
  42619. }
  42620. }
  42621. }
  42622. /**
  42623. * This method is executed at the beginning of a compute call and
  42624. * prepares the state for upcoming compute tasks.
  42625. *
  42626. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42627. */
  42628. beginCompute( computeGroup ) {
  42629. const { state, gl } = this;
  42630. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  42631. this.initTimestampQuery( computeGroup );
  42632. }
  42633. /**
  42634. * Executes a compute command for the given compute node.
  42635. *
  42636. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  42637. * @param {Node} computeNode - The compute node.
  42638. * @param {Array<BindGroup>} bindings - The bindings.
  42639. * @param {ComputePipeline} pipeline - The compute pipeline.
  42640. */
  42641. compute( computeGroup, computeNode, bindings, pipeline ) {
  42642. const { state, gl } = this;
  42643. if ( this.discard === false ) {
  42644. // required here to handle async behaviour of render.compute()
  42645. gl.enable( gl.RASTERIZER_DISCARD );
  42646. this.discard = true;
  42647. }
  42648. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  42649. const vaoKey = this._getVaoKey( attributes );
  42650. const vaoGPU = this.vaoCache[ vaoKey ];
  42651. if ( vaoGPU === undefined ) {
  42652. this._createVao( attributes );
  42653. } else {
  42654. state.setVertexState( vaoGPU );
  42655. }
  42656. state.useProgram( programGPU );
  42657. this._bindUniforms( bindings );
  42658. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  42659. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42660. gl.beginTransformFeedback( gl.POINTS );
  42661. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  42662. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  42663. } else {
  42664. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  42665. }
  42666. gl.endTransformFeedback();
  42667. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42668. // switch active buffers
  42669. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42670. const dualAttributeData = transformBuffers[ i ];
  42671. if ( dualAttributeData.pbo ) {
  42672. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  42673. }
  42674. dualAttributeData.switchBuffers();
  42675. }
  42676. }
  42677. /**
  42678. * This method is executed at the end of a compute call and
  42679. * finalizes work after compute tasks.
  42680. *
  42681. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42682. */
  42683. finishCompute( computeGroup ) {
  42684. const gl = this.gl;
  42685. this.discard = false;
  42686. gl.disable( gl.RASTERIZER_DISCARD );
  42687. this.prepareTimestampBuffer( computeGroup );
  42688. if ( this._currentContext ) {
  42689. this._setFramebuffer( this._currentContext );
  42690. }
  42691. }
  42692. /**
  42693. * Executes a draw command for the given render object.
  42694. *
  42695. * @param {RenderObject} renderObject - The render object to draw.
  42696. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42697. */
  42698. draw( renderObject/*, info*/ ) {
  42699. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  42700. const { programGPU } = this.get( pipeline );
  42701. const { gl, state } = this;
  42702. const contextData = this.get( context );
  42703. const drawParams = renderObject.getDrawParameters();
  42704. if ( drawParams === null ) return;
  42705. //
  42706. this._bindUniforms( renderObject.getBindings() );
  42707. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  42708. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  42709. state.useProgram( programGPU );
  42710. // vertex state
  42711. const renderObjectData = this.get( renderObject );
  42712. let vaoGPU = renderObjectData.staticVao;
  42713. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  42714. const vaoKey = this._getVaoKey( renderObject.getAttributes() );
  42715. vaoGPU = this.vaoCache[ vaoKey ];
  42716. if ( vaoGPU === undefined ) {
  42717. let staticVao;
  42718. ( { vaoGPU, staticVao } = this._createVao( renderObject.getAttributes() ) );
  42719. if ( staticVao ) {
  42720. renderObjectData.staticVao = vaoGPU;
  42721. renderObjectData.geometryId = renderObject.geometry.id;
  42722. }
  42723. }
  42724. }
  42725. const index = renderObject.getIndex();
  42726. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  42727. state.setVertexState( vaoGPU, indexGPU );
  42728. //
  42729. const lastObject = contextData.lastOcclusionObject;
  42730. if ( lastObject !== object && lastObject !== undefined ) {
  42731. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42732. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42733. contextData.occlusionQueryIndex ++;
  42734. }
  42735. if ( object.occlusionTest === true ) {
  42736. const query = gl.createQuery();
  42737. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  42738. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  42739. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42740. }
  42741. contextData.lastOcclusionObject = object;
  42742. }
  42743. //
  42744. const renderer = this.bufferRenderer;
  42745. if ( object.isPoints ) renderer.mode = gl.POINTS;
  42746. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  42747. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  42748. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  42749. else {
  42750. if ( material.wireframe === true ) {
  42751. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  42752. renderer.mode = gl.LINES;
  42753. } else {
  42754. renderer.mode = gl.TRIANGLES;
  42755. }
  42756. }
  42757. //
  42758. const { vertexCount, instanceCount } = drawParams;
  42759. let { firstVertex } = drawParams;
  42760. renderer.object = object;
  42761. if ( index !== null ) {
  42762. firstVertex *= index.array.BYTES_PER_ELEMENT;
  42763. const indexData = this.get( index );
  42764. renderer.index = index.count;
  42765. renderer.type = indexData.type;
  42766. } else {
  42767. renderer.index = 0;
  42768. }
  42769. const draw = () => {
  42770. if ( object.isBatchedMesh ) {
  42771. if ( object._multiDrawInstances !== null ) {
  42772. // @deprecated, r174
  42773. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  42774. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  42775. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  42776. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  42777. } else {
  42778. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  42779. }
  42780. } else if ( instanceCount > 1 ) {
  42781. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  42782. } else {
  42783. renderer.render( firstVertex, vertexCount );
  42784. }
  42785. };
  42786. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  42787. const cameraData = this.get( renderObject.camera );
  42788. const cameras = renderObject.camera.cameras;
  42789. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  42790. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  42791. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  42792. const indexesGPU = [];
  42793. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42794. const bufferGPU = gl.createBuffer();
  42795. data[ 0 ] = i;
  42796. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42797. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  42798. indexesGPU.push( bufferGPU );
  42799. }
  42800. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  42801. }
  42802. const cameraIndexData = this.get( cameraIndex );
  42803. const pixelRatio = this.renderer.getPixelRatio();
  42804. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42805. const subCamera = cameras[ i ];
  42806. if ( object.layers.test( subCamera.layers ) ) {
  42807. const vp = subCamera.viewport;
  42808. const x = vp.x * pixelRatio;
  42809. const y = vp.y * pixelRatio;
  42810. const width = vp.width * pixelRatio;
  42811. const height = vp.height * pixelRatio;
  42812. state.viewport(
  42813. Math.floor( x ),
  42814. Math.floor( renderObject.context.height - height - y ),
  42815. Math.floor( width ),
  42816. Math.floor( height )
  42817. );
  42818. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  42819. draw();
  42820. }
  42821. }
  42822. } else {
  42823. draw();
  42824. }
  42825. }
  42826. /**
  42827. * Explain why always null is returned.
  42828. *
  42829. * @param {RenderObject} renderObject - The render object.
  42830. * @return {boolean} Whether the render pipeline requires an update or not.
  42831. */
  42832. needsRenderUpdate( /*renderObject*/ ) {
  42833. return false;
  42834. }
  42835. /**
  42836. * Explain why no cache key is computed.
  42837. *
  42838. * @param {RenderObject} renderObject - The render object.
  42839. * @return {string} The cache key.
  42840. */
  42841. getRenderCacheKey( /*renderObject*/ ) {
  42842. return '';
  42843. }
  42844. // textures
  42845. /**
  42846. * Creates a default texture for the given texture that can be used
  42847. * as a placeholder until the actual texture is ready for usage.
  42848. *
  42849. * @param {Texture} texture - The texture to create a default texture for.
  42850. */
  42851. createDefaultTexture( texture ) {
  42852. this.textureUtils.createDefaultTexture( texture );
  42853. }
  42854. /**
  42855. * Defines a texture on the GPU for the given texture object.
  42856. *
  42857. * @param {Texture} texture - The texture.
  42858. * @param {Object} [options={}] - Optional configuration parameter.
  42859. */
  42860. createTexture( texture, options ) {
  42861. this.textureUtils.createTexture( texture, options );
  42862. }
  42863. /**
  42864. * Uploads the updated texture data to the GPU.
  42865. *
  42866. * @param {Texture} texture - The texture.
  42867. * @param {Object} [options={}] - Optional configuration parameter.
  42868. */
  42869. updateTexture( texture, options ) {
  42870. this.textureUtils.updateTexture( texture, options );
  42871. }
  42872. /**
  42873. * Generates mipmaps for the given texture.
  42874. *
  42875. * @param {Texture} texture - The texture.
  42876. */
  42877. generateMipmaps( texture ) {
  42878. this.textureUtils.generateMipmaps( texture );
  42879. }
  42880. /**
  42881. * Destroys the GPU data for the given texture object.
  42882. *
  42883. * @param {Texture} texture - The texture.
  42884. */
  42885. destroyTexture( texture ) {
  42886. this.textureUtils.destroyTexture( texture );
  42887. }
  42888. /**
  42889. * Returns texture data as a typed array.
  42890. *
  42891. * @async
  42892. * @param {Texture} texture - The texture to copy.
  42893. * @param {number} x - The x coordinate of the copy origin.
  42894. * @param {number} y - The y coordinate of the copy origin.
  42895. * @param {number} width - The width of the copy.
  42896. * @param {number} height - The height of the copy.
  42897. * @param {number} faceIndex - The face index.
  42898. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42899. */
  42900. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42901. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  42902. }
  42903. /**
  42904. * This method does nothing since WebGL 2 has no concept of samplers.
  42905. *
  42906. * @param {Texture} texture - The texture to create the sampler for.
  42907. */
  42908. createSampler( /*texture*/ ) {
  42909. //console.warn( 'Abstract class.' );
  42910. }
  42911. /**
  42912. * This method does nothing since WebGL 2 has no concept of samplers.
  42913. *
  42914. * @param {Texture} texture - The texture to destroy the sampler for.
  42915. */
  42916. destroySampler( /*texture*/ ) {}
  42917. // node builder
  42918. /**
  42919. * Returns a node builder for the given render object.
  42920. *
  42921. * @param {RenderObject} object - The render object.
  42922. * @param {Renderer} renderer - The renderer.
  42923. * @return {GLSLNodeBuilder} The node builder.
  42924. */
  42925. createNodeBuilder( object, renderer ) {
  42926. return new GLSLNodeBuilder( object, renderer );
  42927. }
  42928. // program
  42929. /**
  42930. * Creates a shader program from the given programmable stage.
  42931. *
  42932. * @param {ProgrammableStage} program - The programmable stage.
  42933. */
  42934. createProgram( program ) {
  42935. const gl = this.gl;
  42936. const { stage, code } = program;
  42937. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  42938. gl.shaderSource( shader, code );
  42939. gl.compileShader( shader );
  42940. this.set( program, {
  42941. shaderGPU: shader
  42942. } );
  42943. }
  42944. /**
  42945. * Destroys the shader program of the given programmable stage.
  42946. *
  42947. * @param {ProgrammableStage} program - The programmable stage.
  42948. */
  42949. destroyProgram( program ) {
  42950. this.delete( program );
  42951. }
  42952. /**
  42953. * Creates a render pipeline for the given render object.
  42954. *
  42955. * @param {RenderObject} renderObject - The render object.
  42956. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42957. */
  42958. createRenderPipeline( renderObject, promises ) {
  42959. const gl = this.gl;
  42960. const pipeline = renderObject.pipeline;
  42961. // Program
  42962. const { fragmentProgram, vertexProgram } = pipeline;
  42963. const programGPU = gl.createProgram();
  42964. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42965. const vertexShader = this.get( vertexProgram ).shaderGPU;
  42966. gl.attachShader( programGPU, fragmentShader );
  42967. gl.attachShader( programGPU, vertexShader );
  42968. gl.linkProgram( programGPU );
  42969. this.set( pipeline, {
  42970. programGPU,
  42971. fragmentShader,
  42972. vertexShader
  42973. } );
  42974. if ( promises !== null && this.parallel ) {
  42975. const p = new Promise( ( resolve /*, reject*/ ) => {
  42976. const parallel = this.parallel;
  42977. const checkStatus = () => {
  42978. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  42979. this._completeCompile( renderObject, pipeline );
  42980. resolve();
  42981. } else {
  42982. requestAnimationFrame( checkStatus );
  42983. }
  42984. };
  42985. checkStatus();
  42986. } );
  42987. promises.push( p );
  42988. return;
  42989. }
  42990. this._completeCompile( renderObject, pipeline );
  42991. }
  42992. /**
  42993. * Formats the source code of error messages.
  42994. *
  42995. * @private
  42996. * @param {string} string - The code.
  42997. * @param {number} errorLine - The error line.
  42998. * @return {string} The formatted code.
  42999. */
  43000. _handleSource( string, errorLine ) {
  43001. const lines = string.split( '\n' );
  43002. const lines2 = [];
  43003. const from = Math.max( errorLine - 6, 0 );
  43004. const to = Math.min( errorLine + 6, lines.length );
  43005. for ( let i = from; i < to; i ++ ) {
  43006. const line = i + 1;
  43007. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  43008. }
  43009. return lines2.join( '\n' );
  43010. }
  43011. /**
  43012. * Gets the shader compilation errors from the info log.
  43013. *
  43014. * @private
  43015. * @param {WebGL2RenderingContext} gl - The rendering context.
  43016. * @param {WebGLShader} shader - The WebGL shader object.
  43017. * @param {string} type - The shader type.
  43018. * @return {string} The shader errors.
  43019. */
  43020. _getShaderErrors( gl, shader, type ) {
  43021. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  43022. const errors = gl.getShaderInfoLog( shader ).trim();
  43023. if ( status && errors === '' ) return '';
  43024. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  43025. if ( errorMatches ) {
  43026. const errorLine = parseInt( errorMatches[ 1 ] );
  43027. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  43028. } else {
  43029. return errors;
  43030. }
  43031. }
  43032. /**
  43033. * Logs shader compilation errors.
  43034. *
  43035. * @private
  43036. * @param {WebGLProgram} programGPU - The WebGL program.
  43037. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  43038. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  43039. */
  43040. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  43041. if ( this.renderer.debug.checkShaderErrors ) {
  43042. const gl = this.gl;
  43043. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  43044. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  43045. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  43046. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  43047. } else {
  43048. // default error reporting
  43049. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  43050. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  43051. console.error(
  43052. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  43053. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  43054. 'Program Info Log: ' + programLog + '\n' +
  43055. vertexErrors + '\n' +
  43056. fragmentErrors
  43057. );
  43058. }
  43059. } else if ( programLog !== '' ) {
  43060. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  43061. }
  43062. }
  43063. }
  43064. /**
  43065. * Completes the shader program setup for the given render object.
  43066. *
  43067. * @private
  43068. * @param {RenderObject} renderObject - The render object.
  43069. * @param {RenderPipeline} pipeline - The render pipeline.
  43070. */
  43071. _completeCompile( renderObject, pipeline ) {
  43072. const { state, gl } = this;
  43073. const pipelineData = this.get( pipeline );
  43074. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  43075. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  43076. this._logProgramError( programGPU, fragmentShader, vertexShader );
  43077. }
  43078. state.useProgram( programGPU );
  43079. // Bindings
  43080. const bindings = renderObject.getBindings();
  43081. this._setupBindings( bindings, programGPU );
  43082. //
  43083. this.set( pipeline, {
  43084. programGPU
  43085. } );
  43086. }
  43087. /**
  43088. * Creates a compute pipeline for the given compute node.
  43089. *
  43090. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43091. * @param {Array<BindGroup>} bindings - The bindings.
  43092. */
  43093. createComputePipeline( computePipeline, bindings ) {
  43094. const { state, gl } = this;
  43095. // Program
  43096. const fragmentProgram = {
  43097. stage: 'fragment',
  43098. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  43099. };
  43100. this.createProgram( fragmentProgram );
  43101. const { computeProgram } = computePipeline;
  43102. const programGPU = gl.createProgram();
  43103. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  43104. const vertexShader = this.get( computeProgram ).shaderGPU;
  43105. const transforms = computeProgram.transforms;
  43106. const transformVaryingNames = [];
  43107. const transformAttributeNodes = [];
  43108. for ( let i = 0; i < transforms.length; i ++ ) {
  43109. const transform = transforms[ i ];
  43110. transformVaryingNames.push( transform.varyingName );
  43111. transformAttributeNodes.push( transform.attributeNode );
  43112. }
  43113. gl.attachShader( programGPU, fragmentShader );
  43114. gl.attachShader( programGPU, vertexShader );
  43115. gl.transformFeedbackVaryings(
  43116. programGPU,
  43117. transformVaryingNames,
  43118. gl.SEPARATE_ATTRIBS
  43119. );
  43120. gl.linkProgram( programGPU );
  43121. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  43122. this._logProgramError( programGPU, fragmentShader, vertexShader );
  43123. }
  43124. state.useProgram( programGPU );
  43125. // Bindings
  43126. this._setupBindings( bindings, programGPU );
  43127. const attributeNodes = computeProgram.attributes;
  43128. const attributes = [];
  43129. const transformBuffers = [];
  43130. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  43131. const attribute = attributeNodes[ i ].node.attribute;
  43132. attributes.push( attribute );
  43133. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43134. }
  43135. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  43136. const attribute = transformAttributeNodes[ i ].attribute;
  43137. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43138. const attributeData = this.get( attribute );
  43139. transformBuffers.push( attributeData );
  43140. }
  43141. //
  43142. this.set( computePipeline, {
  43143. programGPU,
  43144. transformBuffers,
  43145. attributes
  43146. } );
  43147. }
  43148. /**
  43149. * Creates bindings from the given bind group definition.
  43150. *
  43151. * @param {BindGroup} bindGroup - The bind group.
  43152. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43153. * @param {number} cacheIndex - The cache index.
  43154. * @param {number} version - The version.
  43155. */
  43156. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  43157. if ( this._knownBindings.has( bindings ) === false ) {
  43158. this._knownBindings.add( bindings );
  43159. let uniformBuffers = 0;
  43160. let textures = 0;
  43161. for ( const bindGroup of bindings ) {
  43162. this.set( bindGroup, {
  43163. textures: textures,
  43164. uniformBuffers: uniformBuffers
  43165. } );
  43166. for ( const binding of bindGroup.bindings ) {
  43167. if ( binding.isUniformBuffer ) uniformBuffers ++;
  43168. if ( binding.isSampledTexture ) textures ++;
  43169. }
  43170. }
  43171. }
  43172. this.updateBindings( bindGroup, bindings );
  43173. }
  43174. /**
  43175. * Updates the given bind group definition.
  43176. *
  43177. * @param {BindGroup} bindGroup - The bind group.
  43178. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43179. * @param {number} cacheIndex - The cache index.
  43180. * @param {number} version - The version.
  43181. */
  43182. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  43183. const { gl } = this;
  43184. const bindGroupData = this.get( bindGroup );
  43185. let i = bindGroupData.uniformBuffers;
  43186. let t = bindGroupData.textures;
  43187. for ( const binding of bindGroup.bindings ) {
  43188. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43189. const data = binding.buffer;
  43190. const bufferGPU = gl.createBuffer();
  43191. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  43192. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  43193. this.set( binding, {
  43194. index: i ++,
  43195. bufferGPU
  43196. } );
  43197. } else if ( binding.isSampledTexture ) {
  43198. const { textureGPU, glTextureType } = this.get( binding.texture );
  43199. this.set( binding, {
  43200. index: t ++,
  43201. textureGPU,
  43202. glTextureType
  43203. } );
  43204. }
  43205. }
  43206. }
  43207. /**
  43208. * Updates a buffer binding.
  43209. *
  43210. * @param {Buffer} binding - The buffer binding to update.
  43211. */
  43212. updateBinding( binding ) {
  43213. const gl = this.gl;
  43214. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43215. const bindingData = this.get( binding );
  43216. const bufferGPU = bindingData.bufferGPU;
  43217. const data = binding.buffer;
  43218. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  43219. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  43220. }
  43221. }
  43222. // attributes
  43223. /**
  43224. * Creates the GPU buffer of an indexed shader attribute.
  43225. *
  43226. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43227. */
  43228. createIndexAttribute( attribute ) {
  43229. const gl = this.gl;
  43230. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  43231. }
  43232. /**
  43233. * Creates the GPU buffer of a shader attribute.
  43234. *
  43235. * @param {BufferAttribute} attribute - The buffer attribute.
  43236. */
  43237. createAttribute( attribute ) {
  43238. if ( this.has( attribute ) ) return;
  43239. const gl = this.gl;
  43240. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43241. }
  43242. /**
  43243. * Creates the GPU buffer of a storage attribute.
  43244. *
  43245. * @param {BufferAttribute} attribute - The buffer attribute.
  43246. */
  43247. createStorageAttribute( attribute ) {
  43248. if ( this.has( attribute ) ) return;
  43249. const gl = this.gl;
  43250. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43251. }
  43252. /**
  43253. * Updates the GPU buffer of a shader attribute.
  43254. *
  43255. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43256. */
  43257. updateAttribute( attribute ) {
  43258. this.attributeUtils.updateAttribute( attribute );
  43259. }
  43260. /**
  43261. * Destroys the GPU buffer of a shader attribute.
  43262. *
  43263. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43264. */
  43265. destroyAttribute( attribute ) {
  43266. this.attributeUtils.destroyAttribute( attribute );
  43267. }
  43268. /**
  43269. * Checks if the given feature is supported by the backend.
  43270. *
  43271. * @param {string} name - The feature's name.
  43272. * @return {boolean} Whether the feature is supported or not.
  43273. */
  43274. hasFeature( name ) {
  43275. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  43276. const extensions = this.extensions;
  43277. for ( let i = 0; i < keysMatching.length; i ++ ) {
  43278. if ( extensions.has( keysMatching[ i ] ) ) return true;
  43279. }
  43280. return false;
  43281. }
  43282. /**
  43283. * Returns the maximum anisotropy texture filtering value.
  43284. *
  43285. * @return {number} The maximum anisotropy texture filtering value.
  43286. */
  43287. getMaxAnisotropy() {
  43288. return this.capabilities.getMaxAnisotropy();
  43289. }
  43290. /**
  43291. * Copies data of the given source texture to the given destination texture.
  43292. *
  43293. * @param {Texture} srcTexture - The source texture.
  43294. * @param {Texture} dstTexture - The destination texture.
  43295. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43296. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43297. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43298. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43299. */
  43300. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43301. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  43302. }
  43303. /**
  43304. * Copies the current bound framebuffer to the given texture.
  43305. *
  43306. * @param {Texture} texture - The destination texture.
  43307. * @param {RenderContext} renderContext - The render context.
  43308. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43309. */
  43310. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  43311. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  43312. }
  43313. /**
  43314. * Configures the active framebuffer from the given render context.
  43315. *
  43316. * @private
  43317. * @param {RenderContext} descriptor - The render context.
  43318. */
  43319. _setFramebuffer( descriptor ) {
  43320. const { gl, state } = this;
  43321. let currentFrameBuffer = null;
  43322. if ( descriptor.textures !== null ) {
  43323. const renderTarget = descriptor.renderTarget;
  43324. const renderTargetContextData = this.get( renderTarget );
  43325. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  43326. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  43327. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  43328. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  43329. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  43330. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  43331. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  43332. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  43333. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43334. const useMultisampledRTT = this._useMultisampledRTT( renderTarget );
  43335. const cacheKey = getCacheKey( descriptor );
  43336. let fb;
  43337. if ( isCube ) {
  43338. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  43339. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  43340. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  43341. fb = this._xrFramebuffer;
  43342. } else {
  43343. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  43344. fb = renderTargetContextData.framebuffers[ cacheKey ];
  43345. }
  43346. if ( fb === undefined ) {
  43347. fb = gl.createFramebuffer();
  43348. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  43349. const textures = descriptor.textures;
  43350. if ( isCube ) {
  43351. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  43352. const { textureGPU } = this.get( textures[ 0 ] );
  43353. const cubeFace = this.renderer._activeCubeFace;
  43354. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  43355. } else {
  43356. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  43357. for ( let i = 0; i < textures.length; i ++ ) {
  43358. const texture = textures[ i ];
  43359. const textureData = this.get( texture );
  43360. textureData.renderTarget = descriptor.renderTarget;
  43361. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  43362. const attachment = gl.COLOR_ATTACHMENT0 + i;
  43363. if ( isRenderTarget3D || isRenderTargetArray ) {
  43364. const layer = this.renderer._activeCubeFace;
  43365. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  43366. } else {
  43367. if ( hasExternalTextures && useMultisampledRTT ) {
  43368. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43369. } else {
  43370. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43371. }
  43372. }
  43373. }
  43374. state.drawBuffers( descriptor, fb );
  43375. }
  43376. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  43377. const renderbuffer = gl.createRenderbuffer();
  43378. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  43379. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  43380. } else {
  43381. if ( descriptor.depthTexture !== null ) {
  43382. const textureData = this.get( descriptor.depthTexture );
  43383. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43384. textureData.renderTarget = descriptor.renderTarget;
  43385. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  43386. if ( hasExternalTextures && useMultisampledRTT ) {
  43387. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43388. } else {
  43389. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43390. }
  43391. }
  43392. }
  43393. } else {
  43394. // rebind external XR textures
  43395. if ( isXRRenderTarget && hasExternalTextures ) {
  43396. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  43397. // rebind color
  43398. const textureData = this.get( descriptor.textures[ 0 ] );
  43399. if ( useMultisampledRTT ) {
  43400. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43401. } else {
  43402. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43403. }
  43404. // rebind depth
  43405. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43406. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  43407. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  43408. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  43409. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  43410. } else {
  43411. const textureData = this.get( descriptor.depthTexture );
  43412. if ( useMultisampledRTT ) {
  43413. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43414. } else {
  43415. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43416. }
  43417. }
  43418. }
  43419. }
  43420. if ( samples > 0 && useMultisampledRTT === false ) {
  43421. if ( msaaFb === undefined ) {
  43422. const invalidationArray = [];
  43423. msaaFb = gl.createFramebuffer();
  43424. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  43425. const msaaRenderbuffers = [];
  43426. const textures = descriptor.textures;
  43427. for ( let i = 0; i < textures.length; i ++ ) {
  43428. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  43429. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  43430. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  43431. if ( depthBuffer ) {
  43432. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43433. invalidationArray.push( depthStyle );
  43434. }
  43435. const texture = descriptor.textures[ i ];
  43436. const textureData = this.get( texture );
  43437. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  43438. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  43439. }
  43440. renderTargetContextData.msaaFrameBuffer = msaaFb;
  43441. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  43442. if ( depthRenderbuffer === undefined ) {
  43443. depthRenderbuffer = gl.createRenderbuffer();
  43444. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  43445. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  43446. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43447. invalidationArray.push( depthStyle );
  43448. }
  43449. renderTargetContextData.invalidationArray = invalidationArray;
  43450. }
  43451. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43452. } else {
  43453. currentFrameBuffer = fb;
  43454. }
  43455. }
  43456. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  43457. }
  43458. /**
  43459. * Computes the VAO key for the given index and attributes.
  43460. *
  43461. * @private
  43462. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  43463. * @return {string} The VAO key.
  43464. */
  43465. _getVaoKey( attributes ) {
  43466. let key = '';
  43467. for ( let i = 0; i < attributes.length; i ++ ) {
  43468. const attributeData = this.get( attributes[ i ] );
  43469. key += ':' + attributeData.id;
  43470. }
  43471. return key;
  43472. }
  43473. /**
  43474. * Creates a VAO from the index and attributes.
  43475. *
  43476. * @private
  43477. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  43478. * @return {Object} The VAO data.
  43479. */
  43480. _createVao( attributes ) {
  43481. const { gl } = this;
  43482. const vaoGPU = gl.createVertexArray();
  43483. let key = '';
  43484. let staticVao = true;
  43485. gl.bindVertexArray( vaoGPU );
  43486. for ( let i = 0; i < attributes.length; i ++ ) {
  43487. const attribute = attributes[ i ];
  43488. const attributeData = this.get( attribute );
  43489. key += ':' + attributeData.id;
  43490. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  43491. gl.enableVertexAttribArray( i );
  43492. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  43493. let stride, offset;
  43494. if ( attribute.isInterleavedBufferAttribute === true ) {
  43495. stride = attribute.data.stride * attributeData.bytesPerElement;
  43496. offset = attribute.offset * attributeData.bytesPerElement;
  43497. } else {
  43498. stride = 0;
  43499. offset = 0;
  43500. }
  43501. if ( attributeData.isInteger ) {
  43502. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  43503. } else {
  43504. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  43505. }
  43506. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  43507. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  43508. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  43509. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  43510. }
  43511. }
  43512. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  43513. this.vaoCache[ key ] = vaoGPU;
  43514. return { vaoGPU, staticVao };
  43515. }
  43516. /**
  43517. * Creates a transform feedback from the given transform buffers.
  43518. *
  43519. * @private
  43520. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  43521. * @return {WebGLTransformFeedback} The transform feedback.
  43522. */
  43523. _getTransformFeedback( transformBuffers ) {
  43524. let key = '';
  43525. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  43526. key += ':' + transformBuffers[ i ].id;
  43527. }
  43528. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  43529. if ( transformFeedbackGPU !== undefined ) {
  43530. return transformFeedbackGPU;
  43531. }
  43532. const { gl } = this;
  43533. transformFeedbackGPU = gl.createTransformFeedback();
  43534. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  43535. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  43536. const attributeData = transformBuffers[ i ];
  43537. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  43538. }
  43539. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  43540. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  43541. return transformFeedbackGPU;
  43542. }
  43543. /**
  43544. * Setups the given bindings.
  43545. *
  43546. * @private
  43547. * @param {Array<BindGroup>} bindings - The bindings.
  43548. * @param {WebGLProgram} programGPU - The WebGL program.
  43549. */
  43550. _setupBindings( bindings, programGPU ) {
  43551. const gl = this.gl;
  43552. for ( const bindGroup of bindings ) {
  43553. for ( const binding of bindGroup.bindings ) {
  43554. const bindingData = this.get( binding );
  43555. const index = bindingData.index;
  43556. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43557. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  43558. gl.uniformBlockBinding( programGPU, location, index );
  43559. } else if ( binding.isSampledTexture ) {
  43560. const location = gl.getUniformLocation( programGPU, binding.name );
  43561. gl.uniform1i( location, index );
  43562. }
  43563. }
  43564. }
  43565. }
  43566. /**
  43567. * Binds the given uniforms.
  43568. *
  43569. * @private
  43570. * @param {Array<BindGroup>} bindings - The bindings.
  43571. */
  43572. _bindUniforms( bindings ) {
  43573. const { gl, state } = this;
  43574. for ( const bindGroup of bindings ) {
  43575. for ( const binding of bindGroup.bindings ) {
  43576. const bindingData = this.get( binding );
  43577. const index = bindingData.index;
  43578. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43579. // TODO USE bindBufferRange to group multiple uniform buffers
  43580. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  43581. } else if ( binding.isSampledTexture ) {
  43582. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  43583. }
  43584. }
  43585. }
  43586. }
  43587. /**
  43588. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  43589. * should be used when MSAA is enabled.
  43590. *
  43591. * @private
  43592. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  43593. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  43594. */
  43595. _useMultisampledRTT( renderTarget ) {
  43596. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  43597. }
  43598. /**
  43599. * Frees internal resources.
  43600. */
  43601. dispose() {
  43602. const extension = this.extensions.get( 'WEBGL_lose_context' );
  43603. if ( extension ) extension.loseContext();
  43604. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  43605. }
  43606. }
  43607. const GPUPrimitiveTopology = {
  43608. PointList: 'point-list',
  43609. LineList: 'line-list',
  43610. LineStrip: 'line-strip',
  43611. TriangleList: 'triangle-list',
  43612. TriangleStrip: 'triangle-strip',
  43613. };
  43614. const GPUCompareFunction = {
  43615. Never: 'never',
  43616. Less: 'less',
  43617. Equal: 'equal',
  43618. LessEqual: 'less-equal',
  43619. Greater: 'greater',
  43620. NotEqual: 'not-equal',
  43621. GreaterEqual: 'greater-equal',
  43622. Always: 'always'
  43623. };
  43624. const GPUStoreOp = {
  43625. Store: 'store',
  43626. Discard: 'discard'
  43627. };
  43628. const GPULoadOp = {
  43629. Load: 'load',
  43630. Clear: 'clear'
  43631. };
  43632. const GPUFrontFace = {
  43633. CCW: 'ccw',
  43634. CW: 'cw'
  43635. };
  43636. const GPUCullMode = {
  43637. None: 'none',
  43638. Front: 'front',
  43639. Back: 'back'
  43640. };
  43641. const GPUIndexFormat = {
  43642. Uint16: 'uint16',
  43643. Uint32: 'uint32'
  43644. };
  43645. const GPUTextureFormat = {
  43646. // 8-bit formats
  43647. R8Unorm: 'r8unorm',
  43648. R8Snorm: 'r8snorm',
  43649. R8Uint: 'r8uint',
  43650. R8Sint: 'r8sint',
  43651. // 16-bit formats
  43652. R16Uint: 'r16uint',
  43653. R16Sint: 'r16sint',
  43654. R16Float: 'r16float',
  43655. RG8Unorm: 'rg8unorm',
  43656. RG8Snorm: 'rg8snorm',
  43657. RG8Uint: 'rg8uint',
  43658. RG8Sint: 'rg8sint',
  43659. // 32-bit formats
  43660. R32Uint: 'r32uint',
  43661. R32Sint: 'r32sint',
  43662. R32Float: 'r32float',
  43663. RG16Uint: 'rg16uint',
  43664. RG16Sint: 'rg16sint',
  43665. RG16Float: 'rg16float',
  43666. RGBA8Unorm: 'rgba8unorm',
  43667. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  43668. RGBA8Snorm: 'rgba8snorm',
  43669. RGBA8Uint: 'rgba8uint',
  43670. RGBA8Sint: 'rgba8sint',
  43671. BGRA8Unorm: 'bgra8unorm',
  43672. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  43673. // Packed 32-bit formats
  43674. RGB9E5UFloat: 'rgb9e5ufloat',
  43675. RGB10A2Unorm: 'rgb10a2unorm',
  43676. RG11B10UFloat: 'rgb10a2unorm',
  43677. // 64-bit formats
  43678. RG32Uint: 'rg32uint',
  43679. RG32Sint: 'rg32sint',
  43680. RG32Float: 'rg32float',
  43681. RGBA16Uint: 'rgba16uint',
  43682. RGBA16Sint: 'rgba16sint',
  43683. RGBA16Float: 'rgba16float',
  43684. // 128-bit formats
  43685. RGBA32Uint: 'rgba32uint',
  43686. RGBA32Sint: 'rgba32sint',
  43687. RGBA32Float: 'rgba32float',
  43688. // Depth and stencil formats
  43689. Stencil8: 'stencil8',
  43690. Depth16Unorm: 'depth16unorm',
  43691. Depth24Plus: 'depth24plus',
  43692. Depth24PlusStencil8: 'depth24plus-stencil8',
  43693. Depth32Float: 'depth32float',
  43694. // 'depth32float-stencil8' extension
  43695. Depth32FloatStencil8: 'depth32float-stencil8',
  43696. // BC compressed formats usable if 'texture-compression-bc' is both
  43697. // supported by the device/user agent and enabled in requestDevice.
  43698. BC1RGBAUnorm: 'bc1-rgba-unorm',
  43699. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  43700. BC2RGBAUnorm: 'bc2-rgba-unorm',
  43701. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  43702. BC3RGBAUnorm: 'bc3-rgba-unorm',
  43703. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  43704. BC4RUnorm: 'bc4-r-unorm',
  43705. BC4RSnorm: 'bc4-r-snorm',
  43706. BC5RGUnorm: 'bc5-rg-unorm',
  43707. BC5RGSnorm: 'bc5-rg-snorm',
  43708. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  43709. BC6HRGBFloat: 'bc6h-rgb-float',
  43710. BC7RGBAUnorm: 'bc7-rgba-unorm',
  43711. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  43712. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  43713. // supported by the device/user agent and enabled in requestDevice.
  43714. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  43715. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  43716. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  43717. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  43718. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  43719. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  43720. EACR11Unorm: 'eac-r11unorm',
  43721. EACR11Snorm: 'eac-r11snorm',
  43722. EACRG11Unorm: 'eac-rg11unorm',
  43723. EACRG11Snorm: 'eac-rg11snorm',
  43724. // ASTC compressed formats usable if 'texture-compression-astc' is both
  43725. // supported by the device/user agent and enabled in requestDevice.
  43726. ASTC4x4Unorm: 'astc-4x4-unorm',
  43727. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  43728. ASTC5x4Unorm: 'astc-5x4-unorm',
  43729. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  43730. ASTC5x5Unorm: 'astc-5x5-unorm',
  43731. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  43732. ASTC6x5Unorm: 'astc-6x5-unorm',
  43733. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  43734. ASTC6x6Unorm: 'astc-6x6-unorm',
  43735. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  43736. ASTC8x5Unorm: 'astc-8x5-unorm',
  43737. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  43738. ASTC8x6Unorm: 'astc-8x6-unorm',
  43739. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  43740. ASTC8x8Unorm: 'astc-8x8-unorm',
  43741. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  43742. ASTC10x5Unorm: 'astc-10x5-unorm',
  43743. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  43744. ASTC10x6Unorm: 'astc-10x6-unorm',
  43745. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  43746. ASTC10x8Unorm: 'astc-10x8-unorm',
  43747. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  43748. ASTC10x10Unorm: 'astc-10x10-unorm',
  43749. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  43750. ASTC12x10Unorm: 'astc-12x10-unorm',
  43751. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  43752. ASTC12x12Unorm: 'astc-12x12-unorm',
  43753. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  43754. };
  43755. const GPUAddressMode = {
  43756. ClampToEdge: 'clamp-to-edge',
  43757. Repeat: 'repeat',
  43758. MirrorRepeat: 'mirror-repeat'
  43759. };
  43760. const GPUFilterMode = {
  43761. Linear: 'linear',
  43762. Nearest: 'nearest'
  43763. };
  43764. const GPUBlendFactor = {
  43765. Zero: 'zero',
  43766. One: 'one',
  43767. Src: 'src',
  43768. OneMinusSrc: 'one-minus-src',
  43769. SrcAlpha: 'src-alpha',
  43770. OneMinusSrcAlpha: 'one-minus-src-alpha',
  43771. Dst: 'dst',
  43772. OneMinusDstColor: 'one-minus-dst',
  43773. DstAlpha: 'dst-alpha',
  43774. OneMinusDstAlpha: 'one-minus-dst-alpha',
  43775. SrcAlphaSaturated: 'src-alpha-saturated',
  43776. Constant: 'constant',
  43777. OneMinusConstant: 'one-minus-constant'
  43778. };
  43779. const GPUBlendOperation = {
  43780. Add: 'add',
  43781. Subtract: 'subtract',
  43782. ReverseSubtract: 'reverse-subtract',
  43783. Min: 'min',
  43784. Max: 'max'
  43785. };
  43786. const GPUColorWriteFlags = {
  43787. None: 0,
  43788. Red: 0x1,
  43789. Green: 0x2,
  43790. Blue: 0x4,
  43791. Alpha: 0x8,
  43792. All: 0xF
  43793. };
  43794. const GPUStencilOperation = {
  43795. Keep: 'keep',
  43796. Zero: 'zero',
  43797. Replace: 'replace',
  43798. Invert: 'invert',
  43799. IncrementClamp: 'increment-clamp',
  43800. DecrementClamp: 'decrement-clamp',
  43801. IncrementWrap: 'increment-wrap',
  43802. DecrementWrap: 'decrement-wrap'
  43803. };
  43804. const GPUBufferBindingType = {
  43805. Uniform: 'uniform',
  43806. Storage: 'storage',
  43807. ReadOnlyStorage: 'read-only-storage'
  43808. };
  43809. const GPUStorageTextureAccess = {
  43810. WriteOnly: 'write-only',
  43811. ReadOnly: 'read-only',
  43812. ReadWrite: 'read-write',
  43813. };
  43814. const GPUTextureSampleType = {
  43815. Float: 'float',
  43816. UnfilterableFloat: 'unfilterable-float',
  43817. Depth: 'depth',
  43818. SInt: 'sint',
  43819. UInt: 'uint'
  43820. };
  43821. const GPUTextureDimension = {
  43822. OneD: '1d',
  43823. TwoD: '2d',
  43824. ThreeD: '3d'
  43825. };
  43826. const GPUTextureViewDimension = {
  43827. OneD: '1d',
  43828. TwoD: '2d',
  43829. TwoDArray: '2d-array',
  43830. Cube: 'cube',
  43831. CubeArray: 'cube-array',
  43832. ThreeD: '3d'
  43833. };
  43834. const GPUTextureAspect = {
  43835. All: 'all',
  43836. StencilOnly: 'stencil-only',
  43837. DepthOnly: 'depth-only'
  43838. };
  43839. const GPUInputStepMode = {
  43840. Vertex: 'vertex',
  43841. Instance: 'instance'
  43842. };
  43843. const GPUFeatureName = {
  43844. DepthClipControl: 'depth-clip-control',
  43845. Depth32FloatStencil8: 'depth32float-stencil8',
  43846. TextureCompressionBC: 'texture-compression-bc',
  43847. TextureCompressionETC2: 'texture-compression-etc2',
  43848. TextureCompressionASTC: 'texture-compression-astc',
  43849. TimestampQuery: 'timestamp-query',
  43850. IndirectFirstInstance: 'indirect-first-instance',
  43851. ShaderF16: 'shader-f16',
  43852. RG11B10UFloat: 'rg11b10ufloat-renderable',
  43853. BGRA8UNormStorage: 'bgra8unorm-storage',
  43854. Float32Filterable: 'float32-filterable',
  43855. ClipDistances: 'clip-distances',
  43856. DualSourceBlending: 'dual-source-blending',
  43857. Subgroups: 'subgroups'
  43858. };
  43859. /**
  43860. * Represents a sampler binding type.
  43861. *
  43862. * @private
  43863. * @augments Binding
  43864. */
  43865. class Sampler extends Binding {
  43866. /**
  43867. * Constructs a new sampler.
  43868. *
  43869. * @param {string} name - The samplers's name.
  43870. * @param {?Texture} texture - The texture this binding is referring to.
  43871. */
  43872. constructor( name, texture ) {
  43873. super( name );
  43874. /**
  43875. * The texture the sampler is referring to.
  43876. *
  43877. * @type {?Texture}
  43878. */
  43879. this.texture = texture;
  43880. /**
  43881. * The binding's version.
  43882. *
  43883. * @type {number}
  43884. */
  43885. this.version = texture ? texture.version : 0;
  43886. /**
  43887. * This flag can be used for type testing.
  43888. *
  43889. * @type {boolean}
  43890. * @readonly
  43891. * @default true
  43892. */
  43893. this.isSampler = true;
  43894. }
  43895. }
  43896. /**
  43897. * A special form of sampler binding type.
  43898. * It's texture value is managed by a node object.
  43899. *
  43900. * @private
  43901. * @augments Sampler
  43902. */
  43903. class NodeSampler extends Sampler {
  43904. /**
  43905. * Constructs a new node-based sampler.
  43906. *
  43907. * @param {string} name - The samplers's name.
  43908. * @param {TextureNode} textureNode - The texture node.
  43909. * @param {UniformGroupNode} groupNode - The uniform group node.
  43910. */
  43911. constructor( name, textureNode, groupNode ) {
  43912. super( name, textureNode ? textureNode.value : null );
  43913. /**
  43914. * The texture node.
  43915. *
  43916. * @type {TextureNode}
  43917. */
  43918. this.textureNode = textureNode;
  43919. /**
  43920. * The uniform group node.
  43921. *
  43922. * @type {UniformGroupNode}
  43923. */
  43924. this.groupNode = groupNode;
  43925. }
  43926. /**
  43927. * Updates the texture value of this sampler.
  43928. */
  43929. update() {
  43930. this.texture = this.textureNode.value;
  43931. }
  43932. }
  43933. /**
  43934. * Represents a storage buffer binding type.
  43935. *
  43936. * @private
  43937. * @augments Buffer
  43938. */
  43939. class StorageBuffer extends Buffer {
  43940. /**
  43941. * Constructs a new uniform buffer.
  43942. *
  43943. * @param {string} name - The buffer's name.
  43944. * @param {BufferAttribute} attribute - The buffer attribute.
  43945. */
  43946. constructor( name, attribute ) {
  43947. super( name, attribute ? attribute.array : null );
  43948. /**
  43949. * This flag can be used for type testing.
  43950. *
  43951. * @type {BufferAttribute}
  43952. */
  43953. this.attribute = attribute;
  43954. /**
  43955. * This flag can be used for type testing.
  43956. *
  43957. * @type {boolean}
  43958. * @readonly
  43959. * @default true
  43960. */
  43961. this.isStorageBuffer = true;
  43962. }
  43963. }
  43964. let _id = 0;
  43965. /**
  43966. * A special form of storage buffer binding type.
  43967. * It's buffer value is managed by a node object.
  43968. *
  43969. * @private
  43970. * @augments StorageBuffer
  43971. */
  43972. class NodeStorageBuffer extends StorageBuffer {
  43973. /**
  43974. * Constructs a new node-based storage buffer.
  43975. *
  43976. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  43977. * @param {UniformGroupNode} groupNode - The uniform group node.
  43978. */
  43979. constructor( nodeUniform, groupNode ) {
  43980. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  43981. /**
  43982. * The node uniform.
  43983. *
  43984. * @type {StorageBufferNode}
  43985. */
  43986. this.nodeUniform = nodeUniform;
  43987. /**
  43988. * The access type.
  43989. *
  43990. * @type {string}
  43991. */
  43992. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  43993. /**
  43994. * The uniform group node.
  43995. *
  43996. * @type {UniformGroupNode}
  43997. */
  43998. this.groupNode = groupNode;
  43999. }
  44000. /**
  44001. * The storage buffer.
  44002. *
  44003. * @type {BufferAttribute}
  44004. */
  44005. get buffer() {
  44006. return this.nodeUniform.value;
  44007. }
  44008. }
  44009. /**
  44010. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  44011. *
  44012. * @private
  44013. */
  44014. class WebGPUTexturePassUtils extends DataMap {
  44015. /**
  44016. * Constructs a new utility object.
  44017. *
  44018. * @param {GPUDevice} device - The WebGPU device.
  44019. */
  44020. constructor( device ) {
  44021. super();
  44022. /**
  44023. * The WebGPU device.
  44024. *
  44025. * @type {GPUDevice}
  44026. */
  44027. this.device = device;
  44028. const mipmapVertexSource = `
  44029. struct VarysStruct {
  44030. @builtin( position ) Position: vec4<f32>,
  44031. @location( 0 ) vTex : vec2<f32>
  44032. };
  44033. @vertex
  44034. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  44035. var Varys : VarysStruct;
  44036. var pos = array< vec2<f32>, 4 >(
  44037. vec2<f32>( -1.0, 1.0 ),
  44038. vec2<f32>( 1.0, 1.0 ),
  44039. vec2<f32>( -1.0, -1.0 ),
  44040. vec2<f32>( 1.0, -1.0 )
  44041. );
  44042. var tex = array< vec2<f32>, 4 >(
  44043. vec2<f32>( 0.0, 0.0 ),
  44044. vec2<f32>( 1.0, 0.0 ),
  44045. vec2<f32>( 0.0, 1.0 ),
  44046. vec2<f32>( 1.0, 1.0 )
  44047. );
  44048. Varys.vTex = tex[ vertexIndex ];
  44049. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  44050. return Varys;
  44051. }
  44052. `;
  44053. const mipmapFragmentSource = `
  44054. @group( 0 ) @binding( 0 )
  44055. var imgSampler : sampler;
  44056. @group( 0 ) @binding( 1 )
  44057. var img : texture_2d<f32>;
  44058. @fragment
  44059. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  44060. return textureSample( img, imgSampler, vTex );
  44061. }
  44062. `;
  44063. const flipYFragmentSource = `
  44064. @group( 0 ) @binding( 0 )
  44065. var imgSampler : sampler;
  44066. @group( 0 ) @binding( 1 )
  44067. var img : texture_2d<f32>;
  44068. @fragment
  44069. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  44070. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  44071. }
  44072. `;
  44073. /**
  44074. * The mipmap GPU sampler.
  44075. *
  44076. * @type {GPUSampler}
  44077. */
  44078. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  44079. /**
  44080. * The flipY GPU sampler.
  44081. *
  44082. * @type {GPUSampler}
  44083. */
  44084. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  44085. /**
  44086. * A cache for GPU render pipelines used for copy/transfer passes.
  44087. * Every texture format requires a unique pipeline.
  44088. *
  44089. * @type {Object<string,GPURenderPipeline>}
  44090. */
  44091. this.transferPipelines = {};
  44092. /**
  44093. * A cache for GPU render pipelines used for flipY passes.
  44094. * Every texture format requires a unique pipeline.
  44095. *
  44096. * @type {Object<string,GPURenderPipeline>}
  44097. */
  44098. this.flipYPipelines = {};
  44099. /**
  44100. * The mipmap vertex shader module.
  44101. *
  44102. * @type {GPUShaderModule}
  44103. */
  44104. this.mipmapVertexShaderModule = device.createShaderModule( {
  44105. label: 'mipmapVertex',
  44106. code: mipmapVertexSource
  44107. } );
  44108. /**
  44109. * The mipmap fragment shader module.
  44110. *
  44111. * @type {GPUShaderModule}
  44112. */
  44113. this.mipmapFragmentShaderModule = device.createShaderModule( {
  44114. label: 'mipmapFragment',
  44115. code: mipmapFragmentSource
  44116. } );
  44117. /**
  44118. * The flipY fragment shader module.
  44119. *
  44120. * @type {GPUShaderModule}
  44121. */
  44122. this.flipYFragmentShaderModule = device.createShaderModule( {
  44123. label: 'flipYFragment',
  44124. code: flipYFragmentSource
  44125. } );
  44126. }
  44127. /**
  44128. * Returns a render pipeline for the internal copy render pass. The pass
  44129. * requires a unique render pipeline for each texture format.
  44130. *
  44131. * @param {string} format - The GPU texture format
  44132. * @return {GPURenderPipeline} The GPU render pipeline.
  44133. */
  44134. getTransferPipeline( format ) {
  44135. let pipeline = this.transferPipelines[ format ];
  44136. if ( pipeline === undefined ) {
  44137. pipeline = this.device.createRenderPipeline( {
  44138. label: `mipmap-${ format }`,
  44139. vertex: {
  44140. module: this.mipmapVertexShaderModule,
  44141. entryPoint: 'main'
  44142. },
  44143. fragment: {
  44144. module: this.mipmapFragmentShaderModule,
  44145. entryPoint: 'main',
  44146. targets: [ { format } ]
  44147. },
  44148. primitive: {
  44149. topology: GPUPrimitiveTopology.TriangleStrip,
  44150. stripIndexFormat: GPUIndexFormat.Uint32
  44151. },
  44152. layout: 'auto'
  44153. } );
  44154. this.transferPipelines[ format ] = pipeline;
  44155. }
  44156. return pipeline;
  44157. }
  44158. /**
  44159. * Returns a render pipeline for the flipY render pass. The pass
  44160. * requires a unique render pipeline for each texture format.
  44161. *
  44162. * @param {string} format - The GPU texture format
  44163. * @return {GPURenderPipeline} The GPU render pipeline.
  44164. */
  44165. getFlipYPipeline( format ) {
  44166. let pipeline = this.flipYPipelines[ format ];
  44167. if ( pipeline === undefined ) {
  44168. pipeline = this.device.createRenderPipeline( {
  44169. label: `flipY-${ format }`,
  44170. vertex: {
  44171. module: this.mipmapVertexShaderModule,
  44172. entryPoint: 'main'
  44173. },
  44174. fragment: {
  44175. module: this.flipYFragmentShaderModule,
  44176. entryPoint: 'main',
  44177. targets: [ { format } ]
  44178. },
  44179. primitive: {
  44180. topology: GPUPrimitiveTopology.TriangleStrip,
  44181. stripIndexFormat: GPUIndexFormat.Uint32
  44182. },
  44183. layout: 'auto'
  44184. } );
  44185. this.flipYPipelines[ format ] = pipeline;
  44186. }
  44187. return pipeline;
  44188. }
  44189. /**
  44190. * Flip the contents of the given GPU texture along its vertical axis.
  44191. *
  44192. * @param {GPUTexture} textureGPU - The GPU texture object.
  44193. * @param {Object} textureGPUDescriptor - The texture descriptor.
  44194. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44195. */
  44196. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  44197. const format = textureGPUDescriptor.format;
  44198. const { width, height } = textureGPUDescriptor.size;
  44199. const transferPipeline = this.getTransferPipeline( format );
  44200. const flipYPipeline = this.getFlipYPipeline( format );
  44201. const tempTexture = this.device.createTexture( {
  44202. size: { width, height, depthOrArrayLayers: 1 },
  44203. format,
  44204. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  44205. } );
  44206. const srcView = textureGPU.createView( {
  44207. baseMipLevel: 0,
  44208. mipLevelCount: 1,
  44209. dimension: GPUTextureViewDimension.TwoD,
  44210. baseArrayLayer
  44211. } );
  44212. const dstView = tempTexture.createView( {
  44213. baseMipLevel: 0,
  44214. mipLevelCount: 1,
  44215. dimension: GPUTextureViewDimension.TwoD,
  44216. baseArrayLayer: 0
  44217. } );
  44218. const commandEncoder = this.device.createCommandEncoder( {} );
  44219. const pass = ( pipeline, sourceView, destinationView ) => {
  44220. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  44221. const bindGroup = this.device.createBindGroup( {
  44222. layout: bindGroupLayout,
  44223. entries: [ {
  44224. binding: 0,
  44225. resource: this.flipYSampler
  44226. }, {
  44227. binding: 1,
  44228. resource: sourceView
  44229. } ]
  44230. } );
  44231. const passEncoder = commandEncoder.beginRenderPass( {
  44232. colorAttachments: [ {
  44233. view: destinationView,
  44234. loadOp: GPULoadOp.Clear,
  44235. storeOp: GPUStoreOp.Store,
  44236. clearValue: [ 0, 0, 0, 0 ]
  44237. } ]
  44238. } );
  44239. passEncoder.setPipeline( pipeline );
  44240. passEncoder.setBindGroup( 0, bindGroup );
  44241. passEncoder.draw( 4, 1, 0, 0 );
  44242. passEncoder.end();
  44243. };
  44244. pass( transferPipeline, srcView, dstView );
  44245. pass( flipYPipeline, dstView, srcView );
  44246. this.device.queue.submit( [ commandEncoder.finish() ] );
  44247. tempTexture.destroy();
  44248. }
  44249. /**
  44250. * Generates mipmaps for the given GPU texture.
  44251. *
  44252. * @param {GPUTexture} textureGPU - The GPU texture object.
  44253. * @param {Object} textureGPUDescriptor - The texture descriptor.
  44254. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44255. */
  44256. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  44257. const textureData = this.get( textureGPU );
  44258. if ( textureData.useCount === undefined ) {
  44259. textureData.useCount = 0;
  44260. textureData.layers = [];
  44261. }
  44262. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  44263. const commandEncoder = this.device.createCommandEncoder( {} );
  44264. this._mipmapRunBundles( commandEncoder, passes );
  44265. this.device.queue.submit( [ commandEncoder.finish() ] );
  44266. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  44267. textureData.useCount ++;
  44268. }
  44269. /**
  44270. * Since multiple copy render passes are required to generate mipmaps, the passes
  44271. * are managed as render bundles to improve performance.
  44272. *
  44273. * @param {GPUTexture} textureGPU - The GPU texture object.
  44274. * @param {Object} textureGPUDescriptor - The texture descriptor.
  44275. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  44276. * @return {Array<Object>} An array of render bundles.
  44277. */
  44278. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  44279. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  44280. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  44281. let srcView = textureGPU.createView( {
  44282. baseMipLevel: 0,
  44283. mipLevelCount: 1,
  44284. dimension: GPUTextureViewDimension.TwoD,
  44285. baseArrayLayer
  44286. } );
  44287. const passes = [];
  44288. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  44289. const bindGroup = this.device.createBindGroup( {
  44290. layout: bindGroupLayout,
  44291. entries: [ {
  44292. binding: 0,
  44293. resource: this.mipmapSampler
  44294. }, {
  44295. binding: 1,
  44296. resource: srcView
  44297. } ]
  44298. } );
  44299. const dstView = textureGPU.createView( {
  44300. baseMipLevel: i,
  44301. mipLevelCount: 1,
  44302. dimension: GPUTextureViewDimension.TwoD,
  44303. baseArrayLayer
  44304. } );
  44305. const passDescriptor = {
  44306. colorAttachments: [ {
  44307. view: dstView,
  44308. loadOp: GPULoadOp.Clear,
  44309. storeOp: GPUStoreOp.Store,
  44310. clearValue: [ 0, 0, 0, 0 ]
  44311. } ]
  44312. };
  44313. const passEncoder = this.device.createRenderBundleEncoder( {
  44314. colorFormats: [ textureGPUDescriptor.format ]
  44315. } );
  44316. passEncoder.setPipeline( pipeline );
  44317. passEncoder.setBindGroup( 0, bindGroup );
  44318. passEncoder.draw( 4, 1, 0, 0 );
  44319. passes.push( {
  44320. renderBundles: [ passEncoder.finish() ],
  44321. passDescriptor
  44322. } );
  44323. srcView = dstView;
  44324. }
  44325. return passes;
  44326. }
  44327. /**
  44328. * Executes the render bundles.
  44329. *
  44330. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  44331. * @param {Array<Object>} passes - An array of render bundles.
  44332. */
  44333. _mipmapRunBundles( commandEncoder, passes ) {
  44334. const levels = passes.length;
  44335. for ( let i = 0; i < levels; i ++ ) {
  44336. const pass = passes[ i ];
  44337. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  44338. passEncoder.executeBundles( pass.renderBundles );
  44339. passEncoder.end();
  44340. }
  44341. }
  44342. }
  44343. const _compareToWebGPU = {
  44344. [ NeverCompare ]: 'never',
  44345. [ LessCompare ]: 'less',
  44346. [ EqualCompare ]: 'equal',
  44347. [ LessEqualCompare ]: 'less-equal',
  44348. [ GreaterCompare ]: 'greater',
  44349. [ GreaterEqualCompare ]: 'greater-equal',
  44350. [ AlwaysCompare ]: 'always',
  44351. [ NotEqualCompare ]: 'not-equal'
  44352. };
  44353. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  44354. /**
  44355. * A WebGPU backend utility module for managing textures.
  44356. *
  44357. * @private
  44358. */
  44359. class WebGPUTextureUtils {
  44360. /**
  44361. * Constructs a new utility object.
  44362. *
  44363. * @param {WebGPUBackend} backend - The WebGPU backend.
  44364. */
  44365. constructor( backend ) {
  44366. /**
  44367. * A reference to the WebGPU backend.
  44368. *
  44369. * @type {WebGPUBackend}
  44370. */
  44371. this.backend = backend;
  44372. /**
  44373. * A reference to the pass utils.
  44374. *
  44375. * @type {?WebGPUTexturePassUtils}
  44376. * @default null
  44377. */
  44378. this._passUtils = null;
  44379. /**
  44380. * A dictionary for managing default textures. The key
  44381. * is the texture format, the value the texture object.
  44382. *
  44383. * @type {Object<string,Texture>}
  44384. */
  44385. this.defaultTexture = {};
  44386. /**
  44387. * A dictionary for managing default cube textures. The key
  44388. * is the texture format, the value the texture object.
  44389. *
  44390. * @type {Object<string,CubeTexture>}
  44391. */
  44392. this.defaultCubeTexture = {};
  44393. /**
  44394. * A default video frame.
  44395. *
  44396. * @type {?VideoFrame}
  44397. * @default null
  44398. */
  44399. this.defaultVideoFrame = null;
  44400. /**
  44401. * Represents the color attachment of the default framebuffer.
  44402. *
  44403. * @type {?GPUTexture}
  44404. * @default null
  44405. */
  44406. this.colorBuffer = null;
  44407. /**
  44408. * Represents the depth attachment of the default framebuffer.
  44409. *
  44410. * @type {DepthTexture}
  44411. */
  44412. this.depthTexture = new DepthTexture();
  44413. this.depthTexture.name = 'depthBuffer';
  44414. }
  44415. /**
  44416. * Creates a GPU sampler for the given texture.
  44417. *
  44418. * @param {Texture} texture - The texture to create the sampler for.
  44419. */
  44420. createSampler( texture ) {
  44421. const backend = this.backend;
  44422. const device = backend.device;
  44423. const textureGPU = backend.get( texture );
  44424. const samplerDescriptorGPU = {
  44425. addressModeU: this._convertAddressMode( texture.wrapS ),
  44426. addressModeV: this._convertAddressMode( texture.wrapT ),
  44427. addressModeW: this._convertAddressMode( texture.wrapR ),
  44428. magFilter: this._convertFilterMode( texture.magFilter ),
  44429. minFilter: this._convertFilterMode( texture.minFilter ),
  44430. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  44431. maxAnisotropy: 1
  44432. };
  44433. // anisotropy can only be used when all filter modes are set to linear.
  44434. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  44435. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  44436. }
  44437. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  44438. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  44439. }
  44440. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  44441. }
  44442. /**
  44443. * Creates a default texture for the given texture that can be used
  44444. * as a placeholder until the actual texture is ready for usage.
  44445. *
  44446. * @param {Texture} texture - The texture to create a default texture for.
  44447. */
  44448. createDefaultTexture( texture ) {
  44449. let textureGPU;
  44450. const format = getFormat( texture );
  44451. if ( texture.isCubeTexture ) {
  44452. textureGPU = this._getDefaultCubeTextureGPU( format );
  44453. } else if ( texture.isVideoTexture ) {
  44454. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  44455. } else {
  44456. textureGPU = this._getDefaultTextureGPU( format );
  44457. }
  44458. this.backend.get( texture ).texture = textureGPU;
  44459. }
  44460. /**
  44461. * Defines a texture on the GPU for the given texture object.
  44462. *
  44463. * @param {Texture} texture - The texture.
  44464. * @param {Object} [options={}] - Optional configuration parameter.
  44465. */
  44466. createTexture( texture, options = {} ) {
  44467. const backend = this.backend;
  44468. const textureData = backend.get( texture );
  44469. if ( textureData.initialized ) {
  44470. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  44471. }
  44472. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  44473. if ( options.levels === undefined ) options.levels = 1;
  44474. if ( options.depth === undefined ) options.depth = 1;
  44475. const { width, height, depth, levels } = options;
  44476. if ( texture.isFramebufferTexture ) {
  44477. if ( options.renderTarget ) {
  44478. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  44479. } else {
  44480. options.format = this.backend.utils.getPreferredCanvasFormat();
  44481. }
  44482. }
  44483. const dimension = this._getDimension( texture );
  44484. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  44485. textureData.format = format;
  44486. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  44487. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  44488. if ( texture.isStorageTexture === true ) {
  44489. usage |= GPUTextureUsage.STORAGE_BINDING;
  44490. }
  44491. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  44492. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  44493. }
  44494. const textureDescriptorGPU = {
  44495. label: texture.name,
  44496. size: {
  44497. width: width,
  44498. height: height,
  44499. depthOrArrayLayers: depth,
  44500. },
  44501. mipLevelCount: levels,
  44502. sampleCount: primarySamples,
  44503. dimension: dimension,
  44504. format: format,
  44505. usage: usage
  44506. };
  44507. // texture creation
  44508. if ( texture.isVideoTexture ) {
  44509. const video = texture.source.data;
  44510. const videoFrame = new VideoFrame( video );
  44511. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  44512. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  44513. videoFrame.close();
  44514. textureData.externalTexture = video;
  44515. } else {
  44516. if ( format === undefined ) {
  44517. console.warn( 'WebGPURenderer: Texture format not supported.' );
  44518. this.createDefaultTexture( texture );
  44519. return;
  44520. }
  44521. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  44522. }
  44523. if ( isMSAA ) {
  44524. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  44525. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  44526. msaaTextureDescriptorGPU.sampleCount = samples;
  44527. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  44528. }
  44529. textureData.initialized = true;
  44530. textureData.textureDescriptorGPU = textureDescriptorGPU;
  44531. }
  44532. /**
  44533. * Destroys the GPU data for the given texture object.
  44534. *
  44535. * @param {Texture} texture - The texture.
  44536. */
  44537. destroyTexture( texture ) {
  44538. const backend = this.backend;
  44539. const textureData = backend.get( texture );
  44540. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  44541. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  44542. backend.delete( texture );
  44543. }
  44544. /**
  44545. * Destroys the GPU sampler for the given texture.
  44546. *
  44547. * @param {Texture} texture - The texture to destroy the sampler for.
  44548. */
  44549. destroySampler( texture ) {
  44550. const backend = this.backend;
  44551. const textureData = backend.get( texture );
  44552. delete textureData.sampler;
  44553. }
  44554. /**
  44555. * Generates mipmaps for the given texture.
  44556. *
  44557. * @param {Texture} texture - The texture.
  44558. */
  44559. generateMipmaps( texture ) {
  44560. const textureData = this.backend.get( texture );
  44561. if ( texture.isCubeTexture ) {
  44562. for ( let i = 0; i < 6; i ++ ) {
  44563. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  44564. }
  44565. } else {
  44566. const depth = texture.image.depth || 1;
  44567. for ( let i = 0; i < depth; i ++ ) {
  44568. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  44569. }
  44570. }
  44571. }
  44572. /**
  44573. * Returns the color buffer representing the color
  44574. * attachment of the default framebuffer.
  44575. *
  44576. * @return {GPUTexture} The color buffer.
  44577. */
  44578. getColorBuffer() {
  44579. if ( this.colorBuffer ) this.colorBuffer.destroy();
  44580. const backend = this.backend;
  44581. const { width, height } = backend.getDrawingBufferSize();
  44582. this.colorBuffer = backend.device.createTexture( {
  44583. label: 'colorBuffer',
  44584. size: {
  44585. width: width,
  44586. height: height,
  44587. depthOrArrayLayers: 1
  44588. },
  44589. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  44590. format: backend.utils.getPreferredCanvasFormat(),
  44591. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  44592. } );
  44593. return this.colorBuffer;
  44594. }
  44595. /**
  44596. * Returns the depth buffer representing the depth
  44597. * attachment of the default framebuffer.
  44598. *
  44599. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  44600. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  44601. * @return {GPUTexture} The depth buffer.
  44602. */
  44603. getDepthBuffer( depth = true, stencil = false ) {
  44604. const backend = this.backend;
  44605. const { width, height } = backend.getDrawingBufferSize();
  44606. const depthTexture = this.depthTexture;
  44607. const depthTextureGPU = backend.get( depthTexture ).texture;
  44608. let format, type;
  44609. if ( stencil ) {
  44610. format = DepthStencilFormat;
  44611. type = UnsignedInt248Type;
  44612. } else if ( depth ) {
  44613. format = DepthFormat;
  44614. type = UnsignedIntType;
  44615. }
  44616. if ( depthTextureGPU !== undefined ) {
  44617. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  44618. return depthTextureGPU;
  44619. }
  44620. this.destroyTexture( depthTexture );
  44621. }
  44622. depthTexture.name = 'depthBuffer';
  44623. depthTexture.format = format;
  44624. depthTexture.type = type;
  44625. depthTexture.image.width = width;
  44626. depthTexture.image.height = height;
  44627. this.createTexture( depthTexture, { width, height } );
  44628. return backend.get( depthTexture ).texture;
  44629. }
  44630. /**
  44631. * Uploads the updated texture data to the GPU.
  44632. *
  44633. * @param {Texture} texture - The texture.
  44634. * @param {Object} [options={}] - Optional configuration parameter.
  44635. */
  44636. updateTexture( texture, options ) {
  44637. const textureData = this.backend.get( texture );
  44638. const { textureDescriptorGPU } = textureData;
  44639. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  44640. return;
  44641. // transfer texture data
  44642. if ( texture.isDataTexture ) {
  44643. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  44644. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  44645. for ( let i = 0; i < options.image.depth; i ++ ) {
  44646. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  44647. }
  44648. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  44649. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  44650. } else if ( texture.isCubeTexture ) {
  44651. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  44652. } else if ( texture.isVideoTexture ) {
  44653. const video = texture.source.data;
  44654. textureData.externalTexture = video;
  44655. } else {
  44656. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  44657. }
  44658. //
  44659. textureData.version = texture.version;
  44660. if ( texture.onUpdate ) texture.onUpdate( texture );
  44661. }
  44662. /**
  44663. * Returns texture data as a typed array.
  44664. *
  44665. * @async
  44666. * @param {Texture} texture - The texture to copy.
  44667. * @param {number} x - The x coordinate of the copy origin.
  44668. * @param {number} y - The y coordinate of the copy origin.
  44669. * @param {number} width - The width of the copy.
  44670. * @param {number} height - The height of the copy.
  44671. * @param {number} faceIndex - The face index.
  44672. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44673. */
  44674. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44675. const device = this.backend.device;
  44676. const textureData = this.backend.get( texture );
  44677. const textureGPU = textureData.texture;
  44678. const format = textureData.textureDescriptorGPU.format;
  44679. const bytesPerTexel = this._getBytesPerTexel( format );
  44680. let bytesPerRow = width * bytesPerTexel;
  44681. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  44682. const readBuffer = device.createBuffer(
  44683. {
  44684. size: width * height * bytesPerTexel,
  44685. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44686. }
  44687. );
  44688. const encoder = device.createCommandEncoder();
  44689. encoder.copyTextureToBuffer(
  44690. {
  44691. texture: textureGPU,
  44692. origin: { x, y, z: faceIndex },
  44693. },
  44694. {
  44695. buffer: readBuffer,
  44696. bytesPerRow: bytesPerRow
  44697. },
  44698. {
  44699. width: width,
  44700. height: height
  44701. }
  44702. );
  44703. const typedArrayType = this._getTypedArrayType( format );
  44704. device.queue.submit( [ encoder.finish() ] );
  44705. await readBuffer.mapAsync( GPUMapMode.READ );
  44706. const buffer = readBuffer.getMappedRange();
  44707. return new typedArrayType( buffer );
  44708. }
  44709. /**
  44710. * Returns `true` if the given texture is an environment map.
  44711. *
  44712. * @private
  44713. * @param {Texture} texture - The texture.
  44714. * @return {boolean} Whether the given texture is an environment map or not.
  44715. */
  44716. _isEnvironmentTexture( texture ) {
  44717. const mapping = texture.mapping;
  44718. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44719. }
  44720. /**
  44721. * Returns the default GPU texture for the given format.
  44722. *
  44723. * @private
  44724. * @param {string} format - The GPU format.
  44725. * @return {GPUTexture} The GPU texture.
  44726. */
  44727. _getDefaultTextureGPU( format ) {
  44728. let defaultTexture = this.defaultTexture[ format ];
  44729. if ( defaultTexture === undefined ) {
  44730. const texture = new Texture();
  44731. texture.minFilter = NearestFilter;
  44732. texture.magFilter = NearestFilter;
  44733. this.createTexture( texture, { width: 1, height: 1, format } );
  44734. this.defaultTexture[ format ] = defaultTexture = texture;
  44735. }
  44736. return this.backend.get( defaultTexture ).texture;
  44737. }
  44738. /**
  44739. * Returns the default GPU cube texture for the given format.
  44740. *
  44741. * @private
  44742. * @param {string} format - The GPU format.
  44743. * @return {GPUTexture} The GPU texture.
  44744. */
  44745. _getDefaultCubeTextureGPU( format ) {
  44746. let defaultCubeTexture = this.defaultTexture[ format ];
  44747. if ( defaultCubeTexture === undefined ) {
  44748. const texture = new CubeTexture();
  44749. texture.minFilter = NearestFilter;
  44750. texture.magFilter = NearestFilter;
  44751. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  44752. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  44753. }
  44754. return this.backend.get( defaultCubeTexture ).texture;
  44755. }
  44756. /**
  44757. * Returns the default video frame used as default data in context of video textures.
  44758. *
  44759. * @private
  44760. * @return {VideoFrame} The video frame.
  44761. */
  44762. _getDefaultVideoFrame() {
  44763. let defaultVideoFrame = this.defaultVideoFrame;
  44764. if ( defaultVideoFrame === null ) {
  44765. const init = {
  44766. timestamp: 0,
  44767. codedWidth: 1,
  44768. codedHeight: 1,
  44769. format: 'RGBA',
  44770. };
  44771. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  44772. }
  44773. return defaultVideoFrame;
  44774. }
  44775. /**
  44776. * Uploads cube texture image data to the GPU memory.
  44777. *
  44778. * @private
  44779. * @param {Array} images - The cube image data.
  44780. * @param {GPUTexture} textureGPU - The GPU texture.
  44781. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44782. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44783. */
  44784. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  44785. for ( let i = 0; i < 6; i ++ ) {
  44786. const image = images[ i ];
  44787. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  44788. if ( image.isDataTexture ) {
  44789. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44790. } else {
  44791. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44792. }
  44793. }
  44794. }
  44795. /**
  44796. * Uploads texture image data to the GPU memory.
  44797. *
  44798. * @private
  44799. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  44800. * @param {GPUTexture} textureGPU - The GPU texture.
  44801. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44802. * @param {number} originDepth - The origin depth.
  44803. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44804. */
  44805. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  44806. const device = this.backend.device;
  44807. device.queue.copyExternalImageToTexture(
  44808. {
  44809. source: image,
  44810. flipY: flipY
  44811. }, {
  44812. texture: textureGPU,
  44813. mipLevel: 0,
  44814. origin: { x: 0, y: 0, z: originDepth }
  44815. }, {
  44816. width: image.width,
  44817. height: image.height,
  44818. depthOrArrayLayers: 1
  44819. }
  44820. );
  44821. }
  44822. /**
  44823. * Returns the pass utils singleton.
  44824. *
  44825. * @private
  44826. * @return {WebGPUTexturePassUtils} The utils instance.
  44827. */
  44828. _getPassUtils() {
  44829. let passUtils = this._passUtils;
  44830. if ( passUtils === null ) {
  44831. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  44832. }
  44833. return passUtils;
  44834. }
  44835. /**
  44836. * Generates mipmaps for the given GPU texture.
  44837. *
  44838. * @private
  44839. * @param {GPUTexture} textureGPU - The GPU texture object.
  44840. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44841. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44842. */
  44843. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  44844. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  44845. }
  44846. /**
  44847. * Flip the contents of the given GPU texture along its vertical axis.
  44848. *
  44849. * @private
  44850. * @param {GPUTexture} textureGPU - The GPU texture object.
  44851. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44852. * @param {number} [originDepth=0] - The origin depth.
  44853. */
  44854. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  44855. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  44856. }
  44857. /**
  44858. * Uploads texture buffer data to the GPU memory.
  44859. *
  44860. * @private
  44861. * @param {Object} image - An object defining the image buffer data.
  44862. * @param {GPUTexture} textureGPU - The GPU texture.
  44863. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44864. * @param {number} originDepth - The origin depth.
  44865. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44866. * @param {number} [depth=0] - TODO.
  44867. */
  44868. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  44869. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44870. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  44871. const device = this.backend.device;
  44872. const data = image.data;
  44873. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  44874. const bytesPerRow = image.width * bytesPerTexel;
  44875. device.queue.writeTexture(
  44876. {
  44877. texture: textureGPU,
  44878. mipLevel: 0,
  44879. origin: { x: 0, y: 0, z: originDepth }
  44880. },
  44881. data,
  44882. {
  44883. offset: image.width * image.height * bytesPerTexel * depth,
  44884. bytesPerRow
  44885. },
  44886. {
  44887. width: image.width,
  44888. height: image.height,
  44889. depthOrArrayLayers: 1
  44890. } );
  44891. if ( flipY === true ) {
  44892. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  44893. }
  44894. }
  44895. /**
  44896. * Uploads compressed texture data to the GPU memory.
  44897. *
  44898. * @private
  44899. * @param {Array<Object>} mipmaps - An array with mipmap data.
  44900. * @param {GPUTexture} textureGPU - The GPU texture.
  44901. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44902. */
  44903. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  44904. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44905. const device = this.backend.device;
  44906. const blockData = this._getBlockData( textureDescriptorGPU.format );
  44907. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  44908. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44909. const mipmap = mipmaps[ i ];
  44910. const width = mipmap.width;
  44911. const height = mipmap.height;
  44912. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  44913. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  44914. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  44915. for ( let j = 0; j < depth; j ++ ) {
  44916. device.queue.writeTexture(
  44917. {
  44918. texture: textureGPU,
  44919. mipLevel: i,
  44920. origin: { x: 0, y: 0, z: j }
  44921. },
  44922. mipmap.data,
  44923. {
  44924. offset: j * bytesPerImage,
  44925. bytesPerRow,
  44926. rowsPerImage: Math.ceil( height / blockData.height )
  44927. },
  44928. {
  44929. width: Math.ceil( width / blockData.width ) * blockData.width,
  44930. height: Math.ceil( height / blockData.height ) * blockData.height,
  44931. depthOrArrayLayers: 1
  44932. }
  44933. );
  44934. }
  44935. }
  44936. }
  44937. /**
  44938. * This method is only relevant for compressed texture formats. It returns a block
  44939. * data descriptor for the given GPU compressed texture format.
  44940. *
  44941. * @private
  44942. * @param {string} format - The GPU compressed texture format.
  44943. * @return {Object} The block data descriptor.
  44944. */
  44945. _getBlockData( format ) {
  44946. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  44947. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  44948. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  44949. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  44950. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  44951. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  44952. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  44953. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44954. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44955. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44956. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  44957. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  44958. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  44959. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  44960. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44961. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  44962. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  44963. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  44964. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  44965. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  44966. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  44967. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  44968. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  44969. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  44970. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  44971. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  44972. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  44973. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  44974. }
  44975. /**
  44976. * Converts the three.js uv wrapping constants to GPU address mode constants.
  44977. *
  44978. * @private
  44979. * @param {number} value - The three.js constant defining a uv wrapping mode.
  44980. * @return {string} The GPU address mode.
  44981. */
  44982. _convertAddressMode( value ) {
  44983. let addressMode = GPUAddressMode.ClampToEdge;
  44984. if ( value === RepeatWrapping ) {
  44985. addressMode = GPUAddressMode.Repeat;
  44986. } else if ( value === MirroredRepeatWrapping ) {
  44987. addressMode = GPUAddressMode.MirrorRepeat;
  44988. }
  44989. return addressMode;
  44990. }
  44991. /**
  44992. * Converts the three.js filter constants to GPU filter constants.
  44993. *
  44994. * @private
  44995. * @param {number} value - The three.js constant defining a filter mode.
  44996. * @return {string} The GPU filter mode.
  44997. */
  44998. _convertFilterMode( value ) {
  44999. let filterMode = GPUFilterMode.Linear;
  45000. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  45001. filterMode = GPUFilterMode.Nearest;
  45002. }
  45003. return filterMode;
  45004. }
  45005. /**
  45006. * Returns the bytes-per-texel value for the given GPU texture format.
  45007. *
  45008. * @private
  45009. * @param {string} format - The GPU texture format.
  45010. * @return {number} The bytes-per-texel.
  45011. */
  45012. _getBytesPerTexel( format ) {
  45013. // 8-bit formats
  45014. if ( format === GPUTextureFormat.R8Unorm ||
  45015. format === GPUTextureFormat.R8Snorm ||
  45016. format === GPUTextureFormat.R8Uint ||
  45017. format === GPUTextureFormat.R8Sint ) return 1;
  45018. // 16-bit formats
  45019. if ( format === GPUTextureFormat.R16Uint ||
  45020. format === GPUTextureFormat.R16Sint ||
  45021. format === GPUTextureFormat.R16Float ||
  45022. format === GPUTextureFormat.RG8Unorm ||
  45023. format === GPUTextureFormat.RG8Snorm ||
  45024. format === GPUTextureFormat.RG8Uint ||
  45025. format === GPUTextureFormat.RG8Sint ) return 2;
  45026. // 32-bit formats
  45027. if ( format === GPUTextureFormat.R32Uint ||
  45028. format === GPUTextureFormat.R32Sint ||
  45029. format === GPUTextureFormat.R32Float ||
  45030. format === GPUTextureFormat.RG16Uint ||
  45031. format === GPUTextureFormat.RG16Sint ||
  45032. format === GPUTextureFormat.RG16Float ||
  45033. format === GPUTextureFormat.RGBA8Unorm ||
  45034. format === GPUTextureFormat.RGBA8UnormSRGB ||
  45035. format === GPUTextureFormat.RGBA8Snorm ||
  45036. format === GPUTextureFormat.RGBA8Uint ||
  45037. format === GPUTextureFormat.RGBA8Sint ||
  45038. format === GPUTextureFormat.BGRA8Unorm ||
  45039. format === GPUTextureFormat.BGRA8UnormSRGB ||
  45040. // Packed 32-bit formats
  45041. format === GPUTextureFormat.RGB9E5UFloat ||
  45042. format === GPUTextureFormat.RGB10A2Unorm ||
  45043. format === GPUTextureFormat.RG11B10UFloat ||
  45044. format === GPUTextureFormat.Depth32Float ||
  45045. format === GPUTextureFormat.Depth24Plus ||
  45046. format === GPUTextureFormat.Depth24PlusStencil8 ||
  45047. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  45048. // 64-bit formats
  45049. if ( format === GPUTextureFormat.RG32Uint ||
  45050. format === GPUTextureFormat.RG32Sint ||
  45051. format === GPUTextureFormat.RG32Float ||
  45052. format === GPUTextureFormat.RGBA16Uint ||
  45053. format === GPUTextureFormat.RGBA16Sint ||
  45054. format === GPUTextureFormat.RGBA16Float ) return 8;
  45055. // 128-bit formats
  45056. if ( format === GPUTextureFormat.RGBA32Uint ||
  45057. format === GPUTextureFormat.RGBA32Sint ||
  45058. format === GPUTextureFormat.RGBA32Float ) return 16;
  45059. }
  45060. /**
  45061. * Returns the corresponding typed array type for the given GPU texture format.
  45062. *
  45063. * @private
  45064. * @param {string} format - The GPU texture format.
  45065. * @return {TypedArray.constructor} The typed array type.
  45066. */
  45067. _getTypedArrayType( format ) {
  45068. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  45069. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  45070. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  45071. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  45072. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  45073. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  45074. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  45075. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  45076. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  45077. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  45078. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  45079. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  45080. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  45081. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  45082. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  45083. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  45084. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  45085. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  45086. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  45087. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  45088. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  45089. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  45090. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  45091. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  45092. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  45093. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  45094. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  45095. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  45096. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  45097. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  45098. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  45099. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  45100. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  45101. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  45102. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  45103. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  45104. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  45105. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  45106. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  45107. }
  45108. /**
  45109. * Returns the GPU dimensions for the given texture.
  45110. *
  45111. * @private
  45112. * @param {Texture} texture - The texture.
  45113. * @return {string} The GPU dimension.
  45114. */
  45115. _getDimension( texture ) {
  45116. let dimension;
  45117. if ( texture.isData3DTexture ) {
  45118. dimension = GPUTextureDimension.ThreeD;
  45119. } else {
  45120. dimension = GPUTextureDimension.TwoD;
  45121. }
  45122. return dimension;
  45123. }
  45124. }
  45125. /**
  45126. * Returns the GPU format for the given texture.
  45127. *
  45128. * @param {Texture} texture - The texture.
  45129. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  45130. * It is not necessary to apply the device for most formats.
  45131. * @return {string} The GPU format.
  45132. */
  45133. function getFormat( texture, device = null ) {
  45134. const format = texture.format;
  45135. const type = texture.type;
  45136. const colorSpace = texture.colorSpace;
  45137. let formatGPU;
  45138. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  45139. switch ( format ) {
  45140. case RGBA_S3TC_DXT1_Format:
  45141. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  45142. break;
  45143. case RGBA_S3TC_DXT3_Format:
  45144. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  45145. break;
  45146. case RGBA_S3TC_DXT5_Format:
  45147. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  45148. break;
  45149. case RGB_ETC2_Format:
  45150. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  45151. break;
  45152. case RGBA_ETC2_EAC_Format:
  45153. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  45154. break;
  45155. case RGBA_ASTC_4x4_Format:
  45156. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  45157. break;
  45158. case RGBA_ASTC_5x4_Format:
  45159. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  45160. break;
  45161. case RGBA_ASTC_5x5_Format:
  45162. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  45163. break;
  45164. case RGBA_ASTC_6x5_Format:
  45165. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  45166. break;
  45167. case RGBA_ASTC_6x6_Format:
  45168. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  45169. break;
  45170. case RGBA_ASTC_8x5_Format:
  45171. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  45172. break;
  45173. case RGBA_ASTC_8x6_Format:
  45174. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  45175. break;
  45176. case RGBA_ASTC_8x8_Format:
  45177. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  45178. break;
  45179. case RGBA_ASTC_10x5_Format:
  45180. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  45181. break;
  45182. case RGBA_ASTC_10x6_Format:
  45183. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  45184. break;
  45185. case RGBA_ASTC_10x8_Format:
  45186. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  45187. break;
  45188. case RGBA_ASTC_10x10_Format:
  45189. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  45190. break;
  45191. case RGBA_ASTC_12x10_Format:
  45192. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  45193. break;
  45194. case RGBA_ASTC_12x12_Format:
  45195. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  45196. break;
  45197. case RGBAFormat:
  45198. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  45199. break;
  45200. default:
  45201. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  45202. }
  45203. } else {
  45204. switch ( format ) {
  45205. case RGBAFormat:
  45206. switch ( type ) {
  45207. case ByteType:
  45208. formatGPU = GPUTextureFormat.RGBA8Snorm;
  45209. break;
  45210. case ShortType:
  45211. formatGPU = GPUTextureFormat.RGBA16Sint;
  45212. break;
  45213. case UnsignedShortType:
  45214. formatGPU = GPUTextureFormat.RGBA16Uint;
  45215. break;
  45216. case UnsignedIntType:
  45217. formatGPU = GPUTextureFormat.RGBA32Uint;
  45218. break;
  45219. case IntType:
  45220. formatGPU = GPUTextureFormat.RGBA32Sint;
  45221. break;
  45222. case UnsignedByteType:
  45223. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  45224. break;
  45225. case HalfFloatType:
  45226. formatGPU = GPUTextureFormat.RGBA16Float;
  45227. break;
  45228. case FloatType:
  45229. formatGPU = GPUTextureFormat.RGBA32Float;
  45230. break;
  45231. default:
  45232. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  45233. }
  45234. break;
  45235. case RGBFormat:
  45236. switch ( type ) {
  45237. case UnsignedInt5999Type:
  45238. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  45239. break;
  45240. default:
  45241. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  45242. }
  45243. break;
  45244. case RedFormat:
  45245. switch ( type ) {
  45246. case ByteType:
  45247. formatGPU = GPUTextureFormat.R8Snorm;
  45248. break;
  45249. case ShortType:
  45250. formatGPU = GPUTextureFormat.R16Sint;
  45251. break;
  45252. case UnsignedShortType:
  45253. formatGPU = GPUTextureFormat.R16Uint;
  45254. break;
  45255. case UnsignedIntType:
  45256. formatGPU = GPUTextureFormat.R32Uint;
  45257. break;
  45258. case IntType:
  45259. formatGPU = GPUTextureFormat.R32Sint;
  45260. break;
  45261. case UnsignedByteType:
  45262. formatGPU = GPUTextureFormat.R8Unorm;
  45263. break;
  45264. case HalfFloatType:
  45265. formatGPU = GPUTextureFormat.R16Float;
  45266. break;
  45267. case FloatType:
  45268. formatGPU = GPUTextureFormat.R32Float;
  45269. break;
  45270. default:
  45271. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  45272. }
  45273. break;
  45274. case RGFormat:
  45275. switch ( type ) {
  45276. case ByteType:
  45277. formatGPU = GPUTextureFormat.RG8Snorm;
  45278. break;
  45279. case ShortType:
  45280. formatGPU = GPUTextureFormat.RG16Sint;
  45281. break;
  45282. case UnsignedShortType:
  45283. formatGPU = GPUTextureFormat.RG16Uint;
  45284. break;
  45285. case UnsignedIntType:
  45286. formatGPU = GPUTextureFormat.RG32Uint;
  45287. break;
  45288. case IntType:
  45289. formatGPU = GPUTextureFormat.RG32Sint;
  45290. break;
  45291. case UnsignedByteType:
  45292. formatGPU = GPUTextureFormat.RG8Unorm;
  45293. break;
  45294. case HalfFloatType:
  45295. formatGPU = GPUTextureFormat.RG16Float;
  45296. break;
  45297. case FloatType:
  45298. formatGPU = GPUTextureFormat.RG32Float;
  45299. break;
  45300. default:
  45301. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  45302. }
  45303. break;
  45304. case DepthFormat:
  45305. switch ( type ) {
  45306. case UnsignedShortType:
  45307. formatGPU = GPUTextureFormat.Depth16Unorm;
  45308. break;
  45309. case UnsignedIntType:
  45310. formatGPU = GPUTextureFormat.Depth24Plus;
  45311. break;
  45312. case FloatType:
  45313. formatGPU = GPUTextureFormat.Depth32Float;
  45314. break;
  45315. default:
  45316. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  45317. }
  45318. break;
  45319. case DepthStencilFormat:
  45320. switch ( type ) {
  45321. case UnsignedInt248Type:
  45322. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  45323. break;
  45324. case FloatType:
  45325. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  45326. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  45327. }
  45328. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  45329. break;
  45330. default:
  45331. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  45332. }
  45333. break;
  45334. case RedIntegerFormat:
  45335. switch ( type ) {
  45336. case IntType:
  45337. formatGPU = GPUTextureFormat.R32Sint;
  45338. break;
  45339. case UnsignedIntType:
  45340. formatGPU = GPUTextureFormat.R32Uint;
  45341. break;
  45342. default:
  45343. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  45344. }
  45345. break;
  45346. case RGIntegerFormat:
  45347. switch ( type ) {
  45348. case IntType:
  45349. formatGPU = GPUTextureFormat.RG32Sint;
  45350. break;
  45351. case UnsignedIntType:
  45352. formatGPU = GPUTextureFormat.RG32Uint;
  45353. break;
  45354. default:
  45355. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  45356. }
  45357. break;
  45358. case RGBAIntegerFormat:
  45359. switch ( type ) {
  45360. case IntType:
  45361. formatGPU = GPUTextureFormat.RGBA32Sint;
  45362. break;
  45363. case UnsignedIntType:
  45364. formatGPU = GPUTextureFormat.RGBA32Uint;
  45365. break;
  45366. default:
  45367. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  45368. }
  45369. break;
  45370. default:
  45371. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  45372. }
  45373. }
  45374. return formatGPU;
  45375. }
  45376. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  45377. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  45378. const wgslTypeLib$1 = {
  45379. 'f32': 'float',
  45380. 'i32': 'int',
  45381. 'u32': 'uint',
  45382. 'bool': 'bool',
  45383. 'vec2<f32>': 'vec2',
  45384. 'vec2<i32>': 'ivec2',
  45385. 'vec2<u32>': 'uvec2',
  45386. 'vec2<bool>': 'bvec2',
  45387. 'vec2f': 'vec2',
  45388. 'vec2i': 'ivec2',
  45389. 'vec2u': 'uvec2',
  45390. 'vec2b': 'bvec2',
  45391. 'vec3<f32>': 'vec3',
  45392. 'vec3<i32>': 'ivec3',
  45393. 'vec3<u32>': 'uvec3',
  45394. 'vec3<bool>': 'bvec3',
  45395. 'vec3f': 'vec3',
  45396. 'vec3i': 'ivec3',
  45397. 'vec3u': 'uvec3',
  45398. 'vec3b': 'bvec3',
  45399. 'vec4<f32>': 'vec4',
  45400. 'vec4<i32>': 'ivec4',
  45401. 'vec4<u32>': 'uvec4',
  45402. 'vec4<bool>': 'bvec4',
  45403. 'vec4f': 'vec4',
  45404. 'vec4i': 'ivec4',
  45405. 'vec4u': 'uvec4',
  45406. 'vec4b': 'bvec4',
  45407. 'mat2x2<f32>': 'mat2',
  45408. 'mat2x2f': 'mat2',
  45409. 'mat3x3<f32>': 'mat3',
  45410. 'mat3x3f': 'mat3',
  45411. 'mat4x4<f32>': 'mat4',
  45412. 'mat4x4f': 'mat4',
  45413. 'sampler': 'sampler',
  45414. 'texture_1d': 'texture',
  45415. 'texture_2d': 'texture',
  45416. 'texture_2d_array': 'texture',
  45417. 'texture_multisampled_2d': 'cubeTexture',
  45418. 'texture_depth_2d': 'depthTexture',
  45419. 'texture_depth_multisampled_2d': 'depthTexture',
  45420. 'texture_3d': 'texture3D',
  45421. 'texture_cube': 'cubeTexture',
  45422. 'texture_cube_array': 'cubeTexture',
  45423. 'texture_storage_1d': 'storageTexture',
  45424. 'texture_storage_2d': 'storageTexture',
  45425. 'texture_storage_2d_array': 'storageTexture',
  45426. 'texture_storage_3d': 'storageTexture'
  45427. };
  45428. const parse = ( source ) => {
  45429. source = source.trim();
  45430. const declaration = source.match( declarationRegexp );
  45431. if ( declaration !== null && declaration.length === 4 ) {
  45432. const inputsCode = declaration[ 2 ];
  45433. const propsMatches = [];
  45434. let match = null;
  45435. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  45436. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  45437. }
  45438. // Process matches to correctly pair names and types
  45439. const inputs = [];
  45440. for ( let i = 0; i < propsMatches.length; i ++ ) {
  45441. const { name, type } = propsMatches[ i ];
  45442. let resolvedType = type;
  45443. if ( resolvedType.startsWith( 'ptr' ) ) {
  45444. resolvedType = 'pointer';
  45445. } else {
  45446. if ( resolvedType.startsWith( 'texture' ) ) {
  45447. resolvedType = type.split( '<' )[ 0 ];
  45448. }
  45449. resolvedType = wgslTypeLib$1[ resolvedType ];
  45450. }
  45451. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  45452. }
  45453. const blockCode = source.substring( declaration[ 0 ].length );
  45454. const outputType = declaration[ 3 ] || 'void';
  45455. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  45456. const type = wgslTypeLib$1[ outputType ] || outputType;
  45457. return {
  45458. type,
  45459. inputs,
  45460. name,
  45461. inputsCode,
  45462. blockCode,
  45463. outputType
  45464. };
  45465. } else {
  45466. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  45467. }
  45468. };
  45469. /**
  45470. * This class represents a WSL node function.
  45471. *
  45472. * @augments NodeFunction
  45473. */
  45474. class WGSLNodeFunction extends NodeFunction {
  45475. /**
  45476. * Constructs a new WGSL node function.
  45477. *
  45478. * @param {string} source - The WGSL source.
  45479. */
  45480. constructor( source ) {
  45481. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  45482. super( type, inputs, name );
  45483. this.inputsCode = inputsCode;
  45484. this.blockCode = blockCode;
  45485. this.outputType = outputType;
  45486. }
  45487. /**
  45488. * This method returns the WGSL code of the node function.
  45489. *
  45490. * @param {string} [name=this.name] - The function's name.
  45491. * @return {string} The shader code.
  45492. */
  45493. getCode( name = this.name ) {
  45494. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  45495. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  45496. }
  45497. }
  45498. /**
  45499. * A WGSL node parser.
  45500. *
  45501. * @augments NodeParser
  45502. */
  45503. class WGSLNodeParser extends NodeParser {
  45504. /**
  45505. * The method parses the given WGSL code an returns a node function.
  45506. *
  45507. * @param {string} source - The WGSL code.
  45508. * @return {WGSLNodeFunction} A node function.
  45509. */
  45510. parseFunction( source ) {
  45511. return new WGSLNodeFunction( source );
  45512. }
  45513. }
  45514. // GPUShaderStage is not defined in browsers not supporting WebGPU
  45515. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  45516. const accessNames = {
  45517. [ NodeAccess.READ_ONLY ]: 'read',
  45518. [ NodeAccess.WRITE_ONLY ]: 'write',
  45519. [ NodeAccess.READ_WRITE ]: 'read_write'
  45520. };
  45521. const wrapNames = {
  45522. [ RepeatWrapping ]: 'repeat',
  45523. [ ClampToEdgeWrapping ]: 'clamp',
  45524. [ MirroredRepeatWrapping ]: 'mirror'
  45525. };
  45526. const gpuShaderStageLib = {
  45527. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  45528. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  45529. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  45530. };
  45531. const supports = {
  45532. instance: true,
  45533. swizzleAssign: false,
  45534. storageBuffer: true
  45535. };
  45536. const wgslFnOpLib = {
  45537. '^^': 'tsl_xor'
  45538. };
  45539. const wgslTypeLib = {
  45540. float: 'f32',
  45541. int: 'i32',
  45542. uint: 'u32',
  45543. bool: 'bool',
  45544. color: 'vec3<f32>',
  45545. vec2: 'vec2<f32>',
  45546. ivec2: 'vec2<i32>',
  45547. uvec2: 'vec2<u32>',
  45548. bvec2: 'vec2<bool>',
  45549. vec3: 'vec3<f32>',
  45550. ivec3: 'vec3<i32>',
  45551. uvec3: 'vec3<u32>',
  45552. bvec3: 'vec3<bool>',
  45553. vec4: 'vec4<f32>',
  45554. ivec4: 'vec4<i32>',
  45555. uvec4: 'vec4<u32>',
  45556. bvec4: 'vec4<bool>',
  45557. mat2: 'mat2x2<f32>',
  45558. mat3: 'mat3x3<f32>',
  45559. mat4: 'mat4x4<f32>'
  45560. };
  45561. const wgslCodeCache = {};
  45562. const wgslPolyfill = {
  45563. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  45564. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  45565. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  45566. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  45567. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  45568. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  45569. 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 ); }' ),
  45570. 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 ); }' ),
  45571. 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 ); }' ),
  45572. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  45573. 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 ); }' ),
  45574. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  45575. biquadraticTexture: new CodeNode( /* wgsl */`
  45576. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  45577. let res = vec2f( iRes );
  45578. let uvScaled = coord * res;
  45579. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  45580. // https://www.shadertoy.com/view/WtyXRy
  45581. let uv = uvWrapping - 0.5;
  45582. let iuv = floor( uv );
  45583. let f = fract( uv );
  45584. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  45585. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  45586. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  45587. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  45588. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  45589. }
  45590. ` )
  45591. };
  45592. const wgslMethods = {
  45593. dFdx: 'dpdx',
  45594. dFdy: '- dpdy',
  45595. mod_float: 'tsl_mod_float',
  45596. mod_vec2: 'tsl_mod_vec2',
  45597. mod_vec3: 'tsl_mod_vec3',
  45598. mod_vec4: 'tsl_mod_vec4',
  45599. equals_bool: 'tsl_equals_bool',
  45600. equals_bvec2: 'tsl_equals_bvec2',
  45601. equals_bvec3: 'tsl_equals_bvec3',
  45602. equals_bvec4: 'tsl_equals_bvec4',
  45603. inversesqrt: 'inverseSqrt',
  45604. bitcast: 'bitcast<f32>'
  45605. };
  45606. // WebGPU issue: does not support pow() with negative base on Windows
  45607. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  45608. 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 ); }' );
  45609. 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 ] );
  45610. 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 ] );
  45611. 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 ] );
  45612. wgslMethods.pow_float = 'tsl_pow_float';
  45613. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  45614. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  45615. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  45616. }
  45617. //
  45618. let diagnostics = '';
  45619. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  45620. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  45621. }
  45622. /**
  45623. * A node builder targeting WGSL.
  45624. *
  45625. * This module generates WGSL shader code from node materials and also
  45626. * generates the respective bindings and vertex buffer definitions. These
  45627. * data are later used by the renderer to create render and compute pipelines
  45628. * for render objects.
  45629. *
  45630. * @augments NodeBuilder
  45631. */
  45632. class WGSLNodeBuilder extends NodeBuilder {
  45633. /**
  45634. * Constructs a new WGSL node builder renderer.
  45635. *
  45636. * @param {Object3D} object - The 3D object.
  45637. * @param {Renderer} renderer - The renderer.
  45638. */
  45639. constructor( object, renderer ) {
  45640. super( object, renderer, new WGSLNodeParser() );
  45641. /**
  45642. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  45643. * another dictionary which manages UBOs per group ('render','frame','object').
  45644. *
  45645. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  45646. */
  45647. this.uniformGroups = {};
  45648. /**
  45649. * A dictionary that holds for each shader stage a Map of builtins.
  45650. *
  45651. * @type {Object<string,Map<string,Object>>}
  45652. */
  45653. this.builtins = {};
  45654. /**
  45655. * A dictionary that holds for each shader stage a Set of directives.
  45656. *
  45657. * @type {Object<string,Set<string>>}
  45658. */
  45659. this.directives = {};
  45660. /**
  45661. * A map for managing scope arrays. Only relevant for when using
  45662. * {@link WorkgroupInfoNode} in context of compute shaders.
  45663. *
  45664. * @type {Map<string,Object>}
  45665. */
  45666. this.scopedArrays = new Map();
  45667. }
  45668. /**
  45669. * Checks if the given texture requires a manual conversion to the working color space.
  45670. *
  45671. * @param {Texture} texture - The texture to check.
  45672. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  45673. */
  45674. needsToWorkingColorSpace( texture ) {
  45675. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  45676. }
  45677. /**
  45678. * Generates the WGSL snippet for sampled textures.
  45679. *
  45680. * @private
  45681. * @param {Texture} texture - The texture.
  45682. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45683. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45684. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45685. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45686. * @return {string} The WGSL snippet.
  45687. */
  45688. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45689. if ( shaderStage === 'fragment' ) {
  45690. if ( depthSnippet ) {
  45691. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  45692. } else {
  45693. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  45694. }
  45695. } else if ( this.isFilteredTexture( texture ) ) {
  45696. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  45697. } else {
  45698. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  45699. }
  45700. }
  45701. /**
  45702. * Generates the WGSL snippet when sampling video textures.
  45703. *
  45704. * @private
  45705. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45706. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45707. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45708. * @return {string} The WGSL snippet.
  45709. */
  45710. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  45711. if ( shaderStage === 'fragment' ) {
  45712. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  45713. } else {
  45714. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  45715. }
  45716. }
  45717. /**
  45718. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45719. *
  45720. * @private
  45721. * @param {Texture} texture - The texture.
  45722. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45723. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45724. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45725. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45726. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45727. * @return {string} The WGSL snippet.
  45728. */
  45729. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45730. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  45731. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  45732. } else if ( this.isFilteredTexture( texture ) ) {
  45733. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  45734. } else {
  45735. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  45736. }
  45737. }
  45738. /**
  45739. * Generates a wrap function used in context of textures.
  45740. *
  45741. * @param {Texture} texture - The texture to generate the function for.
  45742. * @return {string} The name of the generated function.
  45743. */
  45744. generateWrapFunction( texture ) {
  45745. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  45746. let nodeCode = wgslCodeCache[ functionName ];
  45747. if ( nodeCode === undefined ) {
  45748. const includes = [];
  45749. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  45750. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  45751. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  45752. const addWrapSnippet = ( wrap, axis ) => {
  45753. if ( wrap === RepeatWrapping ) {
  45754. includes.push( wgslPolyfill.repeatWrapping_float );
  45755. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  45756. } else if ( wrap === ClampToEdgeWrapping ) {
  45757. includes.push( wgslPolyfill.clampWrapping_float );
  45758. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  45759. } else if ( wrap === MirroredRepeatWrapping ) {
  45760. includes.push( wgslPolyfill.mirrorWrapping_float );
  45761. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  45762. } else {
  45763. code += `\t\tcoord.${ axis }`;
  45764. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  45765. }
  45766. };
  45767. addWrapSnippet( texture.wrapS, 'x' );
  45768. code += ',\n';
  45769. addWrapSnippet( texture.wrapT, 'y' );
  45770. if ( texture.isData3DTexture ) {
  45771. code += ',\n';
  45772. addWrapSnippet( texture.wrapR, 'z' );
  45773. }
  45774. code += '\n\t);\n\n}\n';
  45775. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  45776. }
  45777. nodeCode.build( this );
  45778. return functionName;
  45779. }
  45780. /**
  45781. * Generates the array declaration string.
  45782. *
  45783. * @param {string} type - The type.
  45784. * @param {?number} [count] - The count.
  45785. * @return {string} The generated value as a shader string.
  45786. */
  45787. generateArrayDeclaration( type, count ) {
  45788. return `array< ${ this.getType( type ) }, ${ count } >`;
  45789. }
  45790. /**
  45791. * Generates a WGSL variable that holds the texture dimension of the given texture.
  45792. * It also returns information about the the number of layers (elements) of an arrayed
  45793. * texture as well as the cube face count of cube textures.
  45794. *
  45795. * @param {Texture} texture - The texture to generate the function for.
  45796. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45797. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45798. * @return {string} The name of the dimension variable.
  45799. */
  45800. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  45801. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  45802. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  45803. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  45804. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  45805. let textureDimensionsParams;
  45806. let dimensionType;
  45807. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45808. const isMultisampled = primarySamples > 1;
  45809. if ( texture.isData3DTexture ) {
  45810. dimensionType = 'vec3<u32>';
  45811. } else {
  45812. // Regular 2D textures, depth textures, etc.
  45813. dimensionType = 'vec2<u32>';
  45814. }
  45815. // Build parameters string based on texture type and multisampling
  45816. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  45817. textureDimensionsParams = textureProperty;
  45818. } else {
  45819. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  45820. }
  45821. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  45822. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  45823. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  45824. textureData.arrayLayerCount = new VarNode(
  45825. new ExpressionNode(
  45826. `textureNumLayers(${textureProperty})`,
  45827. 'u32'
  45828. )
  45829. );
  45830. }
  45831. // For cube textures, we know it's always 6 faces
  45832. if ( texture.isTextureCube ) {
  45833. textureData.cubeFaceCount = new VarNode(
  45834. new ExpressionNode( '6u', 'u32' )
  45835. );
  45836. }
  45837. }
  45838. return textureDimensionNode.build( this );
  45839. }
  45840. /**
  45841. * Generates the WGSL snippet for a manual filtered texture.
  45842. *
  45843. * @param {Texture} texture - The texture.
  45844. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45845. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45846. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45847. * @return {string} The WGSL snippet.
  45848. */
  45849. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  45850. this._include( 'biquadraticTexture' );
  45851. const wrapFunction = this.generateWrapFunction( texture );
  45852. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45853. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  45854. }
  45855. /**
  45856. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  45857. * Since it's a lookup, no sampling or filtering is applied.
  45858. *
  45859. * @param {Texture} texture - The texture.
  45860. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45861. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45862. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45863. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45864. * @return {string} The WGSL snippet.
  45865. */
  45866. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  45867. const wrapFunction = this.generateWrapFunction( texture );
  45868. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45869. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  45870. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  45871. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  45872. }
  45873. /**
  45874. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  45875. *
  45876. * @param {Texture} texture - The texture.
  45877. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45878. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45879. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45880. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45881. * @return {string} The WGSL snippet.
  45882. */
  45883. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  45884. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  45885. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  45886. } else if ( depthSnippet ) {
  45887. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  45888. } else {
  45889. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  45890. }
  45891. }
  45892. /**
  45893. * Generates the WGSL snippet that writes a single texel to a texture.
  45894. *
  45895. * @param {Texture} texture - The texture.
  45896. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45897. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45898. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  45899. * @return {string} The WGSL snippet.
  45900. */
  45901. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  45902. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  45903. }
  45904. /**
  45905. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  45906. *
  45907. * @param {Texture} texture - The texture.
  45908. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  45909. */
  45910. isSampleCompare( texture ) {
  45911. return texture.isDepthTexture === true && texture.compareFunction !== null;
  45912. }
  45913. /**
  45914. * Returns `true` if the given texture is unfilterable.
  45915. *
  45916. * @param {Texture} texture - The texture.
  45917. * @return {boolean} Whether the given texture is unfilterable or not.
  45918. */
  45919. isUnfilterable( texture ) {
  45920. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  45921. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  45922. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  45923. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  45924. }
  45925. /**
  45926. * Generates the WGSL snippet for sampling/loading the given texture.
  45927. *
  45928. * @param {Texture} texture - The texture.
  45929. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45930. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45931. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45932. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45933. * @return {string} The WGSL snippet.
  45934. */
  45935. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45936. let snippet = null;
  45937. if ( texture.isVideoTexture === true ) {
  45938. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45939. } else if ( this.isUnfilterable( texture ) ) {
  45940. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  45941. } else {
  45942. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  45943. }
  45944. return snippet;
  45945. }
  45946. /**
  45947. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  45948. *
  45949. * @param {Texture} texture - The texture.
  45950. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45951. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45952. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  45953. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45954. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45955. * @return {string} The WGSL snippet.
  45956. */
  45957. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45958. if ( shaderStage === 'fragment' ) {
  45959. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  45960. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  45961. } else {
  45962. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  45963. }
  45964. }
  45965. /**
  45966. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  45967. * against a reference value.
  45968. *
  45969. * @param {Texture} texture - The texture.
  45970. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45971. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45972. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  45973. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45974. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45975. * @return {string} The WGSL snippet.
  45976. */
  45977. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45978. if ( shaderStage === 'fragment' ) {
  45979. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  45980. } else {
  45981. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  45982. }
  45983. }
  45984. /**
  45985. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45986. *
  45987. * @param {Texture} texture - The texture.
  45988. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45989. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45990. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45991. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45992. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45993. * @return {string} The WGSL snippet.
  45994. */
  45995. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45996. let snippet = null;
  45997. if ( texture.isVideoTexture === true ) {
  45998. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45999. } else {
  46000. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  46001. }
  46002. return snippet;
  46003. }
  46004. /**
  46005. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  46006. *
  46007. * @param {Texture} texture - The texture.
  46008. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46009. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46010. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  46011. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46012. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46013. * @return {string} The WGSL snippet.
  46014. */
  46015. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46016. if ( shaderStage === 'fragment' ) {
  46017. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  46018. } else {
  46019. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  46020. }
  46021. }
  46022. /**
  46023. * Returns a WGSL snippet that represents the property name of the given node.
  46024. *
  46025. * @param {Node} node - The node.
  46026. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46027. * @return {string} The property name.
  46028. */
  46029. getPropertyName( node, shaderStage = this.shaderStage ) {
  46030. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  46031. if ( shaderStage === 'vertex' ) {
  46032. return `varyings.${ node.name }`;
  46033. }
  46034. } else if ( node.isNodeUniform === true ) {
  46035. const name = node.name;
  46036. const type = node.type;
  46037. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  46038. return name;
  46039. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  46040. if ( this.isCustomStruct( node ) ) {
  46041. return name;
  46042. }
  46043. return name + '.value';
  46044. } else {
  46045. return node.groupNode.name + '.' + name;
  46046. }
  46047. }
  46048. return super.getPropertyName( node );
  46049. }
  46050. /**
  46051. * Returns the output struct name.
  46052. *
  46053. * @return {string} The name of the output struct.
  46054. */
  46055. getOutputStructName() {
  46056. return 'output';
  46057. }
  46058. /**
  46059. * Returns the native shader operator name for a given generic name.
  46060. *
  46061. * @param {string} op - The operator name to resolve.
  46062. * @return {?string} The resolved operator name.
  46063. */
  46064. getFunctionOperator( op ) {
  46065. const fnOp = wgslFnOpLib[ op ];
  46066. if ( fnOp !== undefined ) {
  46067. this._include( fnOp );
  46068. return fnOp;
  46069. }
  46070. return null;
  46071. }
  46072. /**
  46073. * Returns the node access for the given node and shader stage.
  46074. *
  46075. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  46076. * @param {string} shaderStage - The shader stage.
  46077. * @return {string} The node access.
  46078. */
  46079. getNodeAccess( node, shaderStage ) {
  46080. if ( shaderStage !== 'compute' )
  46081. return NodeAccess.READ_ONLY;
  46082. return node.access;
  46083. }
  46084. /**
  46085. * Returns A WGSL snippet representing the storage access.
  46086. *
  46087. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  46088. * @param {string} shaderStage - The shader stage.
  46089. * @return {string} The WGSL snippet representing the storage access.
  46090. */
  46091. getStorageAccess( node, shaderStage ) {
  46092. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  46093. }
  46094. /**
  46095. * This method is one of the more important ones since it's responsible
  46096. * for generating a matching binding instance for the given uniform node.
  46097. *
  46098. * These bindings are later used in the renderer to create bind groups
  46099. * and layouts.
  46100. *
  46101. * @param {UniformNode} node - The uniform node.
  46102. * @param {string} type - The node data type.
  46103. * @param {string} shaderStage - The shader stage.
  46104. * @param {?string} [name=null] - An optional uniform name.
  46105. * @return {NodeUniform} The node uniform object.
  46106. */
  46107. getUniformFromNode( node, type, shaderStage, name = null ) {
  46108. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  46109. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  46110. if ( nodeData.uniformGPU === undefined ) {
  46111. let uniformGPU;
  46112. const group = node.groupNode;
  46113. const groupName = group.name;
  46114. const bindings = this.getBindGroupArray( groupName, shaderStage );
  46115. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  46116. let texture = null;
  46117. const access = this.getNodeAccess( node, shaderStage );
  46118. if ( type === 'texture' || type === 'storageTexture' ) {
  46119. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  46120. } else if ( type === 'cubeTexture' ) {
  46121. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  46122. } else if ( type === 'texture3D' ) {
  46123. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  46124. }
  46125. texture.store = node.isStorageTextureNode === true;
  46126. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46127. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  46128. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  46129. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46130. bindings.push( sampler, texture );
  46131. uniformGPU = [ sampler, texture ];
  46132. } else {
  46133. bindings.push( texture );
  46134. uniformGPU = [ texture ];
  46135. }
  46136. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  46137. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  46138. const buffer = new bufferClass( node, group );
  46139. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46140. bindings.push( buffer );
  46141. uniformGPU = buffer;
  46142. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  46143. } else {
  46144. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  46145. let uniformsGroup = uniformsStage[ groupName ];
  46146. if ( uniformsGroup === undefined ) {
  46147. uniformsGroup = new NodeUniformsGroup( groupName, group );
  46148. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46149. uniformsStage[ groupName ] = uniformsGroup;
  46150. bindings.push( uniformsGroup );
  46151. }
  46152. uniformGPU = this.getNodeUniform( uniformNode, type );
  46153. uniformsGroup.addUniform( uniformGPU );
  46154. }
  46155. nodeData.uniformGPU = uniformGPU;
  46156. }
  46157. return uniformNode;
  46158. }
  46159. /**
  46160. * This method should be used whenever builtins are required in nodes.
  46161. * The internal builtins data structure will make sure builtins are
  46162. * defined in the WGSL source.
  46163. *
  46164. * @param {string} name - The builtin name.
  46165. * @param {string} property - The property name.
  46166. * @param {string} type - The node data type.
  46167. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46168. * @return {string} The property name.
  46169. */
  46170. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  46171. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  46172. if ( map.has( name ) === false ) {
  46173. map.set( name, {
  46174. name,
  46175. property,
  46176. type
  46177. } );
  46178. }
  46179. return property;
  46180. }
  46181. /**
  46182. * Returns `true` if the given builtin is defined in the given shader stage.
  46183. *
  46184. * @param {string} name - The builtin name.
  46185. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46186. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  46187. */
  46188. hasBuiltin( name, shaderStage = this.shaderStage ) {
  46189. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  46190. }
  46191. /**
  46192. * Returns the vertex index builtin.
  46193. *
  46194. * @return {string} The vertex index.
  46195. */
  46196. getVertexIndex() {
  46197. if ( this.shaderStage === 'vertex' ) {
  46198. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  46199. }
  46200. return 'vertexIndex';
  46201. }
  46202. /**
  46203. * Builds the given shader node.
  46204. *
  46205. * @param {ShaderNodeInternal} shaderNode - The shader node.
  46206. * @return {string} The WGSL function code.
  46207. */
  46208. buildFunctionCode( shaderNode ) {
  46209. const layout = shaderNode.layout;
  46210. const flowData = this.flowShaderNode( shaderNode );
  46211. const parameters = [];
  46212. for ( const input of layout.inputs ) {
  46213. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  46214. }
  46215. //
  46216. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  46217. ${ flowData.vars }
  46218. ${ flowData.code }
  46219. `;
  46220. if ( flowData.result ) {
  46221. code += `\treturn ${ flowData.result };\n`;
  46222. }
  46223. code += '\n}\n';
  46224. //
  46225. return code;
  46226. }
  46227. /**
  46228. * Returns the instance index builtin.
  46229. *
  46230. * @return {string} The instance index.
  46231. */
  46232. getInstanceIndex() {
  46233. if ( this.shaderStage === 'vertex' ) {
  46234. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  46235. }
  46236. return 'instanceIndex';
  46237. }
  46238. /**
  46239. * Returns the invocation local index builtin.
  46240. *
  46241. * @return {string} The invocation local index.
  46242. */
  46243. getInvocationLocalIndex() {
  46244. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  46245. }
  46246. /**
  46247. * Returns the subgroup size builtin.
  46248. *
  46249. * @return {string} The subgroup size.
  46250. */
  46251. getSubgroupSize() {
  46252. this.enableSubGroups();
  46253. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  46254. }
  46255. /**
  46256. * Returns the invocation subgroup index builtin.
  46257. *
  46258. * @return {string} The invocation subgroup index.
  46259. */
  46260. getInvocationSubgroupIndex() {
  46261. this.enableSubGroups();
  46262. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  46263. }
  46264. /**
  46265. * Returns the subgroup index builtin.
  46266. *
  46267. * @return {string} The subgroup index.
  46268. */
  46269. getSubgroupIndex() {
  46270. this.enableSubGroups();
  46271. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  46272. }
  46273. /**
  46274. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  46275. *
  46276. * @return {null} Null.
  46277. */
  46278. getDrawIndex() {
  46279. return null;
  46280. }
  46281. /**
  46282. * Returns the front facing builtin.
  46283. *
  46284. * @return {string} The front facing builtin.
  46285. */
  46286. getFrontFacing() {
  46287. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  46288. }
  46289. /**
  46290. * Returns the frag coord builtin.
  46291. *
  46292. * @return {string} The frag coord builtin.
  46293. */
  46294. getFragCoord() {
  46295. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  46296. }
  46297. /**
  46298. * Returns the frag depth builtin.
  46299. *
  46300. * @return {string} The frag depth builtin.
  46301. */
  46302. getFragDepth() {
  46303. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  46304. }
  46305. /**
  46306. * Returns the clip distances builtin.
  46307. *
  46308. * @return {string} The clip distances builtin.
  46309. */
  46310. getClipDistance() {
  46311. return 'varyings.hw_clip_distances';
  46312. }
  46313. /**
  46314. * Whether to flip texture data along its vertical axis or not.
  46315. *
  46316. * @return {boolean} Returns always `false` in context of WGSL.
  46317. */
  46318. isFlipY() {
  46319. return false;
  46320. }
  46321. /**
  46322. * Enables the given directive for the given shader stage.
  46323. *
  46324. * @param {string} name - The directive name.
  46325. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  46326. */
  46327. enableDirective( name, shaderStage = this.shaderStage ) {
  46328. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  46329. stage.add( name );
  46330. }
  46331. /**
  46332. * Returns the directives of the given shader stage as a WGSL string.
  46333. *
  46334. * @param {string} shaderStage - The shader stage.
  46335. * @return {string} A WGSL snippet that enables the directives of the given stage.
  46336. */
  46337. getDirectives( shaderStage ) {
  46338. const snippets = [];
  46339. const directives = this.directives[ shaderStage ];
  46340. if ( directives !== undefined ) {
  46341. for ( const directive of directives ) {
  46342. snippets.push( `enable ${directive};` );
  46343. }
  46344. }
  46345. return snippets.join( '\n' );
  46346. }
  46347. /**
  46348. * Enables the 'subgroups' directive.
  46349. */
  46350. enableSubGroups() {
  46351. this.enableDirective( 'subgroups' );
  46352. }
  46353. /**
  46354. * Enables the 'subgroups-f16' directive.
  46355. */
  46356. enableSubgroupsF16() {
  46357. this.enableDirective( 'subgroups-f16' );
  46358. }
  46359. /**
  46360. * Enables the 'clip_distances' directive.
  46361. */
  46362. enableClipDistances() {
  46363. this.enableDirective( 'clip_distances' );
  46364. }
  46365. /**
  46366. * Enables the 'f16' directive.
  46367. */
  46368. enableShaderF16() {
  46369. this.enableDirective( 'f16' );
  46370. }
  46371. /**
  46372. * Enables the 'dual_source_blending' directive.
  46373. */
  46374. enableDualSourceBlending() {
  46375. this.enableDirective( 'dual_source_blending' );
  46376. }
  46377. /**
  46378. * Enables hardware clipping.
  46379. *
  46380. * @param {string} planeCount - The clipping plane count.
  46381. */
  46382. enableHardwareClipping( planeCount ) {
  46383. this.enableClipDistances();
  46384. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  46385. }
  46386. /**
  46387. * Returns the builtins of the given shader stage as a WGSL string.
  46388. *
  46389. * @param {string} shaderStage - The shader stage.
  46390. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  46391. */
  46392. getBuiltins( shaderStage ) {
  46393. const snippets = [];
  46394. const builtins = this.builtins[ shaderStage ];
  46395. if ( builtins !== undefined ) {
  46396. for ( const { name, property, type } of builtins.values() ) {
  46397. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  46398. }
  46399. }
  46400. return snippets.join( ',\n\t' );
  46401. }
  46402. /**
  46403. * This method should be used when a new scoped buffer is used in context of
  46404. * compute shaders. It adds the array to the internal data structure which is
  46405. * later used to generate the respective WGSL.
  46406. *
  46407. * @param {string} name - The array name.
  46408. * @param {string} scope - The scope.
  46409. * @param {string} bufferType - The buffer type.
  46410. * @param {string} bufferCount - The buffer count.
  46411. * @return {string} The array name.
  46412. */
  46413. getScopedArray( name, scope, bufferType, bufferCount ) {
  46414. if ( this.scopedArrays.has( name ) === false ) {
  46415. this.scopedArrays.set( name, {
  46416. name,
  46417. scope,
  46418. bufferType,
  46419. bufferCount
  46420. } );
  46421. }
  46422. return name;
  46423. }
  46424. /**
  46425. * Returns the scoped arrays of the given shader stage as a WGSL string.
  46426. *
  46427. * @param {string} shaderStage - The shader stage.
  46428. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  46429. * Returns `undefined` when used in the vertex or fragment stage.
  46430. */
  46431. getScopedArrays( shaderStage ) {
  46432. if ( shaderStage !== 'compute' ) {
  46433. return;
  46434. }
  46435. const snippets = [];
  46436. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  46437. const type = this.getType( bufferType );
  46438. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  46439. }
  46440. return snippets.join( '\n' );
  46441. }
  46442. /**
  46443. * Returns the shader attributes of the given shader stage as a WGSL string.
  46444. *
  46445. * @param {string} shaderStage - The shader stage.
  46446. * @return {string} The WGSL snippet that defines the shader attributes.
  46447. */
  46448. getAttributes( shaderStage ) {
  46449. const snippets = [];
  46450. if ( shaderStage === 'compute' ) {
  46451. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  46452. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  46453. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  46454. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  46455. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  46456. this.enableDirective( 'subgroups', shaderStage );
  46457. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  46458. }
  46459. }
  46460. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  46461. const builtins = this.getBuiltins( 'attribute' );
  46462. if ( builtins ) snippets.push( builtins );
  46463. const attributes = this.getAttributesArray();
  46464. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  46465. const attribute = attributes[ index ];
  46466. const name = attribute.name;
  46467. const type = this.getType( attribute.type );
  46468. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  46469. }
  46470. }
  46471. return snippets.join( ',\n\t' );
  46472. }
  46473. /**
  46474. * Returns the members of the given struct type node as a WGSL string.
  46475. *
  46476. * @param {StructTypeNode} struct - The struct type node.
  46477. * @return {string} The WGSL snippet that defines the struct members.
  46478. */
  46479. getStructMembers( struct ) {
  46480. const snippets = [];
  46481. for ( const member of struct.members ) {
  46482. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  46483. let type = this.getType( member.type );
  46484. if ( member.atomic ) {
  46485. type = 'atomic< ' + type + ' >';
  46486. }
  46487. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  46488. }
  46489. if ( struct.output ) {
  46490. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  46491. }
  46492. return snippets.join( ',\n' );
  46493. }
  46494. /**
  46495. * Returns the structs of the given shader stage as a WGSL string.
  46496. *
  46497. * @param {string} shaderStage - The shader stage.
  46498. * @return {string} The WGSL snippet that defines the structs.
  46499. */
  46500. getStructs( shaderStage ) {
  46501. let result = '';
  46502. const structs = this.structs[ shaderStage ];
  46503. if ( structs.length > 0 ) {
  46504. const snippets = [];
  46505. for ( const struct of structs ) {
  46506. let snippet = `struct ${ struct.name } {\n`;
  46507. snippet += this.getStructMembers( struct );
  46508. snippet += '\n};';
  46509. snippets.push( snippet );
  46510. }
  46511. result = '\n' + snippets.join( '\n\n' ) + '\n';
  46512. }
  46513. return result;
  46514. }
  46515. /**
  46516. * Returns a WGSL string representing a variable.
  46517. *
  46518. * @param {string} type - The variable's type.
  46519. * @param {string} name - The variable's name.
  46520. * @param {?number} [count=null] - The array length.
  46521. * @return {string} The WGSL snippet that defines a variable.
  46522. */
  46523. getVar( type, name, count = null ) {
  46524. let snippet = `var ${ name } : `;
  46525. if ( count !== null ) {
  46526. snippet += this.generateArrayDeclaration( type, count );
  46527. } else {
  46528. snippet += this.getType( type );
  46529. }
  46530. return snippet;
  46531. }
  46532. /**
  46533. * Returns the variables of the given shader stage as a WGSL string.
  46534. *
  46535. * @param {string} shaderStage - The shader stage.
  46536. * @return {string} The WGSL snippet that defines the variables.
  46537. */
  46538. getVars( shaderStage ) {
  46539. const snippets = [];
  46540. const vars = this.vars[ shaderStage ];
  46541. if ( vars !== undefined ) {
  46542. for ( const variable of vars ) {
  46543. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  46544. }
  46545. }
  46546. return `\n${ snippets.join( '\n' ) }\n`;
  46547. }
  46548. /**
  46549. * Returns the varyings of the given shader stage as a WGSL string.
  46550. *
  46551. * @param {string} shaderStage - The shader stage.
  46552. * @return {string} The WGSL snippet that defines the varyings.
  46553. */
  46554. getVaryings( shaderStage ) {
  46555. const snippets = [];
  46556. if ( shaderStage === 'vertex' ) {
  46557. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  46558. }
  46559. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  46560. const varyings = this.varyings;
  46561. const vars = this.vars[ shaderStage ];
  46562. for ( let index = 0; index < varyings.length; index ++ ) {
  46563. const varying = varyings[ index ];
  46564. if ( varying.needsInterpolation ) {
  46565. let attributesSnippet = `@location( ${index} )`;
  46566. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  46567. attributesSnippet += ' @interpolate( flat )';
  46568. }
  46569. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  46570. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  46571. vars.push( varying );
  46572. }
  46573. }
  46574. }
  46575. const builtins = this.getBuiltins( shaderStage );
  46576. if ( builtins ) snippets.push( builtins );
  46577. const code = snippets.join( ',\n\t' );
  46578. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  46579. }
  46580. isCustomStruct( nodeUniform ) {
  46581. return nodeUniform.value.isStorageBufferAttribute && nodeUniform.node.structTypeNode !== null;
  46582. }
  46583. /**
  46584. * Returns the uniforms of the given shader stage as a WGSL string.
  46585. *
  46586. * @param {string} shaderStage - The shader stage.
  46587. * @return {string} The WGSL snippet that defines the uniforms.
  46588. */
  46589. getUniforms( shaderStage ) {
  46590. const uniforms = this.uniforms[ shaderStage ];
  46591. const bindingSnippets = [];
  46592. const bufferSnippets = [];
  46593. const structSnippets = [];
  46594. const uniformGroups = {};
  46595. for ( const uniform of uniforms ) {
  46596. const groupName = uniform.groupNode.name;
  46597. const uniformIndexes = this.bindingsIndexes[ groupName ];
  46598. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  46599. const texture = uniform.node.value;
  46600. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  46601. if ( this.isSampleCompare( texture ) ) {
  46602. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  46603. } else {
  46604. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  46605. }
  46606. }
  46607. let textureType;
  46608. let multisampled = '';
  46609. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  46610. if ( primarySamples > 1 ) {
  46611. multisampled = '_multisampled';
  46612. }
  46613. if ( texture.isCubeTexture === true ) {
  46614. textureType = 'texture_cube<f32>';
  46615. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  46616. textureType = 'texture_2d_array<f32>';
  46617. } else if ( texture.isDepthTexture === true ) {
  46618. textureType = `texture_depth${multisampled}_2d`;
  46619. } else if ( texture.isVideoTexture === true ) {
  46620. textureType = 'texture_external';
  46621. } else if ( texture.isData3DTexture === true ) {
  46622. textureType = 'texture_3d<f32>';
  46623. } else if ( uniform.node.isStorageTextureNode === true ) {
  46624. const format = getFormat( texture );
  46625. const access = this.getStorageAccess( uniform.node, shaderStage );
  46626. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  46627. } else {
  46628. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  46629. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  46630. }
  46631. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  46632. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  46633. const bufferNode = uniform.node;
  46634. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  46635. const bufferCount = bufferNode.bufferCount;
  46636. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  46637. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  46638. if ( this.isCustomStruct( uniform ) ) {
  46639. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  46640. } else {
  46641. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  46642. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  46643. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  46644. }
  46645. } else {
  46646. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  46647. const groupName = uniform.groupNode.name;
  46648. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  46649. index: uniformIndexes.binding ++,
  46650. id: uniformIndexes.group,
  46651. snippets: []
  46652. } );
  46653. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  46654. }
  46655. }
  46656. for ( const name in uniformGroups ) {
  46657. const group = uniformGroups[ name ];
  46658. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  46659. }
  46660. let code = bindingSnippets.join( '\n' );
  46661. code += bufferSnippets.join( '\n' );
  46662. code += structSnippets.join( '\n' );
  46663. return code;
  46664. }
  46665. /**
  46666. * Controls the code build of the shader stages.
  46667. */
  46668. buildCode() {
  46669. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  46670. this.sortBindingGroups();
  46671. for ( const shaderStage in shadersData ) {
  46672. this.shaderStage = shaderStage;
  46673. const stageData = shadersData[ shaderStage ];
  46674. stageData.uniforms = this.getUniforms( shaderStage );
  46675. stageData.attributes = this.getAttributes( shaderStage );
  46676. stageData.varyings = this.getVaryings( shaderStage );
  46677. stageData.structs = this.getStructs( shaderStage );
  46678. stageData.vars = this.getVars( shaderStage );
  46679. stageData.codes = this.getCodes( shaderStage );
  46680. stageData.directives = this.getDirectives( shaderStage );
  46681. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  46682. //
  46683. let flow = '// code\n\n';
  46684. flow += this.flowCode[ shaderStage ];
  46685. const flowNodes = this.flowNodes[ shaderStage ];
  46686. const mainNode = flowNodes[ flowNodes.length - 1 ];
  46687. const outputNode = mainNode.outputNode;
  46688. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  46689. for ( const node of flowNodes ) {
  46690. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  46691. const slotName = node.name;
  46692. if ( slotName ) {
  46693. if ( flow.length > 0 ) flow += '\n';
  46694. flow += `\t// flow -> ${ slotName }\n`;
  46695. }
  46696. flow += `${ flowSlotData.code }\n\t`;
  46697. if ( node === mainNode && shaderStage !== 'compute' ) {
  46698. flow += '// result\n\n\t';
  46699. if ( shaderStage === 'vertex' ) {
  46700. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  46701. } else if ( shaderStage === 'fragment' ) {
  46702. if ( isOutputStruct ) {
  46703. stageData.returnType = outputNode.getNodeType( this );
  46704. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  46705. flow += `return ${ flowSlotData.result };`;
  46706. } else {
  46707. let structSnippet = '\t@location(0) color: vec4<f32>';
  46708. const builtins = this.getBuiltins( 'output' );
  46709. if ( builtins ) structSnippet += ',\n\t' + builtins;
  46710. stageData.returnType = 'OutputStruct';
  46711. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  46712. stageData.structs += '\nvar<private> output : OutputStruct;';
  46713. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  46714. }
  46715. }
  46716. }
  46717. }
  46718. stageData.flow = flow;
  46719. }
  46720. this.shaderStage = null;
  46721. if ( this.material !== null ) {
  46722. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  46723. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  46724. } else {
  46725. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  46726. }
  46727. }
  46728. /**
  46729. * Returns the native shader method name for a given generic name.
  46730. *
  46731. * @param {string} method - The method name to resolve.
  46732. * @param {?string} [output=null] - An optional output.
  46733. * @return {string} The resolved WGSL method name.
  46734. */
  46735. getMethod( method, output = null ) {
  46736. let wgslMethod;
  46737. if ( output !== null ) {
  46738. wgslMethod = this._getWGSLMethod( method + '_' + output );
  46739. }
  46740. if ( wgslMethod === undefined ) {
  46741. wgslMethod = this._getWGSLMethod( method );
  46742. }
  46743. return wgslMethod || method;
  46744. }
  46745. /**
  46746. * Returns the WGSL type of the given node data type.
  46747. *
  46748. * @param {string} type - The node data type.
  46749. * @return {string} The WGSL type.
  46750. */
  46751. getType( type ) {
  46752. return wgslTypeLib[ type ] || type;
  46753. }
  46754. /**
  46755. * Whether the requested feature is available or not.
  46756. *
  46757. * @param {string} name - The requested feature.
  46758. * @return {boolean} Whether the requested feature is supported or not.
  46759. */
  46760. isAvailable( name ) {
  46761. let result = supports[ name ];
  46762. if ( result === undefined ) {
  46763. if ( name === 'float32Filterable' ) {
  46764. result = this.renderer.hasFeature( 'float32-filterable' );
  46765. } else if ( name === 'clipDistance' ) {
  46766. result = this.renderer.hasFeature( 'clip-distances' );
  46767. }
  46768. supports[ name ] = result;
  46769. }
  46770. return result;
  46771. }
  46772. /**
  46773. * Returns the native shader method name for a given generic name.
  46774. *
  46775. * @private
  46776. * @param {string} method - The method name to resolve.
  46777. * @return {string} The resolved WGSL method name.
  46778. */
  46779. _getWGSLMethod( method ) {
  46780. if ( wgslPolyfill[ method ] !== undefined ) {
  46781. this._include( method );
  46782. }
  46783. return wgslMethods[ method ];
  46784. }
  46785. /**
  46786. * Includes the given method name into the current
  46787. * function node.
  46788. *
  46789. * @private
  46790. * @param {string} name - The method name to include.
  46791. * @return {CodeNode} The respective code node.
  46792. */
  46793. _include( name ) {
  46794. const codeNode = wgslPolyfill[ name ];
  46795. codeNode.build( this );
  46796. if ( this.currentFunctionNode !== null ) {
  46797. this.currentFunctionNode.includes.push( codeNode );
  46798. }
  46799. return codeNode;
  46800. }
  46801. /**
  46802. * Returns a WGSL vertex shader based on the given shader data.
  46803. *
  46804. * @private
  46805. * @param {Object} shaderData - The shader data.
  46806. * @return {string} The vertex shader.
  46807. */
  46808. _getWGSLVertexCode( shaderData ) {
  46809. return `${ this.getSignature() }
  46810. // directives
  46811. ${shaderData.directives}
  46812. // structs
  46813. ${shaderData.structs}
  46814. // uniforms
  46815. ${shaderData.uniforms}
  46816. // varyings
  46817. ${shaderData.varyings}
  46818. var<private> varyings : VaryingsStruct;
  46819. // codes
  46820. ${shaderData.codes}
  46821. @vertex
  46822. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  46823. // vars
  46824. ${shaderData.vars}
  46825. // flow
  46826. ${shaderData.flow}
  46827. return varyings;
  46828. }
  46829. `;
  46830. }
  46831. /**
  46832. * Returns a WGSL fragment shader based on the given shader data.
  46833. *
  46834. * @private
  46835. * @param {Object} shaderData - The shader data.
  46836. * @return {string} The vertex shader.
  46837. */
  46838. _getWGSLFragmentCode( shaderData ) {
  46839. return `${ this.getSignature() }
  46840. // global
  46841. ${ diagnostics }
  46842. // structs
  46843. ${shaderData.structs}
  46844. // uniforms
  46845. ${shaderData.uniforms}
  46846. // codes
  46847. ${shaderData.codes}
  46848. @fragment
  46849. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  46850. // vars
  46851. ${shaderData.vars}
  46852. // flow
  46853. ${shaderData.flow}
  46854. }
  46855. `;
  46856. }
  46857. /**
  46858. * Returns a WGSL compute shader based on the given shader data.
  46859. *
  46860. * @private
  46861. * @param {Object} shaderData - The shader data.
  46862. * @param {string} workgroupSize - The workgroup size.
  46863. * @return {string} The vertex shader.
  46864. */
  46865. _getWGSLComputeCode( shaderData, workgroupSize ) {
  46866. return `${ this.getSignature() }
  46867. // directives
  46868. ${shaderData.directives}
  46869. // system
  46870. var<private> instanceIndex : u32;
  46871. // locals
  46872. ${shaderData.scopedArrays}
  46873. // structs
  46874. ${shaderData.structs}
  46875. // uniforms
  46876. ${shaderData.uniforms}
  46877. // codes
  46878. ${shaderData.codes}
  46879. @compute @workgroup_size( ${workgroupSize} )
  46880. fn main( ${shaderData.attributes} ) {
  46881. // system
  46882. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  46883. // vars
  46884. ${shaderData.vars}
  46885. // flow
  46886. ${shaderData.flow}
  46887. }
  46888. `;
  46889. }
  46890. /**
  46891. * Returns a WGSL struct based on the given name and variables.
  46892. *
  46893. * @private
  46894. * @param {string} name - The struct name.
  46895. * @param {string} vars - The struct variables.
  46896. * @return {string} The WGSL snippet representing a struct.
  46897. */
  46898. _getWGSLStruct( name, vars ) {
  46899. return `
  46900. struct ${name} {
  46901. ${vars}
  46902. };`;
  46903. }
  46904. /**
  46905. * Returns a WGSL struct binding.
  46906. *
  46907. * @private
  46908. * @param {string} name - The struct name.
  46909. * @param {string} vars - The struct variables.
  46910. * @param {string} access - The access.
  46911. * @param {number} [binding=0] - The binding index.
  46912. * @param {number} [group=0] - The group index.
  46913. * @return {string} The WGSL snippet representing a struct binding.
  46914. */
  46915. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  46916. const structName = name + 'Struct';
  46917. const structSnippet = this._getWGSLStruct( structName, vars );
  46918. return `${structSnippet}
  46919. @binding( ${ binding } ) @group( ${ group } )
  46920. var<${access}> ${ name } : ${ structName };`;
  46921. }
  46922. }
  46923. /**
  46924. * A WebGPU backend utility module with common helpers.
  46925. *
  46926. * @private
  46927. */
  46928. class WebGPUUtils {
  46929. /**
  46930. * Constructs a new utility object.
  46931. *
  46932. * @param {WebGPUBackend} backend - The WebGPU backend.
  46933. */
  46934. constructor( backend ) {
  46935. /**
  46936. * A reference to the WebGPU backend.
  46937. *
  46938. * @type {WebGPUBackend}
  46939. */
  46940. this.backend = backend;
  46941. }
  46942. /**
  46943. * Returns the depth/stencil GPU format for the given render context.
  46944. *
  46945. * @param {RenderContext} renderContext - The render context.
  46946. * @return {string} The depth/stencil GPU texture format.
  46947. */
  46948. getCurrentDepthStencilFormat( renderContext ) {
  46949. let format;
  46950. if ( renderContext.depthTexture !== null ) {
  46951. format = this.getTextureFormatGPU( renderContext.depthTexture );
  46952. } else if ( renderContext.depth && renderContext.stencil ) {
  46953. format = GPUTextureFormat.Depth24PlusStencil8;
  46954. } else if ( renderContext.depth ) {
  46955. format = GPUTextureFormat.Depth24Plus;
  46956. }
  46957. return format;
  46958. }
  46959. /**
  46960. * Returns the GPU format for the given texture.
  46961. *
  46962. * @param {Texture} texture - The texture.
  46963. * @return {string} The GPU texture format.
  46964. */
  46965. getTextureFormatGPU( texture ) {
  46966. return this.backend.get( texture ).format;
  46967. }
  46968. /**
  46969. * Returns an object that defines the multi-sampling state of the given texture.
  46970. *
  46971. * @param {Texture} texture - The texture.
  46972. * @return {Object} The multi-sampling state.
  46973. */
  46974. getTextureSampleData( texture ) {
  46975. let samples;
  46976. if ( texture.isFramebufferTexture ) {
  46977. samples = 1;
  46978. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  46979. const renderer = this.backend.renderer;
  46980. const renderTarget = renderer.getRenderTarget();
  46981. samples = renderTarget ? renderTarget.samples : renderer.samples;
  46982. } else if ( texture.renderTarget ) {
  46983. samples = texture.renderTarget.samples;
  46984. }
  46985. samples = samples || 1;
  46986. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  46987. const primarySamples = isMSAA ? 1 : samples;
  46988. return { samples, primarySamples, isMSAA };
  46989. }
  46990. /**
  46991. * Returns the default color attachment's GPU format of the current render context.
  46992. *
  46993. * @param {RenderContext} renderContext - The render context.
  46994. * @return {string} The GPU texture format of the default color attachment.
  46995. */
  46996. getCurrentColorFormat( renderContext ) {
  46997. let format;
  46998. if ( renderContext.textures !== null ) {
  46999. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  47000. } else {
  47001. format = this.getPreferredCanvasFormat(); // default context format
  47002. }
  47003. return format;
  47004. }
  47005. /**
  47006. * Returns the output color space of the current render context.
  47007. *
  47008. * @param {RenderContext} renderContext - The render context.
  47009. * @return {string} The output color space.
  47010. */
  47011. getCurrentColorSpace( renderContext ) {
  47012. if ( renderContext.textures !== null ) {
  47013. return renderContext.textures[ 0 ].colorSpace;
  47014. }
  47015. return this.backend.renderer.outputColorSpace;
  47016. }
  47017. /**
  47018. * Returns GPU primitive topology for the given object and material.
  47019. *
  47020. * @param {Object3D} object - The 3D object.
  47021. * @param {Material} material - The material.
  47022. * @return {string} The GPU primitive topology.
  47023. */
  47024. getPrimitiveTopology( object, material ) {
  47025. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  47026. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  47027. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  47028. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  47029. }
  47030. /**
  47031. * Returns a modified sample count from the given sample count value.
  47032. *
  47033. * That is required since WebGPU does not support arbitrary sample counts.
  47034. *
  47035. * @param {number} sampleCount - The input sample count.
  47036. * @return {number} The (potentially updated) output sample count.
  47037. */
  47038. getSampleCount( sampleCount ) {
  47039. let count = 1;
  47040. if ( sampleCount > 1 ) {
  47041. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  47042. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  47043. if ( count === 2 ) {
  47044. count = 4;
  47045. }
  47046. }
  47047. return count;
  47048. }
  47049. /**
  47050. * Returns the sample count of the given render context.
  47051. *
  47052. * @param {RenderContext} renderContext - The render context.
  47053. * @return {number} The sample count.
  47054. */
  47055. getSampleCountRenderContext( renderContext ) {
  47056. if ( renderContext.textures !== null ) {
  47057. return this.getSampleCount( renderContext.sampleCount );
  47058. }
  47059. return this.getSampleCount( this.backend.renderer.samples );
  47060. }
  47061. /**
  47062. * Returns the preferred canvas format.
  47063. *
  47064. * There is a separate method for this so it's possible to
  47065. * honor edge cases for specific devices.
  47066. *
  47067. * @return {string} The GPU texture format of the canvas.
  47068. */
  47069. getPreferredCanvasFormat() {
  47070. const outputType = this.backend.parameters.outputType;
  47071. if ( outputType === undefined ) {
  47072. return navigator.gpu.getPreferredCanvasFormat();
  47073. } else if ( outputType === UnsignedByteType ) {
  47074. return GPUTextureFormat.BGRA8Unorm;
  47075. } else if ( outputType === HalfFloatType ) {
  47076. return GPUTextureFormat.RGBA16Float;
  47077. } else {
  47078. throw new Error( 'Unsupported outputType' );
  47079. }
  47080. }
  47081. }
  47082. const typedArraysToVertexFormatPrefix = new Map( [
  47083. [ Int8Array, [ 'sint8', 'snorm8' ]],
  47084. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  47085. [ Int16Array, [ 'sint16', 'snorm16' ]],
  47086. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  47087. [ Int32Array, [ 'sint32', 'snorm32' ]],
  47088. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  47089. [ Float32Array, [ 'float32', ]],
  47090. ] );
  47091. const typedAttributeToVertexFormatPrefix = new Map( [
  47092. [ Float16BufferAttribute, [ 'float16', ]],
  47093. ] );
  47094. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  47095. [ Int32Array, 'sint32' ],
  47096. [ Int16Array, 'sint32' ], // patch for INT16
  47097. [ Uint32Array, 'uint32' ],
  47098. [ Uint16Array, 'uint32' ], // patch for UINT16
  47099. [ Float32Array, 'float32' ]
  47100. ] );
  47101. /**
  47102. * A WebGPU backend utility module for managing shader attributes.
  47103. *
  47104. * @private
  47105. */
  47106. class WebGPUAttributeUtils {
  47107. /**
  47108. * Constructs a new utility object.
  47109. *
  47110. * @param {WebGPUBackend} backend - The WebGPU backend.
  47111. */
  47112. constructor( backend ) {
  47113. /**
  47114. * A reference to the WebGPU backend.
  47115. *
  47116. * @type {WebGPUBackend}
  47117. */
  47118. this.backend = backend;
  47119. }
  47120. /**
  47121. * Creates the GPU buffer for the given buffer attribute.
  47122. *
  47123. * @param {BufferAttribute} attribute - The buffer attribute.
  47124. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  47125. */
  47126. createAttribute( attribute, usage ) {
  47127. const bufferAttribute = this._getBufferAttribute( attribute );
  47128. const backend = this.backend;
  47129. const bufferData = backend.get( bufferAttribute );
  47130. let buffer = bufferData.buffer;
  47131. if ( buffer === undefined ) {
  47132. const device = backend.device;
  47133. let array = bufferAttribute.array;
  47134. // patch for INT16 and UINT16
  47135. if ( attribute.normalized === false ) {
  47136. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  47137. array = new Int32Array( array );
  47138. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  47139. array = new Uint32Array( array );
  47140. if ( usage & GPUBufferUsage.INDEX ) {
  47141. for ( let i = 0; i < array.length; i ++ ) {
  47142. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  47143. }
  47144. }
  47145. }
  47146. }
  47147. bufferAttribute.array = array;
  47148. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  47149. array = new array.constructor( bufferAttribute.count * 4 );
  47150. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  47151. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  47152. }
  47153. // Update BufferAttribute
  47154. bufferAttribute.itemSize = 4;
  47155. bufferAttribute.array = array;
  47156. bufferData._force3to4BytesAlignment = true;
  47157. }
  47158. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  47159. buffer = device.createBuffer( {
  47160. label: bufferAttribute.name,
  47161. size: size,
  47162. usage: usage,
  47163. mappedAtCreation: true
  47164. } );
  47165. new array.constructor( buffer.getMappedRange() ).set( array );
  47166. buffer.unmap();
  47167. bufferData.buffer = buffer;
  47168. }
  47169. }
  47170. /**
  47171. * Updates the GPU buffer of the given buffer attribute.
  47172. *
  47173. * @param {BufferAttribute} attribute - The buffer attribute.
  47174. */
  47175. updateAttribute( attribute ) {
  47176. const bufferAttribute = this._getBufferAttribute( attribute );
  47177. const backend = this.backend;
  47178. const device = backend.device;
  47179. const bufferData = backend.get( bufferAttribute );
  47180. const buffer = backend.get( bufferAttribute ).buffer;
  47181. let array = bufferAttribute.array;
  47182. // if storage buffer ensure 4 byte alignment
  47183. if ( bufferData._force3to4BytesAlignment === true ) {
  47184. array = new array.constructor( bufferAttribute.count * 4 );
  47185. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  47186. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  47187. }
  47188. bufferAttribute.array = array;
  47189. }
  47190. const isTypedArray = this._isTypedArray( array );
  47191. const updateRanges = bufferAttribute.updateRanges;
  47192. if ( updateRanges.length === 0 ) {
  47193. // Not using update ranges
  47194. device.queue.writeBuffer(
  47195. buffer,
  47196. 0,
  47197. array,
  47198. 0
  47199. );
  47200. } else {
  47201. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  47202. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  47203. const range = updateRanges[ i ];
  47204. let dataOffset, size;
  47205. if ( bufferData._force3to4BytesAlignment === true ) {
  47206. const vertexStart = Math.floor( range.start / 3 );
  47207. const vertexCount = Math.ceil( range.count / 3 );
  47208. dataOffset = vertexStart * 4 * byteOffsetFactor;
  47209. size = vertexCount * 4 * byteOffsetFactor;
  47210. } else {
  47211. dataOffset = range.start * byteOffsetFactor;
  47212. size = range.count * byteOffsetFactor;
  47213. }
  47214. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  47215. device.queue.writeBuffer(
  47216. buffer,
  47217. bufferOffset,
  47218. array,
  47219. dataOffset,
  47220. size
  47221. );
  47222. }
  47223. bufferAttribute.clearUpdateRanges();
  47224. }
  47225. }
  47226. /**
  47227. * This method creates the vertex buffer layout data which are
  47228. * require when creating a render pipeline for the given render object.
  47229. *
  47230. * @param {RenderObject} renderObject - The render object.
  47231. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  47232. */
  47233. createShaderVertexBuffers( renderObject ) {
  47234. const attributes = renderObject.getAttributes();
  47235. const vertexBuffers = new Map();
  47236. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  47237. const geometryAttribute = attributes[ slot ];
  47238. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  47239. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  47240. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  47241. if ( vertexBufferLayout === undefined ) {
  47242. let arrayStride, stepMode;
  47243. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  47244. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  47245. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  47246. } else {
  47247. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  47248. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  47249. }
  47250. // patch for INT16 and UINT16
  47251. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  47252. arrayStride = 4;
  47253. }
  47254. vertexBufferLayout = {
  47255. arrayStride,
  47256. attributes: [],
  47257. stepMode
  47258. };
  47259. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  47260. }
  47261. const format = this._getVertexFormat( geometryAttribute );
  47262. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  47263. vertexBufferLayout.attributes.push( {
  47264. shaderLocation: slot,
  47265. offset,
  47266. format
  47267. } );
  47268. }
  47269. return Array.from( vertexBuffers.values() );
  47270. }
  47271. /**
  47272. * Destroys the GPU buffer of the given buffer attribute.
  47273. *
  47274. * @param {BufferAttribute} attribute - The buffer attribute.
  47275. */
  47276. destroyAttribute( attribute ) {
  47277. const backend = this.backend;
  47278. const data = backend.get( this._getBufferAttribute( attribute ) );
  47279. data.buffer.destroy();
  47280. backend.delete( attribute );
  47281. }
  47282. /**
  47283. * This method performs a readback operation by moving buffer data from
  47284. * a storage buffer attribute from the GPU to the CPU.
  47285. *
  47286. * @async
  47287. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47288. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47289. */
  47290. async getArrayBufferAsync( attribute ) {
  47291. const backend = this.backend;
  47292. const device = backend.device;
  47293. const data = backend.get( this._getBufferAttribute( attribute ) );
  47294. const bufferGPU = data.buffer;
  47295. const size = bufferGPU.size;
  47296. const readBufferGPU = device.createBuffer( {
  47297. label: `${ attribute.name }_readback`,
  47298. size,
  47299. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47300. } );
  47301. const cmdEncoder = device.createCommandEncoder( {
  47302. label: `readback_encoder_${ attribute.name }`
  47303. } );
  47304. cmdEncoder.copyBufferToBuffer(
  47305. bufferGPU,
  47306. 0,
  47307. readBufferGPU,
  47308. 0,
  47309. size
  47310. );
  47311. const gpuCommands = cmdEncoder.finish();
  47312. device.queue.submit( [ gpuCommands ] );
  47313. await readBufferGPU.mapAsync( GPUMapMode.READ );
  47314. const arrayBuffer = readBufferGPU.getMappedRange();
  47315. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  47316. readBufferGPU.unmap();
  47317. return dstBuffer.buffer;
  47318. }
  47319. /**
  47320. * Returns the vertex format of the given buffer attribute.
  47321. *
  47322. * @private
  47323. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  47324. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  47325. */
  47326. _getVertexFormat( geometryAttribute ) {
  47327. const { itemSize, normalized } = geometryAttribute;
  47328. const ArrayType = geometryAttribute.array.constructor;
  47329. const AttributeType = geometryAttribute.constructor;
  47330. let format;
  47331. if ( itemSize === 1 ) {
  47332. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  47333. } else {
  47334. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  47335. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  47336. if ( prefix ) {
  47337. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  47338. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  47339. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  47340. if ( paddedItemSize % 1 ) {
  47341. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  47342. }
  47343. format = `${prefix}x${paddedItemSize}`;
  47344. }
  47345. }
  47346. if ( ! format ) {
  47347. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  47348. }
  47349. return format;
  47350. }
  47351. /**
  47352. * Returns `true` if the given array is a typed array.
  47353. *
  47354. * @private
  47355. * @param {any} array - The array.
  47356. * @return {boolean} Whether the given array is a typed array or not.
  47357. */
  47358. _isTypedArray( array ) {
  47359. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  47360. }
  47361. /**
  47362. * Utility method for handling interleaved buffer attributes correctly.
  47363. * To process them, their `InterleavedBuffer` is returned.
  47364. *
  47365. * @private
  47366. * @param {BufferAttribute} attribute - The attribute.
  47367. * @return {BufferAttribute|InterleavedBuffer}
  47368. */
  47369. _getBufferAttribute( attribute ) {
  47370. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  47371. return attribute;
  47372. }
  47373. }
  47374. /**
  47375. * A WebGPU backend utility module for managing bindings.
  47376. *
  47377. * When reading the documentation it's helpful to keep in mind that
  47378. * all class definitions starting with 'GPU*' are modules from the
  47379. * WebGPU API. So for example `BindGroup` is a class from the engine
  47380. * whereas `GPUBindGroup` is a class from WebGPU.
  47381. *
  47382. * @private
  47383. */
  47384. class WebGPUBindingUtils {
  47385. /**
  47386. * Constructs a new utility object.
  47387. *
  47388. * @param {WebGPUBackend} backend - The WebGPU backend.
  47389. */
  47390. constructor( backend ) {
  47391. /**
  47392. * A reference to the WebGPU backend.
  47393. *
  47394. * @type {WebGPUBackend}
  47395. */
  47396. this.backend = backend;
  47397. /**
  47398. * A cache for managing bind group layouts.
  47399. *
  47400. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  47401. */
  47402. this.bindGroupLayoutCache = new WeakMap();
  47403. }
  47404. /**
  47405. * Creates a GPU bind group layout for the given bind group.
  47406. *
  47407. * @param {BindGroup} bindGroup - The bind group.
  47408. * @return {GPUBindGroupLayout} The GPU bind group layout.
  47409. */
  47410. createBindingsLayout( bindGroup ) {
  47411. const backend = this.backend;
  47412. const device = backend.device;
  47413. const entries = [];
  47414. let index = 0;
  47415. for ( const binding of bindGroup.bindings ) {
  47416. const bindingGPU = {
  47417. binding: index ++,
  47418. visibility: binding.visibility
  47419. };
  47420. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  47421. const buffer = {}; // GPUBufferBindingLayout
  47422. if ( binding.isStorageBuffer ) {
  47423. if ( binding.visibility & 4 ) {
  47424. // compute
  47425. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  47426. buffer.type = GPUBufferBindingType.Storage;
  47427. } else {
  47428. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  47429. }
  47430. } else {
  47431. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  47432. }
  47433. }
  47434. bindingGPU.buffer = buffer;
  47435. } else if ( binding.isSampler ) {
  47436. const sampler = {}; // GPUSamplerBindingLayout
  47437. if ( binding.texture.isDepthTexture ) {
  47438. if ( binding.texture.compareFunction !== null ) {
  47439. sampler.type = 'comparison';
  47440. }
  47441. }
  47442. bindingGPU.sampler = sampler;
  47443. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  47444. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  47445. } else if ( binding.isSampledTexture && binding.store ) {
  47446. const storageTexture = {}; // GPUStorageTextureBindingLayout
  47447. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  47448. const access = binding.access;
  47449. if ( access === NodeAccess.READ_WRITE ) {
  47450. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  47451. } else if ( access === NodeAccess.WRITE_ONLY ) {
  47452. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  47453. } else {
  47454. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  47455. }
  47456. bindingGPU.storageTexture = storageTexture;
  47457. } else if ( binding.isSampledTexture ) {
  47458. const texture = {}; // GPUTextureBindingLayout
  47459. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  47460. if ( primarySamples > 1 ) {
  47461. texture.multisampled = true;
  47462. if ( ! binding.texture.isDepthTexture ) {
  47463. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  47464. }
  47465. }
  47466. if ( binding.texture.isDepthTexture ) {
  47467. texture.sampleType = GPUTextureSampleType.Depth;
  47468. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  47469. const type = binding.texture.type;
  47470. if ( type === IntType ) {
  47471. texture.sampleType = GPUTextureSampleType.SInt;
  47472. } else if ( type === UnsignedIntType ) {
  47473. texture.sampleType = GPUTextureSampleType.UInt;
  47474. } else if ( type === FloatType ) {
  47475. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  47476. texture.sampleType = GPUTextureSampleType.Float;
  47477. } else {
  47478. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  47479. }
  47480. }
  47481. }
  47482. if ( binding.isSampledCubeTexture ) {
  47483. texture.viewDimension = GPUTextureViewDimension.Cube;
  47484. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  47485. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  47486. } else if ( binding.isSampledTexture3D ) {
  47487. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  47488. }
  47489. bindingGPU.texture = texture;
  47490. } else {
  47491. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  47492. }
  47493. entries.push( bindingGPU );
  47494. }
  47495. return device.createBindGroupLayout( { entries } );
  47496. }
  47497. /**
  47498. * Creates bindings from the given bind group definition.
  47499. *
  47500. * @param {BindGroup} bindGroup - The bind group.
  47501. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47502. * @param {number} cacheIndex - The cache index.
  47503. * @param {number} version - The version.
  47504. */
  47505. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  47506. const { backend, bindGroupLayoutCache } = this;
  47507. const bindingsData = backend.get( bindGroup );
  47508. // setup (static) binding layout and (dynamic) binding group
  47509. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  47510. if ( bindLayoutGPU === undefined ) {
  47511. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  47512. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  47513. }
  47514. let bindGroupGPU;
  47515. if ( cacheIndex > 0 ) {
  47516. if ( bindingsData.groups === undefined ) {
  47517. bindingsData.groups = [];
  47518. bindingsData.versions = [];
  47519. }
  47520. if ( bindingsData.versions[ cacheIndex ] === version ) {
  47521. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  47522. }
  47523. }
  47524. if ( bindGroupGPU === undefined ) {
  47525. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  47526. if ( cacheIndex > 0 ) {
  47527. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  47528. bindingsData.versions[ cacheIndex ] = version;
  47529. }
  47530. }
  47531. bindingsData.group = bindGroupGPU;
  47532. bindingsData.layout = bindLayoutGPU;
  47533. }
  47534. /**
  47535. * Updates a buffer binding.
  47536. *
  47537. * @param {Buffer} binding - The buffer binding to update.
  47538. */
  47539. updateBinding( binding ) {
  47540. const backend = this.backend;
  47541. const device = backend.device;
  47542. const buffer = binding.buffer;
  47543. const bufferGPU = backend.get( binding ).buffer;
  47544. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  47545. }
  47546. /**
  47547. * Creates a GPU bind group for the camera index.
  47548. *
  47549. * @param {Uint32Array} data - The index data.
  47550. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  47551. * @return {GPUBindGroup} The GPU bind group.
  47552. */
  47553. createBindGroupIndex( data, layout ) {
  47554. const backend = this.backend;
  47555. const device = backend.device;
  47556. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  47557. const index = data[ 0 ];
  47558. const buffer = device.createBuffer( {
  47559. label: 'bindingCameraIndex_' + index,
  47560. size: 16, // uint(4) * 4
  47561. usage: usage
  47562. } );
  47563. device.queue.writeBuffer( buffer, 0, data, 0 );
  47564. const entries = [ { binding: 0, resource: { buffer } } ];
  47565. return device.createBindGroup( {
  47566. label: 'bindGroupCameraIndex_' + index,
  47567. layout,
  47568. entries
  47569. } );
  47570. }
  47571. /**
  47572. * Creates a GPU bind group for the given bind group and GPU layout.
  47573. *
  47574. * @param {BindGroup} bindGroup - The bind group.
  47575. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  47576. * @return {GPUBindGroup} The GPU bind group.
  47577. */
  47578. createBindGroup( bindGroup, layoutGPU ) {
  47579. const backend = this.backend;
  47580. const device = backend.device;
  47581. let bindingPoint = 0;
  47582. const entriesGPU = [];
  47583. for ( const binding of bindGroup.bindings ) {
  47584. if ( binding.isUniformBuffer ) {
  47585. const bindingData = backend.get( binding );
  47586. if ( bindingData.buffer === undefined ) {
  47587. const byteLength = binding.byteLength;
  47588. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  47589. const bufferGPU = device.createBuffer( {
  47590. label: 'bindingBuffer_' + binding.name,
  47591. size: byteLength,
  47592. usage: usage
  47593. } );
  47594. bindingData.buffer = bufferGPU;
  47595. }
  47596. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  47597. } else if ( binding.isStorageBuffer ) {
  47598. const bindingData = backend.get( binding );
  47599. if ( bindingData.buffer === undefined ) {
  47600. const attribute = binding.attribute;
  47601. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  47602. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  47603. bindingData.buffer = backend.get( attribute ).buffer;
  47604. }
  47605. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  47606. } else if ( binding.isSampler ) {
  47607. const textureGPU = backend.get( binding.texture );
  47608. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  47609. } else if ( binding.isSampledTexture ) {
  47610. const textureData = backend.get( binding.texture );
  47611. let resourceGPU;
  47612. if ( textureData.externalTexture !== undefined ) {
  47613. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  47614. } else {
  47615. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  47616. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  47617. resourceGPU = textureData[ propertyName ];
  47618. if ( resourceGPU === undefined ) {
  47619. const aspectGPU = GPUTextureAspect.All;
  47620. let dimensionViewGPU;
  47621. if ( binding.isSampledCubeTexture ) {
  47622. dimensionViewGPU = GPUTextureViewDimension.Cube;
  47623. } else if ( binding.isSampledTexture3D ) {
  47624. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  47625. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  47626. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  47627. } else {
  47628. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  47629. }
  47630. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  47631. }
  47632. }
  47633. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  47634. }
  47635. bindingPoint ++;
  47636. }
  47637. return device.createBindGroup( {
  47638. label: 'bindGroup_' + bindGroup.name,
  47639. layout: layoutGPU,
  47640. entries: entriesGPU
  47641. } );
  47642. }
  47643. }
  47644. /**
  47645. * A WebGPU backend utility module for managing pipelines.
  47646. *
  47647. * @private
  47648. */
  47649. class WebGPUPipelineUtils {
  47650. /**
  47651. * Constructs a new utility object.
  47652. *
  47653. * @param {WebGPUBackend} backend - The WebGPU backend.
  47654. */
  47655. constructor( backend ) {
  47656. /**
  47657. * A reference to the WebGPU backend.
  47658. *
  47659. * @type {WebGPUBackend}
  47660. */
  47661. this.backend = backend;
  47662. }
  47663. /**
  47664. * Returns the sample count derived from the given render context.
  47665. *
  47666. * @private
  47667. * @param {RenderContext} renderContext - The render context.
  47668. * @return {number} The sample count.
  47669. */
  47670. _getSampleCount( renderContext ) {
  47671. return this.backend.utils.getSampleCountRenderContext( renderContext );
  47672. }
  47673. /**
  47674. * Creates a render pipeline for the given render object.
  47675. *
  47676. * @param {RenderObject} renderObject - The render object.
  47677. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47678. */
  47679. createRenderPipeline( renderObject, promises ) {
  47680. const { object, material, geometry, pipeline } = renderObject;
  47681. const { vertexProgram, fragmentProgram } = pipeline;
  47682. const backend = this.backend;
  47683. const device = backend.device;
  47684. const utils = backend.utils;
  47685. const pipelineData = backend.get( pipeline );
  47686. // bind group layouts
  47687. const bindGroupLayouts = [];
  47688. for ( const bindGroup of renderObject.getBindings() ) {
  47689. const bindingsData = backend.get( bindGroup );
  47690. bindGroupLayouts.push( bindingsData.layout );
  47691. }
  47692. // vertex buffers
  47693. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  47694. // blending
  47695. let blending;
  47696. if ( material.transparent === true && material.blending !== NoBlending ) {
  47697. blending = this._getBlending( material );
  47698. }
  47699. // stencil
  47700. let stencilFront = {};
  47701. if ( material.stencilWrite === true ) {
  47702. stencilFront = {
  47703. compare: this._getStencilCompare( material ),
  47704. failOp: this._getStencilOperation( material.stencilFail ),
  47705. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  47706. passOp: this._getStencilOperation( material.stencilZPass )
  47707. };
  47708. }
  47709. const colorWriteMask = this._getColorWriteMask( material );
  47710. const targets = [];
  47711. if ( renderObject.context.textures !== null ) {
  47712. const textures = renderObject.context.textures;
  47713. for ( let i = 0; i < textures.length; i ++ ) {
  47714. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  47715. targets.push( {
  47716. format: colorFormat,
  47717. blend: blending,
  47718. writeMask: colorWriteMask
  47719. } );
  47720. }
  47721. } else {
  47722. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  47723. targets.push( {
  47724. format: colorFormat,
  47725. blend: blending,
  47726. writeMask: colorWriteMask
  47727. } );
  47728. }
  47729. const vertexModule = backend.get( vertexProgram ).module;
  47730. const fragmentModule = backend.get( fragmentProgram ).module;
  47731. const primitiveState = this._getPrimitiveState( object, geometry, material );
  47732. const depthCompare = this._getDepthCompare( material );
  47733. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  47734. const sampleCount = this._getSampleCount( renderObject.context );
  47735. const pipelineDescriptor = {
  47736. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  47737. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  47738. fragment: Object.assign( {}, fragmentModule, { targets } ),
  47739. primitive: primitiveState,
  47740. multisample: {
  47741. count: sampleCount,
  47742. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  47743. },
  47744. layout: device.createPipelineLayout( {
  47745. bindGroupLayouts
  47746. } )
  47747. };
  47748. const depthStencil = {};
  47749. const renderDepth = renderObject.context.depth;
  47750. const renderStencil = renderObject.context.stencil;
  47751. if ( renderDepth === true || renderStencil === true ) {
  47752. if ( renderDepth === true ) {
  47753. depthStencil.format = depthStencilFormat;
  47754. depthStencil.depthWriteEnabled = material.depthWrite;
  47755. depthStencil.depthCompare = depthCompare;
  47756. }
  47757. if ( renderStencil === true ) {
  47758. depthStencil.stencilFront = stencilFront;
  47759. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  47760. depthStencil.stencilReadMask = material.stencilFuncMask;
  47761. depthStencil.stencilWriteMask = material.stencilWriteMask;
  47762. }
  47763. if ( material.polygonOffset === true ) {
  47764. depthStencil.depthBias = material.polygonOffsetUnits;
  47765. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  47766. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  47767. }
  47768. pipelineDescriptor.depthStencil = depthStencil;
  47769. }
  47770. if ( promises === null ) {
  47771. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  47772. } else {
  47773. const p = new Promise( ( resolve /*, reject*/ ) => {
  47774. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  47775. pipelineData.pipeline = pipeline;
  47776. resolve();
  47777. } );
  47778. } );
  47779. promises.push( p );
  47780. }
  47781. }
  47782. /**
  47783. * Creates GPU render bundle encoder for the given render context.
  47784. *
  47785. * @param {RenderContext} renderContext - The render context.
  47786. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  47787. */
  47788. createBundleEncoder( renderContext ) {
  47789. const backend = this.backend;
  47790. const { utils, device } = backend;
  47791. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  47792. const colorFormat = utils.getCurrentColorFormat( renderContext );
  47793. const sampleCount = this._getSampleCount( renderContext );
  47794. const descriptor = {
  47795. label: 'renderBundleEncoder',
  47796. colorFormats: [ colorFormat ],
  47797. depthStencilFormat,
  47798. sampleCount
  47799. };
  47800. return device.createRenderBundleEncoder( descriptor );
  47801. }
  47802. /**
  47803. * Creates a compute pipeline for the given compute node.
  47804. *
  47805. * @param {ComputePipeline} pipeline - The compute pipeline.
  47806. * @param {Array<BindGroup>} bindings - The bindings.
  47807. */
  47808. createComputePipeline( pipeline, bindings ) {
  47809. const backend = this.backend;
  47810. const device = backend.device;
  47811. const computeProgram = backend.get( pipeline.computeProgram ).module;
  47812. const pipelineGPU = backend.get( pipeline );
  47813. // bind group layouts
  47814. const bindGroupLayouts = [];
  47815. for ( const bindingsGroup of bindings ) {
  47816. const bindingsData = backend.get( bindingsGroup );
  47817. bindGroupLayouts.push( bindingsData.layout );
  47818. }
  47819. pipelineGPU.pipeline = device.createComputePipeline( {
  47820. compute: computeProgram,
  47821. layout: device.createPipelineLayout( {
  47822. bindGroupLayouts
  47823. } )
  47824. } );
  47825. }
  47826. /**
  47827. * Returns the blending state as a descriptor object required
  47828. * for the pipeline creation.
  47829. *
  47830. * @private
  47831. * @param {Material} material - The material.
  47832. * @return {Object} The blending state.
  47833. */
  47834. _getBlending( material ) {
  47835. let color, alpha;
  47836. const blending = material.blending;
  47837. const blendSrc = material.blendSrc;
  47838. const blendDst = material.blendDst;
  47839. const blendEquation = material.blendEquation;
  47840. if ( blending === CustomBlending ) {
  47841. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  47842. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  47843. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  47844. color = {
  47845. srcFactor: this._getBlendFactor( blendSrc ),
  47846. dstFactor: this._getBlendFactor( blendDst ),
  47847. operation: this._getBlendOperation( blendEquation )
  47848. };
  47849. alpha = {
  47850. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  47851. dstFactor: this._getBlendFactor( blendDstAlpha ),
  47852. operation: this._getBlendOperation( blendEquationAlpha )
  47853. };
  47854. } else {
  47855. const premultipliedAlpha = material.premultipliedAlpha;
  47856. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  47857. color = {
  47858. srcFactor: srcRGB,
  47859. dstFactor: dstRGB,
  47860. operation: GPUBlendOperation.Add
  47861. };
  47862. alpha = {
  47863. srcFactor: srcAlpha,
  47864. dstFactor: dstAlpha,
  47865. operation: GPUBlendOperation.Add
  47866. };
  47867. };
  47868. if ( premultipliedAlpha ) {
  47869. switch ( blending ) {
  47870. case NormalBlending:
  47871. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47872. break;
  47873. case AdditiveBlending:
  47874. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  47875. break;
  47876. case SubtractiveBlending:
  47877. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47878. break;
  47879. case MultiplyBlending:
  47880. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  47881. break;
  47882. }
  47883. } else {
  47884. switch ( blending ) {
  47885. case NormalBlending:
  47886. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47887. break;
  47888. case AdditiveBlending:
  47889. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  47890. break;
  47891. case SubtractiveBlending:
  47892. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47893. break;
  47894. case MultiplyBlending:
  47895. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  47896. break;
  47897. }
  47898. }
  47899. }
  47900. if ( color !== undefined && alpha !== undefined ) {
  47901. return { color, alpha };
  47902. } else {
  47903. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  47904. }
  47905. }
  47906. /**
  47907. * Returns the GPU blend factor which is required for the pipeline creation.
  47908. *
  47909. * @private
  47910. * @param {number} blend - The blend factor as a three.js constant.
  47911. * @return {string} The GPU blend factor.
  47912. */
  47913. _getBlendFactor( blend ) {
  47914. let blendFactor;
  47915. switch ( blend ) {
  47916. case ZeroFactor:
  47917. blendFactor = GPUBlendFactor.Zero;
  47918. break;
  47919. case OneFactor:
  47920. blendFactor = GPUBlendFactor.One;
  47921. break;
  47922. case SrcColorFactor:
  47923. blendFactor = GPUBlendFactor.Src;
  47924. break;
  47925. case OneMinusSrcColorFactor:
  47926. blendFactor = GPUBlendFactor.OneMinusSrc;
  47927. break;
  47928. case SrcAlphaFactor:
  47929. blendFactor = GPUBlendFactor.SrcAlpha;
  47930. break;
  47931. case OneMinusSrcAlphaFactor:
  47932. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  47933. break;
  47934. case DstColorFactor:
  47935. blendFactor = GPUBlendFactor.Dst;
  47936. break;
  47937. case OneMinusDstColorFactor:
  47938. blendFactor = GPUBlendFactor.OneMinusDstColor;
  47939. break;
  47940. case DstAlphaFactor:
  47941. blendFactor = GPUBlendFactor.DstAlpha;
  47942. break;
  47943. case OneMinusDstAlphaFactor:
  47944. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  47945. break;
  47946. case SrcAlphaSaturateFactor:
  47947. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  47948. break;
  47949. case BlendColorFactor:
  47950. blendFactor = GPUBlendFactor.Constant;
  47951. break;
  47952. case OneMinusBlendColorFactor:
  47953. blendFactor = GPUBlendFactor.OneMinusConstant;
  47954. break;
  47955. default:
  47956. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  47957. }
  47958. return blendFactor;
  47959. }
  47960. /**
  47961. * Returns the GPU stencil compare function which is required for the pipeline creation.
  47962. *
  47963. * @private
  47964. * @param {Material} material - The material.
  47965. * @return {string} The GPU stencil compare function.
  47966. */
  47967. _getStencilCompare( material ) {
  47968. let stencilCompare;
  47969. const stencilFunc = material.stencilFunc;
  47970. switch ( stencilFunc ) {
  47971. case NeverStencilFunc:
  47972. stencilCompare = GPUCompareFunction.Never;
  47973. break;
  47974. case AlwaysStencilFunc:
  47975. stencilCompare = GPUCompareFunction.Always;
  47976. break;
  47977. case LessStencilFunc:
  47978. stencilCompare = GPUCompareFunction.Less;
  47979. break;
  47980. case LessEqualStencilFunc:
  47981. stencilCompare = GPUCompareFunction.LessEqual;
  47982. break;
  47983. case EqualStencilFunc:
  47984. stencilCompare = GPUCompareFunction.Equal;
  47985. break;
  47986. case GreaterEqualStencilFunc:
  47987. stencilCompare = GPUCompareFunction.GreaterEqual;
  47988. break;
  47989. case GreaterStencilFunc:
  47990. stencilCompare = GPUCompareFunction.Greater;
  47991. break;
  47992. case NotEqualStencilFunc:
  47993. stencilCompare = GPUCompareFunction.NotEqual;
  47994. break;
  47995. default:
  47996. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  47997. }
  47998. return stencilCompare;
  47999. }
  48000. /**
  48001. * Returns the GPU stencil operation which is required for the pipeline creation.
  48002. *
  48003. * @private
  48004. * @param {number} op - A three.js constant defining the stencil operation.
  48005. * @return {string} The GPU stencil operation.
  48006. */
  48007. _getStencilOperation( op ) {
  48008. let stencilOperation;
  48009. switch ( op ) {
  48010. case KeepStencilOp:
  48011. stencilOperation = GPUStencilOperation.Keep;
  48012. break;
  48013. case ZeroStencilOp:
  48014. stencilOperation = GPUStencilOperation.Zero;
  48015. break;
  48016. case ReplaceStencilOp:
  48017. stencilOperation = GPUStencilOperation.Replace;
  48018. break;
  48019. case InvertStencilOp:
  48020. stencilOperation = GPUStencilOperation.Invert;
  48021. break;
  48022. case IncrementStencilOp:
  48023. stencilOperation = GPUStencilOperation.IncrementClamp;
  48024. break;
  48025. case DecrementStencilOp:
  48026. stencilOperation = GPUStencilOperation.DecrementClamp;
  48027. break;
  48028. case IncrementWrapStencilOp:
  48029. stencilOperation = GPUStencilOperation.IncrementWrap;
  48030. break;
  48031. case DecrementWrapStencilOp:
  48032. stencilOperation = GPUStencilOperation.DecrementWrap;
  48033. break;
  48034. default:
  48035. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  48036. }
  48037. return stencilOperation;
  48038. }
  48039. /**
  48040. * Returns the GPU blend operation which is required for the pipeline creation.
  48041. *
  48042. * @private
  48043. * @param {number} blendEquation - A three.js constant defining the blend equation.
  48044. * @return {string} The GPU blend operation.
  48045. */
  48046. _getBlendOperation( blendEquation ) {
  48047. let blendOperation;
  48048. switch ( blendEquation ) {
  48049. case AddEquation:
  48050. blendOperation = GPUBlendOperation.Add;
  48051. break;
  48052. case SubtractEquation:
  48053. blendOperation = GPUBlendOperation.Subtract;
  48054. break;
  48055. case ReverseSubtractEquation:
  48056. blendOperation = GPUBlendOperation.ReverseSubtract;
  48057. break;
  48058. case MinEquation:
  48059. blendOperation = GPUBlendOperation.Min;
  48060. break;
  48061. case MaxEquation:
  48062. blendOperation = GPUBlendOperation.Max;
  48063. break;
  48064. default:
  48065. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  48066. }
  48067. return blendOperation;
  48068. }
  48069. /**
  48070. * Returns the primitive state as a descriptor object required
  48071. * for the pipeline creation.
  48072. *
  48073. * @private
  48074. * @param {Object3D} object - The 3D object.
  48075. * @param {BufferGeometry} geometry - The geometry.
  48076. * @param {Material} material - The material.
  48077. * @return {Object} The primitive state.
  48078. */
  48079. _getPrimitiveState( object, geometry, material ) {
  48080. const descriptor = {};
  48081. const utils = this.backend.utils;
  48082. descriptor.topology = utils.getPrimitiveTopology( object, material );
  48083. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  48084. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  48085. }
  48086. switch ( material.side ) {
  48087. case FrontSide:
  48088. descriptor.frontFace = GPUFrontFace.CCW;
  48089. descriptor.cullMode = GPUCullMode.Back;
  48090. break;
  48091. case BackSide:
  48092. descriptor.frontFace = GPUFrontFace.CCW;
  48093. descriptor.cullMode = GPUCullMode.Front;
  48094. break;
  48095. case DoubleSide:
  48096. descriptor.frontFace = GPUFrontFace.CCW;
  48097. descriptor.cullMode = GPUCullMode.None;
  48098. break;
  48099. default:
  48100. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  48101. break;
  48102. }
  48103. return descriptor;
  48104. }
  48105. /**
  48106. * Returns the GPU color write mask which is required for the pipeline creation.
  48107. *
  48108. * @private
  48109. * @param {Material} material - The material.
  48110. * @return {string} The GPU color write mask.
  48111. */
  48112. _getColorWriteMask( material ) {
  48113. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  48114. }
  48115. /**
  48116. * Returns the GPU depth compare function which is required for the pipeline creation.
  48117. *
  48118. * @private
  48119. * @param {Material} material - The material.
  48120. * @return {string} The GPU depth compare function.
  48121. */
  48122. _getDepthCompare( material ) {
  48123. let depthCompare;
  48124. if ( material.depthTest === false ) {
  48125. depthCompare = GPUCompareFunction.Always;
  48126. } else {
  48127. const depthFunc = material.depthFunc;
  48128. switch ( depthFunc ) {
  48129. case NeverDepth:
  48130. depthCompare = GPUCompareFunction.Never;
  48131. break;
  48132. case AlwaysDepth:
  48133. depthCompare = GPUCompareFunction.Always;
  48134. break;
  48135. case LessDepth:
  48136. depthCompare = GPUCompareFunction.Less;
  48137. break;
  48138. case LessEqualDepth:
  48139. depthCompare = GPUCompareFunction.LessEqual;
  48140. break;
  48141. case EqualDepth:
  48142. depthCompare = GPUCompareFunction.Equal;
  48143. break;
  48144. case GreaterEqualDepth:
  48145. depthCompare = GPUCompareFunction.GreaterEqual;
  48146. break;
  48147. case GreaterDepth:
  48148. depthCompare = GPUCompareFunction.Greater;
  48149. break;
  48150. case NotEqualDepth:
  48151. depthCompare = GPUCompareFunction.NotEqual;
  48152. break;
  48153. default:
  48154. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  48155. }
  48156. }
  48157. return depthCompare;
  48158. }
  48159. }
  48160. /**
  48161. * Manages a pool of WebGPU timestamp queries for performance measurement.
  48162. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  48163. *
  48164. * @augments TimestampQueryPool
  48165. */
  48166. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  48167. /**
  48168. * Creates a new WebGPU timestamp query pool.
  48169. *
  48170. * @param {GPUDevice} device - The WebGPU device to create queries on.
  48171. * @param {string} type - The type identifier for this query pool.
  48172. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48173. */
  48174. constructor( device, type, maxQueries = 2048 ) {
  48175. super( maxQueries );
  48176. this.device = device;
  48177. this.type = type;
  48178. this.querySet = this.device.createQuerySet( {
  48179. type: 'timestamp',
  48180. count: this.maxQueries,
  48181. label: `queryset_global_timestamp_${type}`
  48182. } );
  48183. const bufferSize = this.maxQueries * 8;
  48184. this.resolveBuffer = this.device.createBuffer( {
  48185. label: `buffer_timestamp_resolve_${type}`,
  48186. size: bufferSize,
  48187. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  48188. } );
  48189. this.resultBuffer = this.device.createBuffer( {
  48190. label: `buffer_timestamp_result_${type}`,
  48191. size: bufferSize,
  48192. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48193. } );
  48194. }
  48195. /**
  48196. * Allocates a pair of queries for a given render context.
  48197. *
  48198. * @param {Object} renderContext - The render context to allocate queries for.
  48199. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48200. */
  48201. allocateQueriesForContext( renderContext ) {
  48202. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  48203. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48204. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  48205. return null;
  48206. }
  48207. const baseOffset = this.currentQueryIndex;
  48208. this.currentQueryIndex += 2;
  48209. this.queryOffsets.set( renderContext.id, baseOffset );
  48210. return baseOffset;
  48211. }
  48212. /**
  48213. * Asynchronously resolves all pending queries and returns the total duration.
  48214. * If there's already a pending resolve operation, returns that promise instead.
  48215. *
  48216. * @async
  48217. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48218. */
  48219. async resolveQueriesAsync() {
  48220. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  48221. return this.lastValue;
  48222. }
  48223. if ( this.pendingResolve ) {
  48224. return this.pendingResolve;
  48225. }
  48226. this.pendingResolve = this._resolveQueries();
  48227. try {
  48228. const result = await this.pendingResolve;
  48229. return result;
  48230. } finally {
  48231. this.pendingResolve = null;
  48232. }
  48233. }
  48234. /**
  48235. * Internal method to resolve queries and calculate total duration.
  48236. *
  48237. * @async
  48238. * @private
  48239. * @returns {Promise<number>} The total duration in milliseconds.
  48240. */
  48241. async _resolveQueries() {
  48242. if ( this.isDisposed ) {
  48243. return this.lastValue;
  48244. }
  48245. try {
  48246. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  48247. return this.lastValue;
  48248. }
  48249. const currentOffsets = new Map( this.queryOffsets );
  48250. const queryCount = this.currentQueryIndex;
  48251. const bytesUsed = queryCount * 8;
  48252. // Reset state before GPU work
  48253. this.currentQueryIndex = 0;
  48254. this.queryOffsets.clear();
  48255. const commandEncoder = this.device.createCommandEncoder();
  48256. commandEncoder.resolveQuerySet(
  48257. this.querySet,
  48258. 0,
  48259. queryCount,
  48260. this.resolveBuffer,
  48261. 0
  48262. );
  48263. commandEncoder.copyBufferToBuffer(
  48264. this.resolveBuffer,
  48265. 0,
  48266. this.resultBuffer,
  48267. 0,
  48268. bytesUsed
  48269. );
  48270. const commandBuffer = commandEncoder.finish();
  48271. this.device.queue.submit( [ commandBuffer ] );
  48272. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  48273. return this.lastValue;
  48274. }
  48275. // Create and track the mapping operation
  48276. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  48277. if ( this.isDisposed ) {
  48278. if ( this.resultBuffer.mapState === 'mapped' ) {
  48279. this.resultBuffer.unmap();
  48280. }
  48281. return this.lastValue;
  48282. }
  48283. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  48284. let totalDuration = 0;
  48285. for ( const [ , baseOffset ] of currentOffsets ) {
  48286. const startTime = times[ baseOffset ];
  48287. const endTime = times[ baseOffset + 1 ];
  48288. const duration = Number( endTime - startTime ) / 1e6;
  48289. totalDuration += duration;
  48290. }
  48291. this.resultBuffer.unmap();
  48292. this.lastValue = totalDuration;
  48293. return totalDuration;
  48294. } catch ( error ) {
  48295. console.error( 'Error resolving queries:', error );
  48296. if ( this.resultBuffer.mapState === 'mapped' ) {
  48297. this.resultBuffer.unmap();
  48298. }
  48299. return this.lastValue;
  48300. }
  48301. }
  48302. /**
  48303. * Dispose of the query pool.
  48304. *
  48305. * @async
  48306. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  48307. */
  48308. async dispose() {
  48309. if ( this.isDisposed ) {
  48310. return;
  48311. }
  48312. this.isDisposed = true;
  48313. // Wait for pending resolve operation
  48314. if ( this.pendingResolve ) {
  48315. try {
  48316. await this.pendingResolve;
  48317. } catch ( error ) {
  48318. console.error( 'Error waiting for pending resolve:', error );
  48319. }
  48320. }
  48321. // Ensure buffer is unmapped before destroying
  48322. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  48323. try {
  48324. this.resultBuffer.unmap();
  48325. } catch ( error ) {
  48326. console.error( 'Error unmapping buffer:', error );
  48327. }
  48328. }
  48329. // Destroy resources
  48330. if ( this.querySet ) {
  48331. this.querySet.destroy();
  48332. this.querySet = null;
  48333. }
  48334. if ( this.resolveBuffer ) {
  48335. this.resolveBuffer.destroy();
  48336. this.resolveBuffer = null;
  48337. }
  48338. if ( this.resultBuffer ) {
  48339. this.resultBuffer.destroy();
  48340. this.resultBuffer = null;
  48341. }
  48342. this.queryOffsets.clear();
  48343. this.pendingResolve = null;
  48344. }
  48345. }
  48346. /*// debugger tools
  48347. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  48348. //*/
  48349. /**
  48350. * A backend implementation targeting WebGPU.
  48351. *
  48352. * @private
  48353. * @augments Backend
  48354. */
  48355. class WebGPUBackend extends Backend {
  48356. /**
  48357. * WebGPUBackend options.
  48358. *
  48359. * @typedef {Object} WebGPUBackend~Options
  48360. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48361. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48362. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48363. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48364. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48365. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  48366. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48367. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  48368. * @property {string} [powerPreference=undefined] - The power preference.
  48369. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  48370. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  48371. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  48372. */
  48373. /**
  48374. * Constructs a new WebGPU backend.
  48375. *
  48376. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  48377. */
  48378. constructor( parameters = {} ) {
  48379. super( parameters );
  48380. /**
  48381. * This flag can be used for type testing.
  48382. *
  48383. * @type {boolean}
  48384. * @readonly
  48385. * @default true
  48386. */
  48387. this.isWebGPUBackend = true;
  48388. // some parameters require default values other than "undefined"
  48389. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  48390. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  48391. /**
  48392. * A reference to the device.
  48393. *
  48394. * @type {?GPUDevice}
  48395. * @default null
  48396. */
  48397. this.device = null;
  48398. /**
  48399. * A reference to the context.
  48400. *
  48401. * @type {?GPUCanvasContext}
  48402. * @default null
  48403. */
  48404. this.context = null;
  48405. /**
  48406. * A reference to the color attachment of the default framebuffer.
  48407. *
  48408. * @type {?GPUTexture}
  48409. * @default null
  48410. */
  48411. this.colorBuffer = null;
  48412. /**
  48413. * A reference to the default render pass descriptor.
  48414. *
  48415. * @type {?Object}
  48416. * @default null
  48417. */
  48418. this.defaultRenderPassdescriptor = null;
  48419. /**
  48420. * A reference to a backend module holding common utility functions.
  48421. *
  48422. * @type {WebGPUUtils}
  48423. */
  48424. this.utils = new WebGPUUtils( this );
  48425. /**
  48426. * A reference to a backend module holding shader attribute-related
  48427. * utility functions.
  48428. *
  48429. * @type {WebGPUAttributeUtils}
  48430. */
  48431. this.attributeUtils = new WebGPUAttributeUtils( this );
  48432. /**
  48433. * A reference to a backend module holding shader binding-related
  48434. * utility functions.
  48435. *
  48436. * @type {WebGPUBindingUtils}
  48437. */
  48438. this.bindingUtils = new WebGPUBindingUtils( this );
  48439. /**
  48440. * A reference to a backend module holding shader pipeline-related
  48441. * utility functions.
  48442. *
  48443. * @type {WebGPUPipelineUtils}
  48444. */
  48445. this.pipelineUtils = new WebGPUPipelineUtils( this );
  48446. /**
  48447. * A reference to a backend module holding shader texture-related
  48448. * utility functions.
  48449. *
  48450. * @type {WebGPUTextureUtils}
  48451. */
  48452. this.textureUtils = new WebGPUTextureUtils( this );
  48453. /**
  48454. * A map that manages the resolve buffers for occlusion queries.
  48455. *
  48456. * @type {Map<number,GPUBuffer>}
  48457. */
  48458. this.occludedResolveCache = new Map();
  48459. }
  48460. /**
  48461. * Initializes the backend so it is ready for usage.
  48462. *
  48463. * @async
  48464. * @param {Renderer} renderer - The renderer.
  48465. * @return {Promise} A Promise that resolves when the backend has been initialized.
  48466. */
  48467. async init( renderer ) {
  48468. await super.init( renderer );
  48469. //
  48470. const parameters = this.parameters;
  48471. // create the device if it is not passed with parameters
  48472. let device;
  48473. if ( parameters.device === undefined ) {
  48474. const adapterOptions = {
  48475. powerPreference: parameters.powerPreference
  48476. };
  48477. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  48478. if ( adapter === null ) {
  48479. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  48480. }
  48481. // feature support
  48482. const features = Object.values( GPUFeatureName );
  48483. const supportedFeatures = [];
  48484. for ( const name of features ) {
  48485. if ( adapter.features.has( name ) ) {
  48486. supportedFeatures.push( name );
  48487. }
  48488. }
  48489. const deviceDescriptor = {
  48490. requiredFeatures: supportedFeatures,
  48491. requiredLimits: parameters.requiredLimits
  48492. };
  48493. device = await adapter.requestDevice( deviceDescriptor );
  48494. } else {
  48495. device = parameters.device;
  48496. }
  48497. device.lost.then( ( info ) => {
  48498. const deviceLossInfo = {
  48499. api: 'WebGPU',
  48500. message: info.message || 'Unknown reason',
  48501. reason: info.reason || null,
  48502. originalEvent: info
  48503. };
  48504. renderer.onDeviceLost( deviceLossInfo );
  48505. } );
  48506. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  48507. this.device = device;
  48508. this.context = context;
  48509. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  48510. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  48511. this.context.configure( {
  48512. device: this.device,
  48513. format: this.utils.getPreferredCanvasFormat(),
  48514. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  48515. alphaMode: alphaMode
  48516. } );
  48517. this.updateSize();
  48518. }
  48519. /**
  48520. * The coordinate system of the backend.
  48521. *
  48522. * @type {number}
  48523. * @readonly
  48524. */
  48525. get coordinateSystem() {
  48526. return WebGPUCoordinateSystem;
  48527. }
  48528. /**
  48529. * This method performs a readback operation by moving buffer data from
  48530. * a storage buffer attribute from the GPU to the CPU.
  48531. *
  48532. * @async
  48533. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48534. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48535. */
  48536. async getArrayBufferAsync( attribute ) {
  48537. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48538. }
  48539. /**
  48540. * Returns the backend's rendering context.
  48541. *
  48542. * @return {GPUCanvasContext} The rendering context.
  48543. */
  48544. getContext() {
  48545. return this.context;
  48546. }
  48547. /**
  48548. * Returns the default render pass descriptor.
  48549. *
  48550. * In WebGPU, the default framebuffer must be configured
  48551. * like custom framebuffers so the backend needs a render
  48552. * pass descriptor even when rendering directly to screen.
  48553. *
  48554. * @private
  48555. * @return {Object} The render pass descriptor.
  48556. */
  48557. _getDefaultRenderPassDescriptor() {
  48558. let descriptor = this.defaultRenderPassdescriptor;
  48559. if ( descriptor === null ) {
  48560. const renderer = this.renderer;
  48561. descriptor = {
  48562. colorAttachments: [ {
  48563. view: null
  48564. } ],
  48565. };
  48566. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  48567. descriptor.depthStencilAttachment = {
  48568. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  48569. };
  48570. }
  48571. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48572. if ( this.renderer.samples > 0 ) {
  48573. colorAttachment.view = this.colorBuffer.createView();
  48574. } else {
  48575. colorAttachment.resolveTarget = undefined;
  48576. }
  48577. this.defaultRenderPassdescriptor = descriptor;
  48578. }
  48579. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48580. if ( this.renderer.samples > 0 ) {
  48581. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  48582. } else {
  48583. colorAttachment.view = this.context.getCurrentTexture().createView();
  48584. }
  48585. return descriptor;
  48586. }
  48587. /**
  48588. * Returns the render pass descriptor for the given render context.
  48589. *
  48590. * @private
  48591. * @param {RenderContext} renderContext - The render context.
  48592. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  48593. * @return {Object} The render pass descriptor.
  48594. */
  48595. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  48596. const renderTarget = renderContext.renderTarget;
  48597. const renderTargetData = this.get( renderTarget );
  48598. let descriptors = renderTargetData.descriptors;
  48599. if ( descriptors === undefined ||
  48600. renderTargetData.width !== renderTarget.width ||
  48601. renderTargetData.height !== renderTarget.height ||
  48602. renderTargetData.dimensions !== renderTarget.dimensions ||
  48603. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  48604. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  48605. renderTargetData.samples !== renderTarget.samples
  48606. ) {
  48607. descriptors = {};
  48608. renderTargetData.descriptors = descriptors;
  48609. // dispose
  48610. const onDispose = () => {
  48611. renderTarget.removeEventListener( 'dispose', onDispose );
  48612. this.delete( renderTarget );
  48613. };
  48614. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  48615. renderTarget.addEventListener( 'dispose', onDispose );
  48616. }
  48617. }
  48618. const cacheKey = renderContext.getCacheKey();
  48619. let descriptorBase = descriptors[ cacheKey ];
  48620. if ( descriptorBase === undefined ) {
  48621. const textures = renderContext.textures;
  48622. const textureViews = [];
  48623. let sliceIndex;
  48624. for ( let i = 0; i < textures.length; i ++ ) {
  48625. const textureData = this.get( textures[ i ] );
  48626. const viewDescriptor = {
  48627. label: `colorAttachment_${ i }`,
  48628. baseMipLevel: renderContext.activeMipmapLevel,
  48629. mipLevelCount: 1,
  48630. baseArrayLayer: renderContext.activeCubeFace,
  48631. arrayLayerCount: 1,
  48632. dimension: GPUTextureViewDimension.TwoD
  48633. };
  48634. if ( renderTarget.isRenderTarget3D ) {
  48635. sliceIndex = renderContext.activeCubeFace;
  48636. viewDescriptor.baseArrayLayer = 0;
  48637. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  48638. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  48639. } else if ( renderTarget.isRenderTargetArray ) {
  48640. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  48641. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  48642. }
  48643. const textureView = textureData.texture.createView( viewDescriptor );
  48644. let view, resolveTarget;
  48645. if ( textureData.msaaTexture !== undefined ) {
  48646. view = textureData.msaaTexture.createView();
  48647. resolveTarget = textureView;
  48648. } else {
  48649. view = textureView;
  48650. resolveTarget = undefined;
  48651. }
  48652. textureViews.push( {
  48653. view,
  48654. resolveTarget,
  48655. depthSlice: sliceIndex
  48656. } );
  48657. }
  48658. descriptorBase = { textureViews };
  48659. if ( renderContext.depth ) {
  48660. const depthTextureData = this.get( renderContext.depthTexture );
  48661. descriptorBase.depthStencilView = depthTextureData.texture.createView();
  48662. }
  48663. descriptors[ cacheKey ] = descriptorBase;
  48664. renderTargetData.width = renderTarget.width;
  48665. renderTargetData.height = renderTarget.height;
  48666. renderTargetData.samples = renderTarget.samples;
  48667. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  48668. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  48669. renderTargetData.dimensions = renderTarget.dimensions;
  48670. }
  48671. const descriptor = {
  48672. colorAttachments: []
  48673. };
  48674. // Apply dynamic properties to cached views
  48675. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  48676. const viewInfo = descriptorBase.textureViews[ i ];
  48677. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  48678. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  48679. clearValue = colorAttachmentsConfig.clearValue;
  48680. }
  48681. descriptor.colorAttachments.push( {
  48682. view: viewInfo.view,
  48683. depthSlice: viewInfo.depthSlice,
  48684. resolveTarget: viewInfo.resolveTarget,
  48685. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  48686. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  48687. clearValue: clearValue
  48688. } );
  48689. }
  48690. if ( descriptorBase.depthStencilView ) {
  48691. descriptor.depthStencilAttachment = {
  48692. view: descriptorBase.depthStencilView
  48693. };
  48694. }
  48695. return descriptor;
  48696. }
  48697. /**
  48698. * This method is executed at the beginning of a render call and prepares
  48699. * the WebGPU state for upcoming render calls
  48700. *
  48701. * @param {RenderContext} renderContext - The render context.
  48702. */
  48703. beginRender( renderContext ) {
  48704. const renderContextData = this.get( renderContext );
  48705. const device = this.device;
  48706. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48707. let occlusionQuerySet;
  48708. if ( occlusionQueryCount > 0 ) {
  48709. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  48710. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  48711. // Get a reference to the array of objects with queries. The renderContextData property
  48712. // can be changed by another render pass before the buffer.mapAsyc() completes.
  48713. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  48714. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  48715. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48716. //
  48717. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  48718. renderContextData.occlusionQuerySet = occlusionQuerySet;
  48719. renderContextData.occlusionQueryIndex = 0;
  48720. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48721. renderContextData.lastOcclusionObject = null;
  48722. }
  48723. let descriptor;
  48724. if ( renderContext.textures === null ) {
  48725. descriptor = this._getDefaultRenderPassDescriptor();
  48726. } else {
  48727. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  48728. }
  48729. this.initTimestampQuery( renderContext, descriptor );
  48730. descriptor.occlusionQuerySet = occlusionQuerySet;
  48731. const depthStencilAttachment = descriptor.depthStencilAttachment;
  48732. if ( renderContext.textures !== null ) {
  48733. const colorAttachments = descriptor.colorAttachments;
  48734. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  48735. const colorAttachment = colorAttachments[ i ];
  48736. if ( renderContext.clearColor ) {
  48737. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  48738. colorAttachment.loadOp = GPULoadOp.Clear;
  48739. colorAttachment.storeOp = GPUStoreOp.Store;
  48740. } else {
  48741. colorAttachment.loadOp = GPULoadOp.Load;
  48742. colorAttachment.storeOp = GPUStoreOp.Store;
  48743. }
  48744. }
  48745. } else {
  48746. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48747. if ( renderContext.clearColor ) {
  48748. colorAttachment.clearValue = renderContext.clearColorValue;
  48749. colorAttachment.loadOp = GPULoadOp.Clear;
  48750. colorAttachment.storeOp = GPUStoreOp.Store;
  48751. } else {
  48752. colorAttachment.loadOp = GPULoadOp.Load;
  48753. colorAttachment.storeOp = GPUStoreOp.Store;
  48754. }
  48755. }
  48756. //
  48757. if ( renderContext.depth ) {
  48758. if ( renderContext.clearDepth ) {
  48759. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  48760. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48761. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48762. } else {
  48763. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48764. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48765. }
  48766. }
  48767. if ( renderContext.stencil ) {
  48768. if ( renderContext.clearStencil ) {
  48769. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  48770. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48771. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48772. } else {
  48773. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48774. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48775. }
  48776. }
  48777. //
  48778. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  48779. const currentPass = encoder.beginRenderPass( descriptor );
  48780. //
  48781. renderContextData.descriptor = descriptor;
  48782. renderContextData.encoder = encoder;
  48783. renderContextData.currentPass = currentPass;
  48784. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48785. renderContextData.renderBundles = [];
  48786. //
  48787. if ( renderContext.viewport ) {
  48788. this.updateViewport( renderContext );
  48789. }
  48790. if ( renderContext.scissor ) {
  48791. const { x, y, width, height } = renderContext.scissorValue;
  48792. currentPass.setScissorRect( x, y, width, height );
  48793. }
  48794. }
  48795. /**
  48796. * This method is executed at the end of a render call and finalizes work
  48797. * after draw calls.
  48798. *
  48799. * @param {RenderContext} renderContext - The render context.
  48800. */
  48801. finishRender( renderContext ) {
  48802. const renderContextData = this.get( renderContext );
  48803. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48804. if ( renderContextData.renderBundles.length > 0 ) {
  48805. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  48806. }
  48807. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48808. renderContextData.currentPass.endOcclusionQuery();
  48809. }
  48810. renderContextData.currentPass.end();
  48811. if ( occlusionQueryCount > 0 ) {
  48812. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  48813. //
  48814. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  48815. if ( queryResolveBuffer === undefined ) {
  48816. queryResolveBuffer = this.device.createBuffer(
  48817. {
  48818. size: bufferSize,
  48819. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  48820. }
  48821. );
  48822. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  48823. }
  48824. //
  48825. const readBuffer = this.device.createBuffer(
  48826. {
  48827. size: bufferSize,
  48828. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48829. }
  48830. );
  48831. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  48832. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  48833. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  48834. renderContextData.occlusionQueryBuffer = readBuffer;
  48835. //
  48836. this.resolveOccludedAsync( renderContext );
  48837. }
  48838. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  48839. //
  48840. if ( renderContext.textures !== null ) {
  48841. const textures = renderContext.textures;
  48842. for ( let i = 0; i < textures.length; i ++ ) {
  48843. const texture = textures[ i ];
  48844. if ( texture.generateMipmaps === true ) {
  48845. this.textureUtils.generateMipmaps( texture );
  48846. }
  48847. }
  48848. }
  48849. }
  48850. /**
  48851. * Returns `true` if the given 3D object is fully occluded by other
  48852. * 3D objects in the scene.
  48853. *
  48854. * @param {RenderContext} renderContext - The render context.
  48855. * @param {Object3D} object - The 3D object to test.
  48856. * @return {boolean} Whether the 3D object is fully occluded or not.
  48857. */
  48858. isOccluded( renderContext, object ) {
  48859. const renderContextData = this.get( renderContext );
  48860. return renderContextData.occluded && renderContextData.occluded.has( object );
  48861. }
  48862. /**
  48863. * This method processes the result of occlusion queries and writes it
  48864. * into render context data.
  48865. *
  48866. * @async
  48867. * @param {RenderContext} renderContext - The render context.
  48868. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  48869. */
  48870. async resolveOccludedAsync( renderContext ) {
  48871. const renderContextData = this.get( renderContext );
  48872. // handle occlusion query results
  48873. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  48874. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  48875. const occluded = new WeakSet();
  48876. renderContextData.currentOcclusionQueryObjects = null;
  48877. renderContextData.currentOcclusionQueryBuffer = null;
  48878. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  48879. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  48880. const results = new BigUint64Array( buffer );
  48881. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  48882. if ( results[ i ] === BigInt( 0 ) ) {
  48883. occluded.add( currentOcclusionQueryObjects[ i ] );
  48884. }
  48885. }
  48886. currentOcclusionQueryBuffer.destroy();
  48887. renderContextData.occluded = occluded;
  48888. }
  48889. }
  48890. /**
  48891. * Updates the viewport with the values from the given render context.
  48892. *
  48893. * @param {RenderContext} renderContext - The render context.
  48894. */
  48895. updateViewport( renderContext ) {
  48896. const { currentPass } = this.get( renderContext );
  48897. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  48898. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  48899. }
  48900. /**
  48901. * Returns the clear color and alpha into a single
  48902. * color object.
  48903. *
  48904. * @return {Color4} The clear color.
  48905. */
  48906. getClearColor() {
  48907. const clearColor = super.getClearColor();
  48908. // only premultiply alpha when alphaMode is "premultiplied"
  48909. if ( this.renderer.alpha === true ) {
  48910. clearColor.r *= clearColor.a;
  48911. clearColor.g *= clearColor.a;
  48912. clearColor.b *= clearColor.a;
  48913. }
  48914. return clearColor;
  48915. }
  48916. /**
  48917. * Performs a clear operation.
  48918. *
  48919. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48920. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48921. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48922. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  48923. */
  48924. clear( color, depth, stencil, renderTargetContext = null ) {
  48925. const device = this.device;
  48926. const renderer = this.renderer;
  48927. let colorAttachments = [];
  48928. let depthStencilAttachment;
  48929. let clearValue;
  48930. let supportsDepth;
  48931. let supportsStencil;
  48932. if ( color ) {
  48933. const clearColor = this.getClearColor();
  48934. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  48935. }
  48936. if ( renderTargetContext === null ) {
  48937. supportsDepth = renderer.depth;
  48938. supportsStencil = renderer.stencil;
  48939. const descriptor = this._getDefaultRenderPassDescriptor();
  48940. if ( color ) {
  48941. colorAttachments = descriptor.colorAttachments;
  48942. const colorAttachment = colorAttachments[ 0 ];
  48943. colorAttachment.clearValue = clearValue;
  48944. colorAttachment.loadOp = GPULoadOp.Clear;
  48945. colorAttachment.storeOp = GPUStoreOp.Store;
  48946. }
  48947. if ( supportsDepth || supportsStencil ) {
  48948. depthStencilAttachment = descriptor.depthStencilAttachment;
  48949. }
  48950. } else {
  48951. supportsDepth = renderTargetContext.depth;
  48952. supportsStencil = renderTargetContext.stencil;
  48953. const clearConfig = {
  48954. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  48955. clearValue: color ? clearValue : undefined
  48956. };
  48957. if ( supportsDepth ) {
  48958. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  48959. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  48960. clearConfig.depthStoreOp = GPUStoreOp.Store;
  48961. }
  48962. if ( supportsStencil ) {
  48963. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  48964. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  48965. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  48966. }
  48967. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  48968. colorAttachments = descriptor.colorAttachments;
  48969. depthStencilAttachment = descriptor.depthStencilAttachment;
  48970. }
  48971. if ( supportsDepth && depthStencilAttachment && depthStencilAttachment.depthLoadOp === undefined ) {
  48972. if ( depth ) {
  48973. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48974. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  48975. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48976. } else {
  48977. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48978. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48979. }
  48980. }
  48981. //
  48982. if ( supportsStencil && depthStencilAttachment && depthStencilAttachment.stencilLoadOp === undefined ) {
  48983. if ( stencil ) {
  48984. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48985. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  48986. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48987. } else {
  48988. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48989. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48990. }
  48991. }
  48992. //
  48993. const encoder = device.createCommandEncoder( { label: 'clear' } );
  48994. const currentPass = encoder.beginRenderPass( {
  48995. colorAttachments,
  48996. depthStencilAttachment
  48997. } );
  48998. currentPass.end();
  48999. device.queue.submit( [ encoder.finish() ] );
  49000. }
  49001. // compute
  49002. /**
  49003. * This method is executed at the beginning of a compute call and
  49004. * prepares the state for upcoming compute tasks.
  49005. *
  49006. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49007. */
  49008. beginCompute( computeGroup ) {
  49009. const groupGPU = this.get( computeGroup );
  49010. const descriptor = {
  49011. label: 'computeGroup_' + computeGroup.id
  49012. };
  49013. this.initTimestampQuery( computeGroup, descriptor );
  49014. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  49015. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  49016. }
  49017. /**
  49018. * Executes a compute command for the given compute node.
  49019. *
  49020. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  49021. * @param {Node} computeNode - The compute node.
  49022. * @param {Array<BindGroup>} bindings - The bindings.
  49023. * @param {ComputePipeline} pipeline - The compute pipeline.
  49024. */
  49025. compute( computeGroup, computeNode, bindings, pipeline ) {
  49026. const { passEncoderGPU } = this.get( computeGroup );
  49027. // pipeline
  49028. const pipelineGPU = this.get( pipeline ).pipeline;
  49029. passEncoderGPU.setPipeline( pipelineGPU );
  49030. // bind groups
  49031. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  49032. const bindGroup = bindings[ i ];
  49033. const bindingsData = this.get( bindGroup );
  49034. passEncoderGPU.setBindGroup( i, bindingsData.group );
  49035. }
  49036. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  49037. const computeNodeData = this.get( computeNode );
  49038. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  49039. const { dispatchSize } = computeNodeData;
  49040. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  49041. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  49042. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  49043. } else {
  49044. dispatchSize.x = computeNode.dispatchCount;
  49045. }
  49046. passEncoderGPU.dispatchWorkgroups(
  49047. dispatchSize.x,
  49048. dispatchSize.y,
  49049. dispatchSize.z
  49050. );
  49051. }
  49052. /**
  49053. * This method is executed at the end of a compute call and
  49054. * finalizes work after compute tasks.
  49055. *
  49056. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49057. */
  49058. finishCompute( computeGroup ) {
  49059. const groupData = this.get( computeGroup );
  49060. groupData.passEncoderGPU.end();
  49061. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  49062. }
  49063. /**
  49064. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  49065. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  49066. *
  49067. * @async
  49068. * @return {Promise} A Promise that resolves when synchronization has been finished.
  49069. */
  49070. async waitForGPU() {
  49071. await this.device.queue.onSubmittedWorkDone();
  49072. }
  49073. // render object
  49074. /**
  49075. * Executes a draw command for the given render object.
  49076. *
  49077. * @param {RenderObject} renderObject - The render object to draw.
  49078. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  49079. */
  49080. draw( renderObject, info ) {
  49081. const { object, material, context, pipeline } = renderObject;
  49082. const bindings = renderObject.getBindings();
  49083. const renderContextData = this.get( context );
  49084. const pipelineGPU = this.get( pipeline ).pipeline;
  49085. const currentSets = renderContextData.currentSets;
  49086. const passEncoderGPU = renderContextData.currentPass;
  49087. const drawParams = renderObject.getDrawParameters();
  49088. if ( drawParams === null ) return;
  49089. // pipeline
  49090. if ( currentSets.pipeline !== pipelineGPU ) {
  49091. passEncoderGPU.setPipeline( pipelineGPU );
  49092. currentSets.pipeline = pipelineGPU;
  49093. }
  49094. // bind groups
  49095. const currentBindingGroups = currentSets.bindingGroups;
  49096. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  49097. const bindGroup = bindings[ i ];
  49098. const bindingsData = this.get( bindGroup );
  49099. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  49100. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  49101. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  49102. }
  49103. }
  49104. // attributes
  49105. const index = renderObject.getIndex();
  49106. const hasIndex = ( index !== null );
  49107. // index
  49108. if ( hasIndex === true ) {
  49109. if ( currentSets.index !== index ) {
  49110. const buffer = this.get( index ).buffer;
  49111. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49112. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  49113. currentSets.index = index;
  49114. }
  49115. }
  49116. // vertex buffers
  49117. const vertexBuffers = renderObject.getVertexBuffers();
  49118. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  49119. const vertexBuffer = vertexBuffers[ i ];
  49120. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  49121. const buffer = this.get( vertexBuffer ).buffer;
  49122. passEncoderGPU.setVertexBuffer( i, buffer );
  49123. currentSets.attributes[ i ] = vertexBuffer;
  49124. }
  49125. }
  49126. // occlusion queries - handle multiple consecutive draw calls for an object
  49127. if ( renderContextData.occlusionQuerySet !== undefined ) {
  49128. const lastObject = renderContextData.lastOcclusionObject;
  49129. if ( lastObject !== object ) {
  49130. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49131. passEncoderGPU.endOcclusionQuery();
  49132. renderContextData.occlusionQueryIndex ++;
  49133. }
  49134. if ( object.occlusionTest === true ) {
  49135. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  49136. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  49137. }
  49138. renderContextData.lastOcclusionObject = object;
  49139. }
  49140. }
  49141. // stencil
  49142. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  49143. passEncoderGPU.setStencilReference( material.stencilRef );
  49144. renderContextData.currentStencilRef = material.stencilRef;
  49145. }
  49146. // draw
  49147. const draw = () => {
  49148. if ( object.isBatchedMesh === true ) {
  49149. const starts = object._multiDrawStarts;
  49150. const counts = object._multiDrawCounts;
  49151. const drawCount = object._multiDrawCount;
  49152. const drawInstances = object._multiDrawInstances;
  49153. if ( drawInstances !== null ) {
  49154. // @deprecated, r174
  49155. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  49156. }
  49157. for ( let i = 0; i < drawCount; i ++ ) {
  49158. const count = drawInstances ? drawInstances[ i ] : 1;
  49159. const firstInstance = count > 1 ? 0 : i;
  49160. if ( hasIndex === true ) {
  49161. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  49162. } else {
  49163. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  49164. }
  49165. info.update( object, counts[ i ], count );
  49166. }
  49167. } else if ( hasIndex === true ) {
  49168. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  49169. const indirect = renderObject.getIndirect();
  49170. if ( indirect !== null ) {
  49171. const buffer = this.get( indirect ).buffer;
  49172. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  49173. } else {
  49174. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  49175. }
  49176. info.update( object, indexCount, instanceCount );
  49177. } else {
  49178. const { vertexCount, instanceCount, firstVertex } = drawParams;
  49179. const indirect = renderObject.getIndirect();
  49180. if ( indirect !== null ) {
  49181. const buffer = this.get( indirect ).buffer;
  49182. passEncoderGPU.drawIndirect( buffer, 0 );
  49183. } else {
  49184. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  49185. }
  49186. info.update( object, vertexCount, instanceCount );
  49187. }
  49188. };
  49189. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  49190. const cameraData = this.get( renderObject.camera );
  49191. const cameras = renderObject.camera.cameras;
  49192. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  49193. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  49194. const bindingsData = this.get( cameraIndex );
  49195. const indexesGPU = [];
  49196. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  49197. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49198. data[ 0 ] = i;
  49199. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  49200. indexesGPU.push( bindGroupIndex );
  49201. }
  49202. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  49203. }
  49204. const pixelRatio = this.renderer.getPixelRatio();
  49205. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49206. const subCamera = cameras[ i ];
  49207. if ( object.layers.test( subCamera.layers ) ) {
  49208. const vp = subCamera.viewport;
  49209. passEncoderGPU.setViewport(
  49210. Math.floor( vp.x * pixelRatio ),
  49211. Math.floor( vp.y * pixelRatio ),
  49212. Math.floor( vp.width * pixelRatio ),
  49213. Math.floor( vp.height * pixelRatio ),
  49214. context.viewportValue.minDepth,
  49215. context.viewportValue.maxDepth
  49216. );
  49217. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  49218. draw();
  49219. }
  49220. }
  49221. } else {
  49222. draw();
  49223. }
  49224. }
  49225. // cache key
  49226. /**
  49227. * Returns `true` if the render pipeline requires an update.
  49228. *
  49229. * @param {RenderObject} renderObject - The render object.
  49230. * @return {boolean} Whether the render pipeline requires an update or not.
  49231. */
  49232. needsRenderUpdate( renderObject ) {
  49233. const data = this.get( renderObject );
  49234. const { object, material } = renderObject;
  49235. const utils = this.utils;
  49236. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  49237. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  49238. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  49239. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  49240. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  49241. let needsUpdate = false;
  49242. if ( data.material !== material || data.materialVersion !== material.version ||
  49243. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  49244. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  49245. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  49246. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  49247. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  49248. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  49249. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  49250. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  49251. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  49252. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  49253. data.primitiveTopology !== primitiveTopology ||
  49254. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  49255. ) {
  49256. data.material = material; data.materialVersion = material.version;
  49257. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  49258. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  49259. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  49260. data.colorWrite = material.colorWrite;
  49261. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  49262. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  49263. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  49264. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  49265. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  49266. data.sampleCount = sampleCount;
  49267. data.colorSpace = colorSpace;
  49268. data.colorFormat = colorFormat;
  49269. data.depthStencilFormat = depthStencilFormat;
  49270. data.primitiveTopology = primitiveTopology;
  49271. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  49272. needsUpdate = true;
  49273. }
  49274. return needsUpdate;
  49275. }
  49276. /**
  49277. * Returns a cache key that is used to identify render pipelines.
  49278. *
  49279. * @param {RenderObject} renderObject - The render object.
  49280. * @return {string} The cache key.
  49281. */
  49282. getRenderCacheKey( renderObject ) {
  49283. const { object, material } = renderObject;
  49284. const utils = this.utils;
  49285. const renderContext = renderObject.context;
  49286. return [
  49287. material.transparent, material.blending, material.premultipliedAlpha,
  49288. material.blendSrc, material.blendDst, material.blendEquation,
  49289. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  49290. material.colorWrite,
  49291. material.depthWrite, material.depthTest, material.depthFunc,
  49292. material.stencilWrite, material.stencilFunc,
  49293. material.stencilFail, material.stencilZFail, material.stencilZPass,
  49294. material.stencilFuncMask, material.stencilWriteMask,
  49295. material.side,
  49296. utils.getSampleCountRenderContext( renderContext ),
  49297. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  49298. utils.getPrimitiveTopology( object, material ),
  49299. renderObject.getGeometryCacheKey(),
  49300. renderObject.clippingContextCacheKey
  49301. ].join();
  49302. }
  49303. // textures
  49304. /**
  49305. * Creates a GPU sampler for the given texture.
  49306. *
  49307. * @param {Texture} texture - The texture to create the sampler for.
  49308. */
  49309. createSampler( texture ) {
  49310. this.textureUtils.createSampler( texture );
  49311. }
  49312. /**
  49313. * Destroys the GPU sampler for the given texture.
  49314. *
  49315. * @param {Texture} texture - The texture to destroy the sampler for.
  49316. */
  49317. destroySampler( texture ) {
  49318. this.textureUtils.destroySampler( texture );
  49319. }
  49320. /**
  49321. * Creates a default texture for the given texture that can be used
  49322. * as a placeholder until the actual texture is ready for usage.
  49323. *
  49324. * @param {Texture} texture - The texture to create a default texture for.
  49325. */
  49326. createDefaultTexture( texture ) {
  49327. this.textureUtils.createDefaultTexture( texture );
  49328. }
  49329. /**
  49330. * Defines a texture on the GPU for the given texture object.
  49331. *
  49332. * @param {Texture} texture - The texture.
  49333. * @param {Object} [options={}] - Optional configuration parameter.
  49334. */
  49335. createTexture( texture, options ) {
  49336. this.textureUtils.createTexture( texture, options );
  49337. }
  49338. /**
  49339. * Uploads the updated texture data to the GPU.
  49340. *
  49341. * @param {Texture} texture - The texture.
  49342. * @param {Object} [options={}] - Optional configuration parameter.
  49343. */
  49344. updateTexture( texture, options ) {
  49345. this.textureUtils.updateTexture( texture, options );
  49346. }
  49347. /**
  49348. * Generates mipmaps for the given texture.
  49349. *
  49350. * @param {Texture} texture - The texture.
  49351. */
  49352. generateMipmaps( texture ) {
  49353. this.textureUtils.generateMipmaps( texture );
  49354. }
  49355. /**
  49356. * Destroys the GPU data for the given texture object.
  49357. *
  49358. * @param {Texture} texture - The texture.
  49359. */
  49360. destroyTexture( texture ) {
  49361. this.textureUtils.destroyTexture( texture );
  49362. }
  49363. /**
  49364. * Returns texture data as a typed array.
  49365. *
  49366. * @async
  49367. * @param {Texture} texture - The texture to copy.
  49368. * @param {number} x - The x coordinate of the copy origin.
  49369. * @param {number} y - The y coordinate of the copy origin.
  49370. * @param {number} width - The width of the copy.
  49371. * @param {number} height - The height of the copy.
  49372. * @param {number} faceIndex - The face index.
  49373. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49374. */
  49375. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49376. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49377. }
  49378. /**
  49379. * Inits a time stamp query for the given render context.
  49380. *
  49381. * @param {RenderContext} renderContext - The render context.
  49382. * @param {Object} descriptor - The query descriptor.
  49383. */
  49384. initTimestampQuery( renderContext, descriptor ) {
  49385. if ( ! this.trackTimestamp ) return;
  49386. const type = renderContext.isComputeNode ? 'compute' : 'render';
  49387. if ( ! this.timestampQueryPool[ type ] ) {
  49388. // TODO: Variable maxQueries?
  49389. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  49390. }
  49391. const timestampQueryPool = this.timestampQueryPool[ type ];
  49392. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  49393. descriptor.timestampWrites = {
  49394. querySet: timestampQueryPool.querySet,
  49395. beginningOfPassWriteIndex: baseOffset,
  49396. endOfPassWriteIndex: baseOffset + 1,
  49397. };
  49398. }
  49399. // node builder
  49400. /**
  49401. * Returns a node builder for the given render object.
  49402. *
  49403. * @param {RenderObject} object - The render object.
  49404. * @param {Renderer} renderer - The renderer.
  49405. * @return {WGSLNodeBuilder} The node builder.
  49406. */
  49407. createNodeBuilder( object, renderer ) {
  49408. return new WGSLNodeBuilder( object, renderer );
  49409. }
  49410. // program
  49411. /**
  49412. * Creates a shader program from the given programmable stage.
  49413. *
  49414. * @param {ProgrammableStage} program - The programmable stage.
  49415. */
  49416. createProgram( program ) {
  49417. const programGPU = this.get( program );
  49418. programGPU.module = {
  49419. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  49420. entryPoint: 'main'
  49421. };
  49422. }
  49423. /**
  49424. * Destroys the shader program of the given programmable stage.
  49425. *
  49426. * @param {ProgrammableStage} program - The programmable stage.
  49427. */
  49428. destroyProgram( program ) {
  49429. this.delete( program );
  49430. }
  49431. // pipelines
  49432. /**
  49433. * Creates a render pipeline for the given render object.
  49434. *
  49435. * @param {RenderObject} renderObject - The render object.
  49436. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49437. */
  49438. createRenderPipeline( renderObject, promises ) {
  49439. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  49440. }
  49441. /**
  49442. * Creates a compute pipeline for the given compute node.
  49443. *
  49444. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49445. * @param {Array<BindGroup>} bindings - The bindings.
  49446. */
  49447. createComputePipeline( computePipeline, bindings ) {
  49448. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  49449. }
  49450. /**
  49451. * Prepares the state for encoding render bundles.
  49452. *
  49453. * @param {RenderContext} renderContext - The render context.
  49454. */
  49455. beginBundle( renderContext ) {
  49456. const renderContextData = this.get( renderContext );
  49457. renderContextData._currentPass = renderContextData.currentPass;
  49458. renderContextData._currentSets = renderContextData.currentSets;
  49459. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49460. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  49461. }
  49462. /**
  49463. * After processing render bundles this method finalizes related work.
  49464. *
  49465. * @param {RenderContext} renderContext - The render context.
  49466. * @param {RenderBundle} bundle - The render bundle.
  49467. */
  49468. finishBundle( renderContext, bundle ) {
  49469. const renderContextData = this.get( renderContext );
  49470. const bundleEncoder = renderContextData.currentPass;
  49471. const bundleGPU = bundleEncoder.finish();
  49472. this.get( bundle ).bundleGPU = bundleGPU;
  49473. // restore render pass state
  49474. renderContextData.currentSets = renderContextData._currentSets;
  49475. renderContextData.currentPass = renderContextData._currentPass;
  49476. }
  49477. /**
  49478. * Adds a render bundle to the render context data.
  49479. *
  49480. * @param {RenderContext} renderContext - The render context.
  49481. * @param {RenderBundle} bundle - The render bundle to add.
  49482. */
  49483. addBundle( renderContext, bundle ) {
  49484. const renderContextData = this.get( renderContext );
  49485. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  49486. }
  49487. // bindings
  49488. /**
  49489. * Creates bindings from the given bind group definition.
  49490. *
  49491. * @param {BindGroup} bindGroup - The bind group.
  49492. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49493. * @param {number} cacheIndex - The cache index.
  49494. * @param {number} version - The version.
  49495. */
  49496. createBindings( bindGroup, bindings, cacheIndex, version ) {
  49497. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  49498. }
  49499. /**
  49500. * Updates the given bind group definition.
  49501. *
  49502. * @param {BindGroup} bindGroup - The bind group.
  49503. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49504. * @param {number} cacheIndex - The cache index.
  49505. * @param {number} version - The version.
  49506. */
  49507. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  49508. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  49509. }
  49510. /**
  49511. * Updates a buffer binding.
  49512. *
  49513. * @param {Buffer} binding - The buffer binding to update.
  49514. */
  49515. updateBinding( binding ) {
  49516. this.bindingUtils.updateBinding( binding );
  49517. }
  49518. // attributes
  49519. /**
  49520. * Creates the buffer of an indexed shader attribute.
  49521. *
  49522. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49523. */
  49524. createIndexAttribute( attribute ) {
  49525. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49526. }
  49527. /**
  49528. * Creates the GPU buffer of a shader attribute.
  49529. *
  49530. * @param {BufferAttribute} attribute - The buffer attribute.
  49531. */
  49532. createAttribute( attribute ) {
  49533. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49534. }
  49535. /**
  49536. * Creates the GPU buffer of a storage attribute.
  49537. *
  49538. * @param {BufferAttribute} attribute - The buffer attribute.
  49539. */
  49540. createStorageAttribute( attribute ) {
  49541. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49542. }
  49543. /**
  49544. * Creates the GPU buffer of an indirect storage attribute.
  49545. *
  49546. * @param {BufferAttribute} attribute - The buffer attribute.
  49547. */
  49548. createIndirectStorageAttribute( attribute ) {
  49549. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49550. }
  49551. /**
  49552. * Updates the GPU buffer of a shader attribute.
  49553. *
  49554. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49555. */
  49556. updateAttribute( attribute ) {
  49557. this.attributeUtils.updateAttribute( attribute );
  49558. }
  49559. /**
  49560. * Destroys the GPU buffer of a shader attribute.
  49561. *
  49562. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49563. */
  49564. destroyAttribute( attribute ) {
  49565. this.attributeUtils.destroyAttribute( attribute );
  49566. }
  49567. // canvas
  49568. /**
  49569. * Triggers an update of the default render pass descriptor.
  49570. */
  49571. updateSize() {
  49572. this.colorBuffer = this.textureUtils.getColorBuffer();
  49573. this.defaultRenderPassdescriptor = null;
  49574. }
  49575. // utils public
  49576. /**
  49577. * Returns the maximum anisotropy texture filtering value.
  49578. *
  49579. * @return {number} The maximum anisotropy texture filtering value.
  49580. */
  49581. getMaxAnisotropy() {
  49582. return 16;
  49583. }
  49584. /**
  49585. * Checks if the given feature is supported by the backend.
  49586. *
  49587. * @param {string} name - The feature's name.
  49588. * @return {boolean} Whether the feature is supported or not.
  49589. */
  49590. hasFeature( name ) {
  49591. return this.device.features.has( name );
  49592. }
  49593. /**
  49594. * Copies data of the given source texture to the given destination texture.
  49595. *
  49596. * @param {Texture} srcTexture - The source texture.
  49597. * @param {Texture} dstTexture - The destination texture.
  49598. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49599. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49600. * @param {number} [srcLevel=0] - The mipmap level to copy.
  49601. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49602. */
  49603. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49604. let dstX = 0;
  49605. let dstY = 0;
  49606. let dstZ = 0;
  49607. let srcX = 0;
  49608. let srcY = 0;
  49609. let srcZ = 0;
  49610. let srcWidth = srcTexture.image.width;
  49611. let srcHeight = srcTexture.image.height;
  49612. let srcDepth = 1;
  49613. if ( srcRegion !== null ) {
  49614. if ( srcRegion.isBox3 === true ) {
  49615. srcX = srcRegion.min.x;
  49616. srcY = srcRegion.min.y;
  49617. srcZ = srcRegion.min.z;
  49618. srcWidth = srcRegion.max.x - srcRegion.min.x;
  49619. srcHeight = srcRegion.max.y - srcRegion.min.y;
  49620. srcDepth = srcRegion.max.z - srcRegion.min.z;
  49621. } else {
  49622. // Assume it's a Box2
  49623. srcX = srcRegion.min.x;
  49624. srcY = srcRegion.min.y;
  49625. srcWidth = srcRegion.max.x - srcRegion.min.x;
  49626. srcHeight = srcRegion.max.y - srcRegion.min.y;
  49627. srcDepth = 1;
  49628. }
  49629. }
  49630. if ( dstPosition !== null ) {
  49631. dstX = dstPosition.x;
  49632. dstY = dstPosition.y;
  49633. dstZ = dstPosition.z || 0;
  49634. }
  49635. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  49636. const sourceGPU = this.get( srcTexture ).texture;
  49637. const destinationGPU = this.get( dstTexture ).texture;
  49638. encoder.copyTextureToTexture(
  49639. {
  49640. texture: sourceGPU,
  49641. mipLevel: srcLevel,
  49642. origin: { x: srcX, y: srcY, z: srcZ }
  49643. },
  49644. {
  49645. texture: destinationGPU,
  49646. mipLevel: dstLevel,
  49647. origin: { x: dstX, y: dstY, z: dstZ }
  49648. },
  49649. [
  49650. srcWidth,
  49651. srcHeight,
  49652. srcDepth
  49653. ]
  49654. );
  49655. this.device.queue.submit( [ encoder.finish() ] );
  49656. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  49657. this.textureUtils.generateMipmaps( dstTexture );
  49658. }
  49659. }
  49660. /**
  49661. * Copies the current bound framebuffer to the given texture.
  49662. *
  49663. * @param {Texture} texture - The destination texture.
  49664. * @param {RenderContext} renderContext - The render context.
  49665. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49666. */
  49667. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49668. const renderContextData = this.get( renderContext );
  49669. let sourceGPU = null;
  49670. if ( renderContext.renderTarget ) {
  49671. if ( texture.isDepthTexture ) {
  49672. sourceGPU = this.get( renderContext.depthTexture ).texture;
  49673. } else {
  49674. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  49675. }
  49676. } else {
  49677. if ( texture.isDepthTexture ) {
  49678. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  49679. } else {
  49680. sourceGPU = this.context.getCurrentTexture();
  49681. }
  49682. }
  49683. const destinationGPU = this.get( texture ).texture;
  49684. if ( sourceGPU.format !== destinationGPU.format ) {
  49685. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  49686. return;
  49687. }
  49688. let encoder;
  49689. if ( renderContextData.currentPass ) {
  49690. renderContextData.currentPass.end();
  49691. encoder = renderContextData.encoder;
  49692. } else {
  49693. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  49694. }
  49695. encoder.copyTextureToTexture(
  49696. {
  49697. texture: sourceGPU,
  49698. origin: [ rectangle.x, rectangle.y, 0 ],
  49699. },
  49700. {
  49701. texture: destinationGPU
  49702. },
  49703. [
  49704. rectangle.z,
  49705. rectangle.w
  49706. ]
  49707. );
  49708. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  49709. if ( renderContextData.currentPass ) {
  49710. const { descriptor } = renderContextData;
  49711. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  49712. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  49713. }
  49714. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  49715. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  49716. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  49717. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49718. if ( renderContext.viewport ) {
  49719. this.updateViewport( renderContext );
  49720. }
  49721. if ( renderContext.scissor ) {
  49722. const { x, y, width, height } = renderContext.scissorValue;
  49723. renderContextData.currentPass.setScissorRect( x, y, width, height );
  49724. }
  49725. } else {
  49726. this.device.queue.submit( [ encoder.finish() ] );
  49727. }
  49728. }
  49729. }
  49730. /**
  49731. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  49732. *
  49733. * @augments SpotLight
  49734. */
  49735. class IESSpotLight extends SpotLight {
  49736. /**
  49737. * Constructs a new IES spot light.
  49738. *
  49739. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  49740. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  49741. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  49742. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  49743. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  49744. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  49745. */
  49746. constructor( color, intensity, distance, angle, penumbra, decay ) {
  49747. super( color, intensity, distance, angle, penumbra, decay );
  49748. /**
  49749. * TODO
  49750. *
  49751. * @type {?Texture}
  49752. * @default null
  49753. */
  49754. this.iesMap = null;
  49755. }
  49756. copy( source, recursive ) {
  49757. super.copy( source, recursive );
  49758. this.iesMap = source.iesMap;
  49759. return this;
  49760. }
  49761. }
  49762. /**
  49763. * This version of a node library represents a basic version
  49764. * just focusing on lights and tone mapping techniques.
  49765. *
  49766. * @private
  49767. * @augments NodeLibrary
  49768. */
  49769. class BasicNodeLibrary extends NodeLibrary {
  49770. /**
  49771. * Constructs a new basic node library.
  49772. */
  49773. constructor() {
  49774. super();
  49775. this.addLight( PointLightNode, PointLight );
  49776. this.addLight( DirectionalLightNode, DirectionalLight );
  49777. this.addLight( RectAreaLightNode, RectAreaLight );
  49778. this.addLight( SpotLightNode, SpotLight );
  49779. this.addLight( AmbientLightNode, AmbientLight );
  49780. this.addLight( HemisphereLightNode, HemisphereLight );
  49781. this.addLight( LightProbeNode, LightProbe );
  49782. this.addLight( IESSpotLightNode, IESSpotLight );
  49783. this.addToneMapping( linearToneMapping, LinearToneMapping );
  49784. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  49785. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  49786. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  49787. this.addToneMapping( agxToneMapping, AgXToneMapping );
  49788. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  49789. }
  49790. }
  49791. /**
  49792. * This alternative version of {@link WebGPURenderer} only supports node materials.
  49793. * So classes like `MeshBasicMaterial` are not compatible.
  49794. *
  49795. * @private
  49796. * @augments Renderer
  49797. */
  49798. class WebGPURenderer extends Renderer {
  49799. /**
  49800. * Constructs a new WebGPU renderer.
  49801. *
  49802. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  49803. */
  49804. constructor( parameters = {} ) {
  49805. let BackendClass;
  49806. if ( parameters.forceWebGL ) {
  49807. BackendClass = WebGLBackend;
  49808. } else {
  49809. BackendClass = WebGPUBackend;
  49810. parameters.getFallback = () => {
  49811. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  49812. return new WebGLBackend( parameters );
  49813. };
  49814. }
  49815. const backend = new BackendClass( parameters );
  49816. super( backend, parameters );
  49817. /**
  49818. * The generic default value is overwritten with the
  49819. * standard node library for type mapping. Material
  49820. * mapping is not supported with this version.
  49821. *
  49822. * @type {BasicNodeLibrary}
  49823. */
  49824. this.library = new BasicNodeLibrary();
  49825. /**
  49826. * This flag can be used for type testing.
  49827. *
  49828. * @type {boolean}
  49829. * @readonly
  49830. * @default true
  49831. */
  49832. this.isWebGPURenderer = true;
  49833. }
  49834. }
  49835. /**
  49836. * A specialized group which enables applications access to the
  49837. * Render Bundle API of WebGPU. The group with all its descendant nodes
  49838. * are considered as one render bundle and processed as such by
  49839. * the renderer.
  49840. *
  49841. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  49842. * With a WebGL backend, the group can technically be rendered but without
  49843. * any performance improvements.
  49844. *
  49845. * @augments Group
  49846. */
  49847. class BundleGroup extends Group {
  49848. /**
  49849. * Constructs a new bundle group.
  49850. */
  49851. constructor() {
  49852. super();
  49853. /**
  49854. * This flag can be used for type testing.
  49855. *
  49856. * @type {boolean}
  49857. * @readonly
  49858. * @default true
  49859. */
  49860. this.isBundleGroup = true;
  49861. /**
  49862. * This property is only relevant for detecting types
  49863. * during serialization/deserialization. It should always
  49864. * match the class name.
  49865. *
  49866. * @type {string}
  49867. * @readonly
  49868. * @default 'BundleGroup'
  49869. */
  49870. this.type = 'BundleGroup';
  49871. /**
  49872. * Whether the bundle is static or not. When set to `true`, the structure
  49873. * is assumed to be static and does not change. E.g. no new objects are
  49874. * added to the group
  49875. *
  49876. * If a change is required, an update can still be forced by setting the
  49877. * `needsUpdate` flag to `true`.
  49878. *
  49879. * @type {boolean}
  49880. * @default true
  49881. */
  49882. this.static = true;
  49883. /**
  49884. * The bundle group's version.
  49885. *
  49886. * @type {number}
  49887. * @readonly
  49888. * @default 0
  49889. */
  49890. this.version = 0;
  49891. }
  49892. /**
  49893. * Set this property to `true` when the bundle group has changed.
  49894. *
  49895. * @type {boolean}
  49896. * @default false
  49897. * @param {boolean} value
  49898. */
  49899. set needsUpdate( value ) {
  49900. if ( value === true ) this.version ++;
  49901. }
  49902. }
  49903. /**
  49904. * This module is responsible to manage the post processing setups in apps.
  49905. * You usually create a single instance of this class and use it to define
  49906. * the output of your post processing effect chain.
  49907. * ```js
  49908. * const postProcessing = new PostProcessing( renderer );
  49909. *
  49910. * const scenePass = pass( scene, camera );
  49911. *
  49912. * postProcessing.outputNode = scenePass;
  49913. * ```
  49914. *
  49915. * Note: This module can only be used with `WebGPURenderer`.
  49916. */
  49917. class PostProcessing {
  49918. /**
  49919. * Constructs a new post processing management module.
  49920. *
  49921. * @param {Renderer} renderer - A reference to the renderer.
  49922. * @param {Node<vec4>} outputNode - An optional output node.
  49923. */
  49924. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  49925. /**
  49926. * A reference to the renderer.
  49927. *
  49928. * @type {Renderer}
  49929. */
  49930. this.renderer = renderer;
  49931. /**
  49932. * A node which defines the final output of the post
  49933. * processing. This is usually the last node in a chain
  49934. * of effect nodes.
  49935. *
  49936. * @type {Node<vec4>}
  49937. */
  49938. this.outputNode = outputNode;
  49939. /**
  49940. * Whether the default output tone mapping and color
  49941. * space transformation should be enabled or not.
  49942. *
  49943. * It is enabled by default by it must be disabled when
  49944. * effects must be executed after tone mapping and color
  49945. * space conversion. A typical example is FXAA which
  49946. * requires sRGB input.
  49947. *
  49948. * When set to `false`, the app must control the output
  49949. * transformation with `RenderOutputNode`.
  49950. *
  49951. * ```js
  49952. * const outputPass = renderOutput( scenePass );
  49953. * ```
  49954. *
  49955. * @type {boolean}
  49956. */
  49957. this.outputColorTransform = true;
  49958. /**
  49959. * Must be set to `true` when the output node changes.
  49960. *
  49961. * @type {Node<vec4>}
  49962. */
  49963. this.needsUpdate = true;
  49964. const material = new NodeMaterial();
  49965. material.name = 'PostProcessing';
  49966. /**
  49967. * The full screen quad that is used to render
  49968. * the effects.
  49969. *
  49970. * @private
  49971. * @type {QuadMesh}
  49972. */
  49973. this._quadMesh = new QuadMesh( material );
  49974. }
  49975. /**
  49976. * When `PostProcessing` is used to apply post processing effects,
  49977. * the application must use this version of `render()` inside
  49978. * its animation loop (not the one from the renderer).
  49979. */
  49980. render() {
  49981. this._update();
  49982. const renderer = this.renderer;
  49983. const toneMapping = renderer.toneMapping;
  49984. const outputColorSpace = renderer.outputColorSpace;
  49985. renderer.toneMapping = NoToneMapping;
  49986. renderer.outputColorSpace = LinearSRGBColorSpace;
  49987. //
  49988. const currentXR = renderer.xr.enabled;
  49989. renderer.xr.enabled = false;
  49990. this._quadMesh.render( renderer );
  49991. renderer.xr.enabled = currentXR;
  49992. //
  49993. renderer.toneMapping = toneMapping;
  49994. renderer.outputColorSpace = outputColorSpace;
  49995. }
  49996. /**
  49997. * Frees internal resources.
  49998. */
  49999. dispose() {
  50000. this._quadMesh.material.dispose();
  50001. }
  50002. /**
  50003. * Updates the state of the module.
  50004. *
  50005. * @private
  50006. */
  50007. _update() {
  50008. if ( this.needsUpdate === true ) {
  50009. const renderer = this.renderer;
  50010. const toneMapping = renderer.toneMapping;
  50011. const outputColorSpace = renderer.outputColorSpace;
  50012. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  50013. this._quadMesh.material.needsUpdate = true;
  50014. this.needsUpdate = false;
  50015. }
  50016. }
  50017. /**
  50018. * When `PostProcessing` is used to apply post processing effects,
  50019. * the application must use this version of `renderAsync()` inside
  50020. * its animation loop (not the one from the renderer).
  50021. *
  50022. * @async
  50023. * @return {Promise} A Promise that resolves when the render has been finished.
  50024. */
  50025. async renderAsync() {
  50026. this._update();
  50027. const renderer = this.renderer;
  50028. const toneMapping = renderer.toneMapping;
  50029. const outputColorSpace = renderer.outputColorSpace;
  50030. renderer.toneMapping = NoToneMapping;
  50031. renderer.outputColorSpace = LinearSRGBColorSpace;
  50032. //
  50033. const currentXR = renderer.xr.enabled;
  50034. renderer.xr.enabled = false;
  50035. await this._quadMesh.renderAsync( renderer );
  50036. renderer.xr.enabled = currentXR;
  50037. //
  50038. renderer.toneMapping = toneMapping;
  50039. renderer.outputColorSpace = outputColorSpace;
  50040. }
  50041. }
  50042. /**
  50043. * This special type of texture is intended for compute shaders.
  50044. * It can be used to compute the data of a texture with a compute shader.
  50045. *
  50046. * Note: This type of texture can only be used with `WebGPURenderer`
  50047. * and a WebGPU backend.
  50048. *
  50049. * @augments Texture
  50050. */
  50051. class StorageTexture extends Texture {
  50052. /**
  50053. * Constructs a new storage texture.
  50054. *
  50055. * @param {number} [width=1] - The storage texture's width.
  50056. * @param {number} [height=1] - The storage texture's height.
  50057. */
  50058. constructor( width = 1, height = 1 ) {
  50059. super();
  50060. /**
  50061. * The image object which just represents the texture's dimension.
  50062. *
  50063. * @type {{width: number, height: number}}
  50064. */
  50065. this.image = { width, height };
  50066. /**
  50067. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  50068. *
  50069. * @type {number}
  50070. */
  50071. this.magFilter = LinearFilter;
  50072. /**
  50073. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  50074. *
  50075. * @type {number}
  50076. */
  50077. this.minFilter = LinearFilter;
  50078. /**
  50079. * This flag can be used for type testing.
  50080. *
  50081. * @type {boolean}
  50082. * @readonly
  50083. * @default true
  50084. */
  50085. this.isStorageTexture = true;
  50086. }
  50087. }
  50088. /**
  50089. * This special type of buffer attribute is intended for compute shaders.
  50090. * It can be used to encode draw parameters for indirect draw calls.
  50091. *
  50092. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  50093. * and a WebGPU backend.
  50094. *
  50095. * @augments StorageBufferAttribute
  50096. */
  50097. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  50098. /**
  50099. * Constructs a new storage buffer attribute.
  50100. *
  50101. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  50102. * The subsequent parameter is then obsolete.
  50103. * @param {number} itemSize - The item size.
  50104. */
  50105. constructor( count, itemSize ) {
  50106. super( count, itemSize, Uint32Array );
  50107. /**
  50108. * This flag can be used for type testing.
  50109. *
  50110. * @type {boolean}
  50111. * @readonly
  50112. * @default true
  50113. */
  50114. this.isIndirectStorageBufferAttribute = true;
  50115. }
  50116. }
  50117. /**
  50118. * A loader for loading node objects in the three.js JSON Object/Scene format.
  50119. *
  50120. * @augments Loader
  50121. */
  50122. class NodeLoader extends Loader {
  50123. /**
  50124. * Constructs a new node loader.
  50125. *
  50126. * @param {LoadingManager} [manager] - A reference to a loading manager.
  50127. */
  50128. constructor( manager ) {
  50129. super( manager );
  50130. /**
  50131. * Represents a dictionary of textures.
  50132. *
  50133. * @type {Object<string,Texture>}
  50134. */
  50135. this.textures = {};
  50136. /**
  50137. * Represents a dictionary of node types.
  50138. *
  50139. * @type {Object<string,Node.constructor>}
  50140. */
  50141. this.nodes = {};
  50142. }
  50143. /**
  50144. * Loads the node definitions from the given URL.
  50145. *
  50146. * @param {string} url - The path/URL of the file to be loaded.
  50147. * @param {Function} onLoad - Will be called when load completes.
  50148. * @param {Function} onProgress - Will be called while load progresses.
  50149. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  50150. */
  50151. load( url, onLoad, onProgress, onError ) {
  50152. const loader = new FileLoader( this.manager );
  50153. loader.setPath( this.path );
  50154. loader.setRequestHeader( this.requestHeader );
  50155. loader.setWithCredentials( this.withCredentials );
  50156. loader.load( url, ( text ) => {
  50157. try {
  50158. onLoad( this.parse( JSON.parse( text ) ) );
  50159. } catch ( e ) {
  50160. if ( onError ) {
  50161. onError( e );
  50162. } else {
  50163. console.error( e );
  50164. }
  50165. this.manager.itemError( url );
  50166. }
  50167. }, onProgress, onError );
  50168. }
  50169. /**
  50170. * Parse the node dependencies for the loaded node.
  50171. *
  50172. * @param {Object} json - The JSON definition
  50173. * @return {Object<string,Node>} A dictionary with node dependencies.
  50174. */
  50175. parseNodes( json ) {
  50176. const nodes = {};
  50177. if ( json !== undefined ) {
  50178. for ( const nodeJSON of json ) {
  50179. const { uuid, type } = nodeJSON;
  50180. nodes[ uuid ] = this.createNodeFromType( type );
  50181. nodes[ uuid ].uuid = uuid;
  50182. }
  50183. const meta = { nodes, textures: this.textures };
  50184. for ( const nodeJSON of json ) {
  50185. nodeJSON.meta = meta;
  50186. const node = nodes[ nodeJSON.uuid ];
  50187. node.deserialize( nodeJSON );
  50188. delete nodeJSON.meta;
  50189. }
  50190. }
  50191. return nodes;
  50192. }
  50193. /**
  50194. * Parses the node from the given JSON.
  50195. *
  50196. * @param {Object} json - The JSON definition
  50197. * @return {Node} The parsed node.
  50198. */
  50199. parse( json ) {
  50200. const node = this.createNodeFromType( json.type );
  50201. node.uuid = json.uuid;
  50202. const nodes = this.parseNodes( json.nodes );
  50203. const meta = { nodes, textures: this.textures };
  50204. json.meta = meta;
  50205. node.deserialize( json );
  50206. delete json.meta;
  50207. return node;
  50208. }
  50209. /**
  50210. * Defines the dictionary of textures.
  50211. *
  50212. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  50213. * @return {NodeLoader} A reference to this loader.
  50214. */
  50215. setTextures( value ) {
  50216. this.textures = value;
  50217. return this;
  50218. }
  50219. /**
  50220. * Defines the dictionary of node types.
  50221. *
  50222. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  50223. * @return {NodeLoader} A reference to this loader.
  50224. */
  50225. setNodes( value ) {
  50226. this.nodes = value;
  50227. return this;
  50228. }
  50229. /**
  50230. * Creates a node object from the given type.
  50231. *
  50232. * @param {string} type - The node type.
  50233. * @return {Node} The created node instance.
  50234. */
  50235. createNodeFromType( type ) {
  50236. if ( this.nodes[ type ] === undefined ) {
  50237. console.error( 'THREE.NodeLoader: Node type not found:', type );
  50238. return float();
  50239. }
  50240. return nodeObject( new this.nodes[ type ]() );
  50241. }
  50242. }
  50243. /**
  50244. * A special type of material loader for loading node materials.
  50245. *
  50246. * @augments MaterialLoader
  50247. */
  50248. class NodeMaterialLoader extends MaterialLoader {
  50249. /**
  50250. * Constructs a new node material loader.
  50251. *
  50252. * @param {LoadingManager} [manager] - A reference to a loading manager.
  50253. */
  50254. constructor( manager ) {
  50255. super( manager );
  50256. /**
  50257. * Represents a dictionary of node types.
  50258. *
  50259. * @type {Object<string,Node.constructor>}
  50260. */
  50261. this.nodes = {};
  50262. /**
  50263. * Represents a dictionary of node material types.
  50264. *
  50265. * @type {Object<string,NodeMaterial.constructor>}
  50266. */
  50267. this.nodeMaterials = {};
  50268. }
  50269. /**
  50270. * Parses the node material from the given JSON.
  50271. *
  50272. * @param {Object} json - The JSON definition
  50273. * @return {NodeMaterial}. The parsed material.
  50274. */
  50275. parse( json ) {
  50276. const material = super.parse( json );
  50277. const nodes = this.nodes;
  50278. const inputNodes = json.inputNodes;
  50279. for ( const property in inputNodes ) {
  50280. const uuid = inputNodes[ property ];
  50281. material[ property ] = nodes[ uuid ];
  50282. }
  50283. return material;
  50284. }
  50285. /**
  50286. * Defines the dictionary of node types.
  50287. *
  50288. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  50289. * @return {NodeLoader} A reference to this loader.
  50290. */
  50291. setNodes( value ) {
  50292. this.nodes = value;
  50293. return this;
  50294. }
  50295. /**
  50296. * Defines the dictionary of node material types.
  50297. *
  50298. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  50299. * @return {NodeLoader} A reference to this loader.
  50300. */
  50301. setNodeMaterials( value ) {
  50302. this.nodeMaterials = value;
  50303. return this;
  50304. }
  50305. /**
  50306. * Creates a node material from the given type.
  50307. *
  50308. * @param {string} type - The node material type.
  50309. * @return {Node} The created node material instance.
  50310. */
  50311. createMaterialFromType( type ) {
  50312. const materialClass = this.nodeMaterials[ type ];
  50313. if ( materialClass !== undefined ) {
  50314. return new materialClass();
  50315. }
  50316. return super.createMaterialFromType( type );
  50317. }
  50318. }
  50319. /**
  50320. * A special type of object loader for loading 3D objects using
  50321. * node materials.
  50322. *
  50323. * @augments ObjectLoader
  50324. */
  50325. class NodeObjectLoader extends ObjectLoader {
  50326. /**
  50327. * Constructs a new node object loader.
  50328. *
  50329. * @param {LoadingManager} [manager] - A reference to a loading manager.
  50330. */
  50331. constructor( manager ) {
  50332. super( manager );
  50333. /**
  50334. * Represents a dictionary of node types.
  50335. *
  50336. * @type {Object<string,Node.constructor>}
  50337. */
  50338. this.nodes = {};
  50339. /**
  50340. * Represents a dictionary of node material types.
  50341. *
  50342. * @type {Object<string,NodeMaterial.constructor>}
  50343. */
  50344. this.nodeMaterials = {};
  50345. /**
  50346. * A reference to hold the `nodes` JSON property.
  50347. *
  50348. * @private
  50349. * @type {?Object}
  50350. */
  50351. this._nodesJSON = null;
  50352. }
  50353. /**
  50354. * Defines the dictionary of node types.
  50355. *
  50356. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  50357. * @return {NodeObjectLoader} A reference to this loader.
  50358. */
  50359. setNodes( value ) {
  50360. this.nodes = value;
  50361. return this;
  50362. }
  50363. /**
  50364. * Defines the dictionary of node material types.
  50365. *
  50366. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  50367. * @return {NodeObjectLoader} A reference to this loader.
  50368. */
  50369. setNodeMaterials( value ) {
  50370. this.nodeMaterials = value;
  50371. return this;
  50372. }
  50373. /**
  50374. * Parses the node objects from the given JSON.
  50375. *
  50376. * @param {Object} json - The JSON definition
  50377. * @param {Function} onLoad - The onLoad callback function.
  50378. * @return {Object3D}. The parsed 3D object.
  50379. */
  50380. parse( json, onLoad ) {
  50381. this._nodesJSON = json.nodes;
  50382. const data = super.parse( json, onLoad );
  50383. this._nodesJSON = null; // dispose
  50384. return data;
  50385. }
  50386. /**
  50387. * Parses the node objects from the given JSON and textures.
  50388. *
  50389. * @param {Object} json - The JSON definition
  50390. * @param {Object<string,Texture>} textures - The texture library.
  50391. * @return {Object<string,Node>}. The parsed nodes.
  50392. */
  50393. parseNodes( json, textures ) {
  50394. if ( json !== undefined ) {
  50395. const loader = new NodeLoader();
  50396. loader.setNodes( this.nodes );
  50397. loader.setTextures( textures );
  50398. return loader.parseNodes( json );
  50399. }
  50400. return {};
  50401. }
  50402. /**
  50403. * Parses the node objects from the given JSON and textures.
  50404. *
  50405. * @param {Object} json - The JSON definition
  50406. * @param {Object<string,Texture>} textures - The texture library.
  50407. * @return {Object<string,NodeMaterial>}. The parsed materials.
  50408. */
  50409. parseMaterials( json, textures ) {
  50410. const materials = {};
  50411. if ( json !== undefined ) {
  50412. const nodes = this.parseNodes( this._nodesJSON, textures );
  50413. const loader = new NodeMaterialLoader();
  50414. loader.setTextures( textures );
  50415. loader.setNodes( nodes );
  50416. loader.setNodeMaterials( this.nodeMaterials );
  50417. for ( let i = 0, l = json.length; i < l; i ++ ) {
  50418. const data = json[ i ];
  50419. materials[ data.uuid ] = loader.parse( data );
  50420. }
  50421. }
  50422. return materials;
  50423. }
  50424. }
  50425. /**
  50426. * In earlier three.js versions, clipping was defined globally
  50427. * on the renderer or on material level. This special version of
  50428. * `THREE.Group` allows to encode the clipping state into the scene
  50429. * graph. Meaning if you create an instance of this group, all
  50430. * descendant 3D objects will be affected by the respective clipping
  50431. * planes.
  50432. *
  50433. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  50434. *
  50435. * @augments Group
  50436. */
  50437. class ClippingGroup extends Group {
  50438. /**
  50439. * Constructs a new clipping group.
  50440. */
  50441. constructor() {
  50442. super();
  50443. /**
  50444. * This flag can be used for type testing.
  50445. *
  50446. * @type {boolean}
  50447. * @readonly
  50448. * @default true
  50449. */
  50450. this.isClippingGroup = true;
  50451. /**
  50452. * An array with clipping planes.
  50453. *
  50454. * @type {Array<Plane>}
  50455. */
  50456. this.clippingPlanes = [];
  50457. /**
  50458. * Whether clipping should be enabled or not.
  50459. *
  50460. * @type {boolean}
  50461. * @default true
  50462. */
  50463. this.enabled = true;
  50464. /**
  50465. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  50466. *
  50467. * @type {boolean}
  50468. * @default false
  50469. */
  50470. this.clipIntersection = false;
  50471. /**
  50472. * Whether shadows should be clipped or not.
  50473. *
  50474. * @type {boolean}
  50475. * @default false
  50476. */
  50477. this.clipShadows = false;
  50478. }
  50479. }
  50480. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号